pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
27,279,740
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>
3,061,186
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>
38,421,784
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>
20,211,559
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>
33,905,192
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>
21,305,099
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>
30,850,931
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>
15,185,127
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>
37,892,431
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>
35,508,423
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>
36,916,053
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>
15,252,037
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>
776,966
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>
8,187,781
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>
23,369,426
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>
35,271,814
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>
25,096,495
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>
27,737,330
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>
10,235,309
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>
6,181,671
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>
39,183,961
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>
12,619,745
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>
26,699,669
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>
10,056,284
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>
10,874,666
0
<p><code>preg_replace("|[^abcdef]|", '')</code>? (where abcdef are the characters to allow)</p>
1,732,216
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>
33,084,184
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>
11,772,716
0
<pre><code>var img = new Image (); img.onload = function () { $('body').css('background','url(image.png)'); }; img.src = src; </code></pre>
19,683,021
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>
3,225,534
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>
30,274,264
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>
26,616,859
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>
34,711,569
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>
8,963,180
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>
12,920,429
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>
7,346,621
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>
3,653,698
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>
38,733,233
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>
39,278,406
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>
19,876,693
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>
25,122,613
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>
38,456,604
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>
2,444,704
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>
8,767,871
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>
18,036,788
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>
24,629,115
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>
15,224,268
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>
10,796,671
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>
1,493,516
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>
17,407,409
0
<p>This is the feature that lets you to auto-merge different Auth Providers into the same account in ServiceStack.</p>
997,954
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>
40,839,019
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>
20,732,858
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>
38,647,215
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>
861,109
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>
14,920,406
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>
37,130,244
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>
38,865,180
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>
38,953,330
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>
6,520,463
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>
11,430,967
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>
34,460,204
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>
17,019,288
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>
7,291,047
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>
12,801,638
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>
6,257,465
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>
38,445,290
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>
21,940,386
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>
38,052,792
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>
5,765,020
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>
12,465,639
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>
40,320,668
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>
14,770,375
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>
22,303,615
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>
9,390,915
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>
18,656,040
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>
33,707,795
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>
9,032,715
0
<p>Try <a href="http://php.net/utf8-decode" rel="nofollow"><code>utf8_decode()</code></a> instead.</p>
1,481,416
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>
8,104,034
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>
15,766,402
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>
23,416,033
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>
28,758,654
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>
1,748,008
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>
7,216,628
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>
27,595,996
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>
37,531,987
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>
32,118,245
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>
35,259,544
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>
4,460,050
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>
35,434,134
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>
39,850,264
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>
26,747,396
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>
11,112,006
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>
36,633,309
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>
4,245,046
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>
21,611,060
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>
7,786,668
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>
17,917,378
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>
35,176,703
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>