pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
37,476,824
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>
9,891,660
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>
1,443,584
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>
17,218,114
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>
38,528,723
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>
10,692,864
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>
3,051,992
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>
26,181,981
0
DIDO is a MATLAB optimal control tool for solving general-purpose hybrid optimal control problems.
8,762,863
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>
5,229,988
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>
39,630,787
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>
25,322,918
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>
17,497,276
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>
22,356,018
0
<p>try this out:-</p> <p>install <code>ruby-nmap</code> gem</p> <pre><code> gem install ruby-nmap </code></pre>
945,344
0
<p>Look into <a href="http://msdn.microsoft.com/en-us/library/ms712704(VS.85).aspx" rel="nofollow noreferrer">Multimedia Timers</a>.</p>
21,654,981
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>
4,245,544
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>
564,273
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>
20,262,609
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>
21,742,461
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>
35,662,195
0
<p>My suggestion is:</p> <pre><code>get_foo = re.compile(r'([^\)]*\)?)').findall foo = get_foo(s1) # And so on </code></pre>
38,945,859
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>
30,512,313
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>
3,596,523
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>
34,647,436
0
<pre><code>.*(=|&lt;|&gt;|!=)\s*(-?\d+|'[^']+') </code></pre> <p><a href="https://regex101.com/r/rX1pW3/1" rel="nofollow">regex101</a></p>
9,104,335
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>
595,878
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>
26,706,176
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>
29,186,154
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>
335,669
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>
280,727
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>
33,085,823
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>
9,936,386
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>
26,542,261
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>
2,584,307
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>
32,734,951
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>
9,914,065
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>
6,685,784
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>
30,701,258
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>
31,724,510
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>
4,277,726
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>
38,392,934
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>
8,924,602
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>
30,604,353
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>
35,613,011
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>
26,409,494
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>
24,066,737
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>
36,658,591
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>
36,631,453
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>
35,066,552
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>
1,367,070
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>
28,800,060
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>
33,896,449
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>
39,388,179
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>
29,020,353
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>
12,875,641
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>
20,959,928
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>
4,701,510
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>
14,556,463
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>
27,060,810
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>
4,312,981
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>
1,279,656
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>
35,760,975
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>
13,639,858
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>
17,153,661
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>
4,229,153
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>
30,437,523
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>
35,887,372
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>
3,166,526
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>
16,628,523
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>
11,783,391
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>
13,601,342
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>
9,041,967
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>
14,750,314
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>
23,259,344
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>
899,839
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>
33,421,480
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>
4,119,323
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>
9,564,683
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>
27,521,806
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>
14,590,175
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>
34,712,258
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>
28,843,800
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>
16,310,394
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>
20,674,738
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>
18,965,975
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>
12,757,460
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 [email protected]:heroku_app_name.git (fetch) heroku [email protected]:heroku_app_name.git (push) origin [email protected]:your_github_org/repo_name.git (fetch) origin [email protected]: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 [email protected]: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>
16,644,830
0
<p>Try enclosing them in back-ticks like </p> <pre><code>ORDER BY `Full Name` ASC </code></pre> <p>HTH</p>
35,999,918
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>
30,827,203
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>
9,378,560
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>
4,512,892
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>
6,662,565
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>
5,467,038
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>
12,699,006
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>
29,700,784
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>
11,525,854
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>
29,849,985
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>
1,176,932
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>
31,177,507
0
<p>what about commit. Is autocommit on?</p> <p>or add 'commit' after your insert statement</p>