id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
307,438
How can I tell when a MySQL table was last updated?
<p>In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated.</p> <p>What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value?</p>
307,488
17
1
null
2008-11-21 00:48:59.003 UTC
70
2021-11-09 14:49:33.497 UTC
2014-10-29 17:09:14.667 UTC
Alnitak
445,131
RaGE
39,474
null
1
205
mysql|sql
342,204
<p>In later versions of MySQL you can use the <code>information_schema</code> database to tell you when another table was updated:</p> <pre><code>SELECT UPDATE_TIME FROM information_schema.tables WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tabname' </code></pre> <p>This does of course mean opening a connection to the database.</p> <hr> <p>An alternative option would be to "touch" a particular file whenever the MySQL table is updated:</p> <p>On database updates:</p> <ul> <li>Open your timestamp file in <code>O_RDRW</code> mode</li> <li><code>close</code> it again</li> </ul> <p>or alternatively</p> <ul> <li>use <a href="http://us3.php.net/manual/en/function.touch.php" rel="noreferrer"><code>touch()</code></a>, the PHP equivalent of the <code>utimes()</code> function, to change the file timestamp.</li> </ul> <p>On page display:</p> <ul> <li>use <code>stat()</code> to read back the file modification time.</li> </ul>
359,424
Detach (move) subdirectory into separate Git repository
<p>I have a <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> repository which contains a number of subdirectories. Now I have found that one of the subdirectories is unrelated to the other and should be detached to a separate repository.</p> <p>How can I do this while keeping the history of the files within the subdirectory?</p> <p>I guess I could make a clone and remove the unwanted parts of each clone, but I suppose this would give me the complete tree when checking out an older revision etc. This might be acceptable, but I would prefer to be able to pretend that the two repositories doesn't have a shared history.</p> <p>Just to make it clear, I have the following structure:</p> <pre><code>XYZ/ .git/ XY1/ ABC/ XY2/ </code></pre> <p>But I would like this instead:</p> <pre><code>XYZ/ .git/ XY1/ XY2/ ABC/ .git/ ABC/ </code></pre>
359,759
26
4
null
2008-12-11 13:57:03.617 UTC
1,210
2021-07-10 12:13:06.293 UTC
2016-08-01 08:25:13.43 UTC
null
2,790,048
matli
23,896
null
1
1,920
git|git-subtree|git-filter-branch
299,823
<p><strong>Update</strong>: This process is so common, that the git team made it much simpler with a new tool, <code>git subtree</code>. See here: <a href="https://stackoverflow.com/questions/359424/detach-subdirectory-into-separate-git-repository/17864475#17864475">Detach (move) subdirectory into separate Git repository</a></p> <hr> <p>You want to clone your repository and then use <code>git filter-branch</code> to mark everything but the subdirectory you want in your new repo to be garbage-collected.</p> <ol> <li><p>To clone your local repository:</p> <pre><code>git clone /XYZ /ABC </code></pre> <p>(Note: the repository will be cloned using hard-links, but that is not a problem since the hard-linked files will not be modified in themselves - new ones will be created.)</p></li> <li><p>Now, let us preserve the interesting branches which we want to rewrite as well, and then remove the origin to avoid pushing there and to make sure that old commits will not be referenced by the origin:</p> <pre><code>cd /ABC for i in branch1 br2 br3; do git branch -t $i origin/$i; done git remote rm origin </code></pre> <p>or for all remote branches:</p> <pre><code>cd /ABC for i in $(git branch -r | sed "s/.*origin\///"); do git branch -t $i origin/$i; done git remote rm origin </code></pre></li> <li><p>Now you might want to also remove tags which have no relation with the subproject; you can also do that later, but you might need to prune your repo again. I did not do so and got a <code>WARNING: Ref 'refs/tags/v0.1' is unchanged</code> for all tags (since they were all unrelated to the subproject); additionally, after removing such tags more space will be reclaimed. Apparently <code>git filter-branch</code> should be able to rewrite other tags, but I could not verify this. If you want to remove all tags, use <code>git tag -l | xargs git tag -d</code>.</p></li> <li><p>Then use filter-branch and reset to exclude the other files, so they can be pruned. Let's also add <code>--tag-name-filter cat --prune-empty</code> to remove empty commits and to rewrite tags (note that this will have to strip their signature):</p> <pre><code>git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC -- --all </code></pre> <p>or alternatively, to only rewrite the HEAD branch and ignore tags and other branches:</p> <pre><code>git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter ABC HEAD </code></pre></li> <li><p>Then delete the backup reflogs so the space can be truly reclaimed (although now the operation is destructive)</p> <pre><code>git reset --hard git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d git reflog expire --expire=now --all git gc --aggressive --prune=now </code></pre> <p>and now you have a local git repository of the ABC sub-directory with all its history preserved. </p></li> </ol> <p>Note: For most uses, <code>git filter-branch</code> should indeed have the added parameter <code>-- --all</code>. Yes that's really <kbd>-</kbd><kbd>-</kbd><kbd>space</kbd><kbd>-</kbd><kbd>-</kbd> <code>all</code>. This needs to be the last parameters for the command. As Matli discovered, this keeps the project branches and tags included in the new repo.</p> <p>Edit: various suggestions from comments below were incorporated to make sure, for instance, that the repository is actually shrunk (which was not always the case before).</p>
749,796
Pretty printing XML in Python
<p>What is the best way (or are the various ways) to pretty print XML in Python?</p>
1,206,856
27
0
null
2009-04-15 00:05:41.433 UTC
113
2022-06-07 10:23:05.873 UTC
2019-06-21 13:45:27.38 UTC
null
604,687
null
16,584
null
1
511
python|xml|pretty-print
488,367
<pre><code>import xml.dom.minidom dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string) pretty_xml_as_string = dom.toprettyxml() </code></pre>
632,742
How can I avoid running ActiveRecord callbacks?
<p>I have some models that have after_save callbacks. Usually that's fine, but in some situations, like when creating development data, I want to save the models without having the callbacks run. Is there a simple way to do that? Something akin to...</p> <pre><code>Person#save( :run_callbacks =&gt; false ) </code></pre> <p>or</p> <pre><code>Person#save_without_callbacks </code></pre> <p>I looked in the Rails docs and didn't find anything. However in my experience the Rails docs don't always tell the whole story.</p> <p>UPDATE</p> <p>I found <a href="http://web.archive.org/web/20120701221754/http://blog.viarails.net/2009/1/29/disabling-callbacks-in-an-activerecord-data-migration" rel="noreferrer">a blog post</a> that explains how you can remove callbacks from a model like this:</p> <pre><code>Foo.after_save.clear </code></pre> <p>I couldn't find where that method is documented but it seems to work.</p>
633,330
28
5
null
2009-03-10 23:52:22.537 UTC
61
2021-05-26 08:57:30.493 UTC
2018-08-28 06:11:22.48 UTC
Ethan
2,262,149
Ethan
42,595
null
1
158
ruby-on-rails|ruby|rails-activerecord
125,009
<p>This solution is Rails 2 only.</p> <p>I just investigated this and I think I have a solution. There are two ActiveRecord private methods that you can use:</p> <pre><code>update_without_callbacks create_without_callbacks </code></pre> <p>You're going to have to use send to call these methods. examples:</p> <pre><code>p = Person.new(:name =&gt; 'foo') p.send(:create_without_callbacks) p = Person.find(1) p.send(:update_without_callbacks) </code></pre> <p>This is definitely something that you'll only really want to use in the console or while doing some random tests. Hope this helps!</p>
250,984
Do I really need version control?
<p>I read all over the Internet (various sites and blogs) about version control. How great it is and how all developers NEED to use it because it is very useful.</p> <p>Here is the question: do I really need this? I'm a front-end developer (usually just HTML/CSS/JavaScript) and I NEVER had a problem like "Wow, my files from yesterday!". I've tried to use it, installed <a href="http://en.wikipedia.org/wiki/Subversion_%28software%29" rel="nofollow noreferrer">Subversion</a> and <a href="http://en.wikipedia.org/wiki/TortoiseSVN" rel="nofollow noreferrer">TortoiseSVN</a>, I understand the concept behind version control but... I can't use it (weird for me).</p> <p>OK, so... Is that bad? I usually work alone (freelancer) and I had no client that asked me to use Subversion (but it never is too late for this, right?). So, should I start and struggle to learn to use Subversion (or something similar?) Or it's just a waste of time?</p> <hr> <p>Related question: <a href="https://stackoverflow.com/questions/132520/good-excuses-not-to-use-version-control#132522">Good excuses NOT to use version control</a>.</p>
251,121
30
0
2010-07-31 00:29:10.237 UTC
2008-10-30 17:14:43.9 UTC
31
2011-10-03 21:16:23.747 UTC
2017-05-23 12:30:28.283 UTC
Bert Huijben
-1
Staicu Ionut
23,810
null
1
47
svn|version-control
6,488
<p>Here's a scenario that may illustrate the usefulness of source control even if you work alone.</p> <blockquote> <p>Your client asks you to implement an ambitious modification to the website. It'll take you a couple of weeks, and involve edits to many pages. You get to work.</p> <p>You're 50% done with this task when the client calls and tells you to drop what you're doing to make an urgent but more minor change to the site. You're not done with the larger task, so it's not ready to go live, and the client can't wait for the smaller change. But he also wants the minor change to be merged into your work for the larger change.</p> <p>Maybe you are working on the large task in a separate folder containing a copy of the website. Now you have to figure out how to do the minor change in a way that can be deployed quickly. You work furiously and get it done. The client calls back with further refinement requests. You do this too and deploy it. All is well.</p> <p>Now you have to merge it into the work in progress for the major change. What did you change for the urgent work? You were working too fast to keep notes. And you can't just diff the two directories easily now that both have changes relative to the baseline you started from.</p> </blockquote> <p>The above scenario shows that source control can be a great tool, even if you work solo. </p> <ul> <li>You can use branches to work on longer-term tasks and then merge the branch back into the main line when it's done.</li> <li>You can compare whole sets of files to other branches or to past revisions to see what's different. </li> <li>You can track work over time (which is great for reporting and invoicing by the way).</li> <li>You can recover any revision of any file based on date or on a milestone that you defined.</li> </ul> <p>For solo work, Subversion or Git is recommended. Anyone is free to prefer one or the other, but either is clearly better than not using any version control. Good books are "<a href="http://www.pragprog.com/titles/svn2/pragmatic-version-control-using-subversion" rel="nofollow noreferrer">Pragmatic Version Control using Subversion, 2nd Edition</a>" by Mike Mason or "<a href="http://www.pragprog.com/titles/tsgit/pragmatic-version-control-using-git" rel="nofollow noreferrer">Pragmatic Version Control Using Git</a>" by Travis Swicegood.</p>
123,999
How can I tell if a DOM element is visible in the current viewport?
<p>Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the <strong>viewport</strong>)?</p> <p>(The question refers to Firefox.)</p>
125,106
30
8
null
2008-09-23 21:24:56.057 UTC
557
2022-01-27 15:06:22.09 UTC
2019-12-15 04:44:59.777 UTC
Itamar Benzaken
63,550
Itamar Benzaken
21,290
null
1
1,195
javascript|html|firefox|dom|browser
732,615
<p><strong>Update:</strong> Time marches on and so have our browsers. <strong>This technique is no longer recommended</strong> and you should use <a href="https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433">Dan's solution</a> if you do not need to support version of Internet&nbsp;Explorer before 7.</p> <p><strong>Original solution (now outdated):</strong></p> <p>This will check if the element is entirely visible in the current viewport:</p> <pre><code>function elementInViewport(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top &gt;= window.pageYOffset &amp;&amp; left &gt;= window.pageXOffset &amp;&amp; (top + height) &lt;= (window.pageYOffset + window.innerHeight) &amp;&amp; (left + width) &lt;= (window.pageXOffset + window.innerWidth) ); } </code></pre> <p>You could modify this simply to determine if any part of the element is visible in the viewport:</p> <pre><code>function elementInViewport2(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top &lt; (window.pageYOffset + window.innerHeight) &amp;&amp; left &lt; (window.pageXOffset + window.innerWidth) &amp;&amp; (top + height) &gt; window.pageYOffset &amp;&amp; (left + width) &gt; window.pageXOffset ); } </code></pre>
6,443,428
Can't find file: './ci/users.frm' (errno: 13)
<p>I installed LAMP on Ubuntu 11.04 and copy project from Windows. PHP directory (/ci/) to var/www/ and MySQL project directory (/ci/) to var/lib/mysql/</p> <p>Full text of error that i get:</p> <pre><code>A Database Error Occurred Error Number: 1017 Can't find file: './ci/users.frm' (errno: 13) SELECT COUNT(*) AS `numrows` FROM (`users`) WHERE `email` = 'admin@localsite.com' </code></pre> <p>I googled that its permission problem, but don't know what do next.</p> <pre><code>Log from /var/log/mysql/error.log: 110622 19:27:21 [ERROR] /usr/sbin/mysqld: Can't find file: './ci/users.frm' (errno: 13) </code></pre>
6,444,519
7
2
null
2011-06-22 16:41:07.98 UTC
3
2022-08-05 16:11:25.46 UTC
2016-06-10 08:26:06.52 UTC
null
5,907,870
null
445,450
null
1
12
mysql|ubuntu|permissions
43,860
<p>Permissions problem meaning the permissions on the file. MySQL probably can't read it. Just change the owner and group to mysql and it should work.</p> <pre><code>chown mysql:mysql /var/lib/mysql/ci/* </code></pre>
6,440,187
Get last path part from NSString
<p>Hi all i want extract the last part from string which is a four digit number '03276' i:e <code>http://www.abc.com/news/read/welcome-new-gig/03276</code></p> <p>how can i do that.</p>
6,440,299
7
0
null
2011-06-22 12:53:42.46 UTC
9
2013-02-19 01:01:26.657 UTC
2013-02-19 01:01:26.657 UTC
null
21,804
null
517,047
null
1
29
iphone|nsstring
28,070
<p>You can also use </p> <pre><code>NSString *sub = [@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent]; </code></pre>
15,607,252
SignalR support in .NET 4
<p>Does SignalR support .NET 4.0. Or is it support only from .NET 4.5 upwards. Is there any link which provides with minimum requirements for SignalR. </p>
17,941,453
7
0
null
2013-03-25 03:40:47.547 UTC
10
2017-08-09 07:09:36.333 UTC
2013-03-25 03:47:28.113 UTC
null
340,046
null
340,046
null
1
25
asp.net|signalr
26,964
<p>This is not the case any more, and the 2.x releases require .NET 4.5. <a href="https://github.com/SignalR/SignalR/issues/1723" rel="noreferrer">https://github.com/SignalR/SignalR/issues/1723</a></p>
15,657,687
Twig date difference
<p>I've got an entity with a starting date and an ending date.</p> <p>Is it possible to get the difference in time between them by using twig?</p>
27,205,095
4
0
null
2013-03-27 11:25:52.397 UTC
5
2021-05-06 14:53:50.14 UTC
2013-06-24 20:07:50.377 UTC
null
881,229
null
2,087,576
null
1
34
datetime|twig|datediff
54,601
<p>Since PHP 5.3 There is another option without to write an extension.</p> <p>This example show how to calc the plural day/days</p> <pre><code>{# endDate and startDate are strings or DateTime objects #} {% set difference = date(endDate).diff(date(startDate)) %} {% set leftDays = difference.days %} {% if leftDays == 1 %} 1 day {% else %} {{ leftDays }} days {% endif %} </code></pre> <p>Explanation:</p> <p>PHP 5.3 <code>DateTime</code> object has <a href="http://php.net/manual/en/datetime.diff.php"><code>diff()</code></a> method which return a <a href="http://php.net/manual/en/class.dateinterval.php"><code>DateInterval</code></a> object with the result difference between <code>endDate</code> and <code>beginDate</code> Twig </p> <p>Twig <a href="http://twig.sensiolabs.org/doc/functions/date.html"><code>date</code></a> function always return a <code>DateTime</code> object so we can call <code>diff</code> method </p> <p>Finally we can access to the properties of the <code>DateInterval</code> object or format it with the Twig <code>date</code> filter.</p> <p>Note: There is no need of wrap <code>endDate</code> or <code>startDate</code> with the <code>date</code> function if the variable is already a <code>DateTime</code> object.</p> <p>Note2: <code>DateTime</code> is used here as a synonym of <code>DateTimeInterface</code>.</p>
15,631,137
MySQL concatenation operator
<p>I don't know concatenation operator for MySQL.</p> <p>I have tried this code for concatenation:</p> <pre><code>SELECT vend_name || ' (' || vend_country || ')' FROM Vendors ORDER BY vend_name; </code></pre> <p>But it didn't work. Which operator should I use to concatenate strings?</p>
15,631,172
6
3
null
2013-03-26 06:58:20.147 UTC
3
2019-04-16 15:14:37.133 UTC
2018-09-21 17:09:45.323 UTC
null
1,704,458
null
2,201,462
null
1
50
mysql|sql|concatenation
62,854
<p>You were using ORACLE type of concatenation. MySQL's Should be </p> <pre><code> SELECT CONCAT(vend_name, '(', vend_country, ')') </code></pre> <p>Call the <code>CONCAT()</code> function and separate your values with commas.</p>
46,466,167
Laravel 5.5 ajax call 419 (unknown status)
<p>I do an ajax call but I keep getting this error:</p> <blockquote> <p>419 (unknown status)</p> </blockquote> <p>No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.</p> <p>my call:</p> <pre><code>$('.company-selector li &gt; a').click(function(e) { e.preventDefault(); var companyId = $(this).data("company-id"); $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: '/fetch-company/' + companyId, dataType : 'json', type: 'POST', data: {}, contentType: false, processData: false, success:function(response) { console.log(response); } }); }); </code></pre> <p>My route:</p> <pre><code>Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany'); </code></pre> <p>My controller method</p> <pre><code>/** * Fetches a company * * @param $companyId * * @return array */ public function fetchCompany($companyId) { $company = Company::where('id', $companyId)-&gt;first(); return response()-&gt;json($company); } </code></pre> <p>The ultimate goal is to display something from the response in a html element.</p>
46,466,616
21
9
null
2017-09-28 09:54:08.933 UTC
37
2022-07-04 20:50:07.353 UTC
null
null
null
null
8,639,310
null
1
181
php|jquery|ajax|laravel
285,366
<p>Use this in the head section: </p> <pre><code>&lt;meta name="csrf-token" content="{{ csrf_token() }}"&gt; </code></pre> <p>and get the csrf token in ajax:</p> <pre><code>$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); </code></pre> <p>Please refer Laravel Documentation <a href="https://laravel.com/docs/5.6/csrf" rel="noreferrer">csrf_token</a></p>
33,706,528
Is it safe to realloc memory allocated with new?
<p>From what is written <a href="https://stackoverflow.com/questions/1350819/c-free-store-vs-heap">here</a>, <code>new</code> allocates in <em>free store</em> while <code>malloc</code> uses <em>heap</em> and the two terms often mean the same thing.</p> <p>From what is written <a href="http://www.cplusplus.com/reference/cstdlib/realloc/" rel="noreferrer">here</a>, <code>realloc</code> may move the memory block to a new location. If free store and heap are two different memory spaces, does it mean any problem then?</p> <p>Specifically I'd like to know if it is safe to use</p> <pre><code>int* data = new int[3]; // ... int* mydata = (int*)realloc(data,6*sizeof(int)); </code></pre> <p>If not, is there any other way to <code>realloc</code> memory allocated with <code>new</code> safely? I could allocate new area and <code>memcpy</code> the contents, but from what I understand <code>realloc</code> may use the same area if possible.</p>
33,706,568
9
12
null
2015-11-14 08:25:02.673 UTC
12
2015-11-17 12:54:25.273 UTC
2017-05-23 12:34:05.947 UTC
null
-1
null
343,721
null
1
38
c++|memory-management|realloc
14,512
<p>You can only <code>realloc</code> that which has been allocated via <code>malloc</code> (or family, like <code>calloc</code>).</p> <p>That's because the underlying data structures that keep track of free and used areas of memory, can be quite different.</p> <p>It's <em>likely</em> but by no means guaranteed that C++ <code>new</code> and C <code>malloc</code> use the same underlying allocator, in which case <code>realloc</code> could work for both. But formally that's in UB-land. And in practice it's just needlessly risky.</p> <hr> <p>C++ does not offer functionality corresponding to <code>realloc</code>.</p> <p>The closest is the automatic reallocation of (the internal buffers of) containers like <code>std::vector</code>.</p> <p>The C++ containers suffer from being designed in a way that excludes use of <code>realloc</code>.</p> <hr> <p>Instead of the presented code</p> <pre><code>int* data = new int[3]; //... int* mydata = (int*)realloc(data,6*sizeof(int)); </code></pre> <p>&hellip; do this:</p> <pre><code>vector&lt;int&gt; data( 3 ); //... data.resize( 6 ); </code></pre> <p>However, if you absolutely need the general efficiency of <code>realloc</code>, and if you have to accept <code>new</code> for the original allocation, then your only recourse for efficiency is to use compiler-specific means, knowledge that <code>realloc</code> is safe with this compiler.</p> <p>Otherwise, if you absolutely need the general efficiency of <code>realloc</code> but is not forced to accept <code>new</code>, then you can use <code>malloc</code> and <code>realloc</code>. Using smart pointers then lets you get much of the same safety as with C++ containers.</p>
35,512,648
Adding a timer to my program (javafx)
<p>I am trying to add a timer to my program. I've tried calling upon java.util.Timer but it frustrates me as i do not completely understand the concepts behind it. I have just done a semester of coding in python but this is an entirely different level to me.</p> <pre><code>import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import javafx.stage.Stage; import java.awt.event.ActionListener; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class main extends Application implements EventHandler&lt;ActionEvent&gt;{ Button button; Button button2; Counter counter = new Counter(0); Counter timecounter = new Counter(0); Text text_counter = new Text(counter.S_count.get()); Text text_timecounter = new Text(timecounter.S_count.get()); Date currdate = new Date(); int currsec = currdate.getSeconds(); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Counter Window"); button = new Button(); button2 = new Button(); button.setText("Reset"); button.setOnAction(this); button2.setText("Tick"); button2.setOnAction(this); button.setTranslateY(-120); button2.setTranslateY(-80); text_counter.textProperty().bind(counter.S_count); text_timecounter.textProperty().bind(timecounter.S_count); text_timecounter.setTranslateX(-100); StackPane layout = new StackPane(); layout.getChildren().add(button); layout.getChildren().add(button2); layout.getChildren().add(text_counter); layout.getChildren().add(text_timecounter); Scene scene = new Scene(layout, 360,280); primaryStage.setScene(scene); primaryStage.show(); } @Override public void handle(ActionEvent event) { if(event.getSource()==button){ counter.Reset(); } if(event.getSource()==button2){ counter.Tick(); } } } </code></pre> <p>I built a program in python with a main loop. I was thinking of a "dirty" way of doing it by adding a check to the loop that checks if the seconds of the current date has changed and if it has, increment a value by one. </p> <pre><code>class timerclass { Timer timer1; private int timecounter = 0; TimerTask Task1 = new TimerTask() { @Override public void run() { setTimecounter(getTimecounter()+1); } }; public timerclass(){ timer1 = new Timer(); } public int getTimecounter() { return timecounter; } public void setTimecounter(int timecounter) { this.timecounter = timecounter; } } </code></pre> <p>This is how far i've come creating a new timer. I understood that I have to create a task and schedule it to the timer but I don't have the slightest clue how...</p> <p>How would I go about this? Sorry for the inconvieniences.</p>
35,512,859
1
5
null
2016-02-19 18:43:55.307 UTC
3
2017-12-21 13:56:09.137 UTC
null
null
null
null
3,327,206
null
1
6
java|javafx|timer|counter
54,960
<p><code>Timer</code> is used to <strong>schedule tasks</strong>.. So where do you write those tasks?? Well you have to write those tasks in a <code>TimerTask</code> class...</p> <p>Confused ? Let me break it down,</p> <pre><code>Timer timer = new Timer(); </code></pre> <p>Now you have created a object of Timer class .. Now you have to do some task right? So to do that create an object of <code>TimerTask</code>.</p> <pre><code>TimerTask task = new TimerTask() { public void run() { //The task you want to do } }; </code></pre> <p>Now you have created a task where you should be defining the tasks you want to do inside the run method..</p> <p>Why have I written a TimerTask class itself?? Thats because TimerTask is a abstract class with three methods.. So you need to define whichever method you want to use..</p> <p>Now scheduling the task</p> <pre><code>timer.schedule(task,5000l); </code></pre> <p><strong>Note the 'l' after 5000. It is to denote long data type because the <code>schedule</code> method is defined as</strong> </p> <p><code>void schedule(TimerTask task,long milliseconds)</code></p> <p>For further reference</p> <p><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html" rel="noreferrer">https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html</a></p> <p><a href="https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html" rel="noreferrer">https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html</a></p>
13,676,714
Command Prompt "Net View System Error 6118"
<p>When I try to use "net view" in command prompt, I get an error code 6118. What does this mean, and how can I fix it? Thanks, Nick.</p>
13,676,747
1
0
null
2012-12-03 03:22:05.77 UTC
3
2012-12-04 07:48:24.917 UTC
null
null
null
null
1,588,826
null
1
10
windows|command-line
91,976
<p>6118 means The list of servers for this workgroup is not currently available, mostly it is due to the firewall protection blocks the SMB.</p> <p>You can check as following steps</p> <ol> <li>first check each pc is in the same workgroup.</li> <li>disable the firewall and virus protect in each PC. </li> <li>Ping PC2 from PC1 to ensure the network is ok </li> <li>net view \PC2 from PC1 to check if it is ok. </li> </ol>
13,461,989
P/Invoke to dynamically loaded library on Mono
<p>I'm writing a cross-platform .NET library that uses some unmanaged code. In the static constructor of my class, the platform is detected and the appropriate unmanaged library is extracted from an embedded resource and saved to a temp directory, similar to the code given in <a href="https://stackoverflow.com/a/768429/358336">another stackoverflow answer</a>. </p> <p>So that the library can be found when it isn't in the PATH, I explicitly load it after it is saved to the temp file. On windows, this works fine with <code>LoadLibrary</code> from kernel32.dll. I'm trying to do the same with <code>dlopen</code> on Linux, but I get a <code>DllNotFoundException</code> when it comes to loading the P/Invoke methods later on.</p> <p>I have verified that the library "libindexfile.so" is successfully saved to the temp directory and that the call to <code>dlopen</code> succeeds. I delved into the <a href="https://github.com/mono/mono/blob/1429f06a9e3baf56245ec2433dcdb77e76eba684/mono/metadata/loader.c#L565" rel="nofollow noreferrer">mono source</a> to try figure out what is going on, and I think it might boil down to whether or not a subsequent call to <code>dlopen</code> will just reuse a previously loaded library. (Of course assuming that my naïve swoop through the mono source drew the correct conclusions).</p> <p>Here is the shape of what I'm trying to do:</p> <pre><code>// actual function that we're going to p/invoke to [DllImport("indexfile")] private static extern IntPtr openIndex(string pathname); const int RTLD_NOW = 2; // for dlopen's flags const int RTLD_GLOBAL = 8; // its okay to have imports for the wrong platforms here // because nothing will complain until I try to use the // function [DllImport("libdl.so")] static extern IntPtr dlopen(string filename, int flags); [DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string filename); static IndexFile() { string libName = ""; if (IsLinux) libName += "libindexfile.so"; else libName += "indexfile.dll"; // [snip] -- save embedded resource to temp dir IntPtr handle = IntPtr.Zero; if (IsLinux) handle = dlopen(libPath, RTLD_NOW|RTLD_GLOBAL); else handle = LoadLibrary(libPath); if (handle == IntPtr.Zero) throw new InvalidOperationException("Couldn't load the unmanaged library"); } public IndexFile(String path) { // P/Invoke to the unmanaged function // currently on Linux this throws a DllNotFoundException // works on Windows IntPtr ptr = openIndex(path); } </code></pre> <hr> <p><strong>Update:</strong></p> <p>It would appear that subsequent calls to <code>LoadLibrary</code> on windows look to see if a dll of the same name has already been loaded, and then uses that path. For example, in the following code, both calls to <code>LoadLibrary</code> will return a valid handle:</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { LPCTSTR libpath = L"D:\\some\\path\\to\\library.dll"; HMODULE handle1 = LoadLibrary(libpath); printf("Handle: %x\n", handle1); HMODULE handle2 = LoadLibrary(L"library.dll"); printf("Handle: %x\n", handle2); return 0; } </code></pre> <p>If the same is attempted with <code>dlopen</code> on Linux, the second call will fail, as it doesn't assume that a library with the same name will be at the same path. Is there any way round this?</p>
13,492,645
4
0
null
2012-11-19 20:50:56.56 UTC
8
2018-05-09 15:03:25.4 UTC
2017-05-23 11:55:07.343 UTC
null
-1
null
358,336
null
1
13
c#|mono|pinvoke|unmanaged
10,663
<p>After much searching and head-scratching, I've discovered a solution. Full control can be exercised over the P/Invoke process by using <a href="http://blogs.msdn.com/b/junfeng/archive/2004/07/14/181932.aspx">dynamic P/Invoke</a> to tell the runtime exactly where to find the code.</p> <hr> <p><strong>Edit:</strong></p> <h2>Windows solution</h2> <p>You need these imports:</p> <pre><code>[DllImport("kernel32.dll")] protected static extern IntPtr LoadLibrary(string filename); [DllImport("kernel32.dll")] protected static extern IntPtr GetProcAddress(IntPtr hModule, string procname); </code></pre> <p>The unmanaged library should be loaded by calling <code>LoadLibrary</code>:</p> <pre><code>IntPtr moduleHandle = LoadLibrary("path/to/library.dll"); </code></pre> <p>Get a pointer to a function in the dll by calling <code>GetProcAddress</code>:</p> <pre><code>IntPtr ptr = GetProcAddress(moduleHandle, methodName); </code></pre> <p>Cast this <code>ptr</code> to a delegate of type <code>TDelegate</code>:</p> <pre><code>TDelegate func = Marshal.GetDelegateForFunctionPointer( ptr, typeof(TDelegate)) as TDelegate; </code></pre> <h2>Linux Solution</h2> <p>Use these imports:</p> <pre><code>[DllImport("libdl.so")] protected static extern IntPtr dlopen(string filename, int flags); [DllImport("libdl.so")] protected static extern IntPtr dlsym(IntPtr handle, string symbol); const int RTLD_NOW = 2; // for dlopen's flags </code></pre> <p>Load the library:</p> <pre><code>IntPtr moduleHandle = dlopen(modulePath, RTLD_NOW); </code></pre> <p>Get the function pointer:</p> <pre><code>IntPtr ptr = dlsym(moduleHandle, methodName); </code></pre> <p>Cast it to a delegate as before:</p> <pre><code>TDelegate func = Marshal.GetDelegateForFunctionPointer( ptr, typeof(TDelegate)) as TDelegate; </code></pre> <hr> <p>For a helper library that I wrote, see <a href="https://github.com/gordonmleigh/Stugo.Interop">my GitHub</a>.</p>
13,483,796
Memory leak in a Java web application
<p>I have a Java web application running on Tomcat 7 that appears to have a memory leak. The average memory usage of the application increases linearly over time when under load (determined using JConsole). After the memory usage reaches the plateau, performance degrades significantly. Response times go from ~100ms to [300ms, 2500ms], so this is actually causing real problems.</p> <p><strong>JConsole memory profile of my application:</strong> <img src="https://i.stack.imgur.com/vROVt.png" alt="application memory profile"></p> <p>Using VisualVM, I see that at least half the memory is being used by character arrays (i.e. char[]) and that most (roughly the same number of each, 300,000 instances) of the strings are one of the following: "Allocation Failure", "Copy", "end of minor GC", all of which seem to be related to garbage collection notification. As far as I know, the application doesn't monitor the garbage collector at all. VisualVM can't find a GC root for any of these strings, so I'm having a hard time tracking this down.</p> <p><strong>Memory Analyzer heap dump:</strong> <img src="https://i.stack.imgur.com/AFKCj.png" alt="heap dump, unreachable memory"></p> <p>I can't explain why the memory usage plateaus like that, but I have a theory as to why performance degrades once it does. If memory is fragmented, the application could take a long time to allocate a contiguous block of memory to handle new requests.</p> <p>Comparing this to the built-in Tomcat server status application, the memory increases and levels off at, but doesn't hit a high "floor" like my application. It also doesn't have the high number of unreachable char[].</p> <p><strong>JConsole memory profile of Tomcat server status application:</strong> <img src="https://i.stack.imgur.com/cHfAy.png" alt="enter image description here"></p> <p><strong>Memory Analyzer heap dump of Tomcat server status applicationp:</strong> <img src="https://i.stack.imgur.com/9NaDu.png" alt="enter image description here"></p> <p>Where could these strings be allocated and why are they not being garbage collected? Are there Tomcat or Java settings that could affect this? Are there specific packages that could be affect this?</p>
13,710,173
8
4
null
2012-11-20 23:09:48.8 UTC
10
2013-10-11 20:58:39.993 UTC
2012-11-27 15:10:37.29 UTC
null
56,739
null
56,739
null
1
21
java|tomcat|web
35,105
<p>I removed the following JMX configuration from <code>tomcat\bin\setenv.bat</code>:</p> <pre><code>set "JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.port=9090 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false" </code></pre> <p>I can't get detailed memory heap dumps anymore, but the memory profile looks much better: <img src="https://i.stack.imgur.com/zmXVS.png" alt="enter image description here"></p> <p>24 hours later, the memory profile looks the same: <img src="https://i.stack.imgur.com/yHo6w.png" alt="enter image description here"></p>
13,320,568
Can I create a TypeScript type and use that when AJAX returns JSON data?
<p>I have the following C# class:</p> <pre><code>public class JsonBackup { public int Added { set; get; } public int DEVCount { set; get; } public int DS1Count { set; get; } public IList&lt;ViewEvent&gt; Events { get; set; } public IEnumerable&lt;string&gt; Errors { set; get; } public int Rejected { set; get; } public bool Success { set; get; } public int Updated { set; get; } } </code></pre> <p>and this code to return JSON data to my browser:</p> <pre><code>return Json(new JsonBackup { Added = added, DEVCount = devCount, DS1Count = ds1Count, Events = t.Events, Rejected = rejected, Success = true, Updated = updated }); </code></pre> <p>The data is returned here:</p> <pre><code> $.ajax("/Backup/Data/Backup", { cache: false, dataType: 'json', type: 'POST' }) .done(function (data: ) { console.log(data); backupDone(data, ajaxElapsed); }); </code></pre> <p>and used in other places and also here:</p> <pre><code> $.each(data.Events, function (i, item) { $("#stats-list li:eq("+(4+i)+")").after('&lt;li&gt;' + item.Description + ' : ' + item.Elapsed + ' ms&lt;/li&gt;'); }); </code></pre> <p>Is it possible for me to create a TypeScript type and assign data to that type so I could for example get intellisense when selecting such things as </p> <pre><code>data.Added or data.DEVCount etc? </code></pre>
13,320,802
1
0
null
2012-11-10 08:41:51.737 UTC
11
2019-01-26 13:28:45.193 UTC
2012-11-12 17:28:12.707 UTC
null
75,525
null
975,566
null
1
29
javascript|typescript
57,392
<p>Simplest way to achieve that is to create interface for IJsonBackup and when you receive json just cast it to IJsonBackup</p> <pre><code>interface IViewEvent { } interface IJsonBackup { Added : number; DEVCount : number; DS1Count : number; Events : IViewEvent[]; Errors : string[]; Rejected : number; Success : bool; Updated : number; } </code></pre> <p>In your class definition:</p> <pre><code>backupDone(data: IJsonBackup, ajaxElapsed: any) { } $.ajax("/Backup/Data/Backup", { cache: false, dataType: 'json', type: 'POST' }) .done(function (data: any) { console.log(data); backupDone(&lt;IJsonBackup&gt;data, ajaxElapsed); }); </code></pre>
13,549,216
Changing css on scrolling Angular Style
<p>I want to change CSS elements while a user scrolls the angular way.</p> <p>here's the code working the JQuery way</p> <pre><code>$(window).scroll(function() { if ($(window).scrollTop() &gt; 20 &amp;&amp; $(window).scrollTop() &lt; 600) { $('header, h1, a, div, span, ul, li, nav').css('height','-=10px'); } else if ($(window).scrollTop() &lt; 80) { $('header, h1, a, div, span, ul, li, nav').css('height','100px'); } </code></pre> <p>I tried doing the Angular way with the following code, but the $scope.scroll seemed to be unable to properly pickup the scroll data.</p> <pre><code>forestboneApp.controller('MainCtrl', function($scope, $document) { $scope.scroll = $($document).scroll(); $scope.$watch('scroll', function (newValue) { console.log(newValue); }); }); </code></pre>
13,549,510
1
1
null
2012-11-25 07:40:44.567 UTC
12
2021-11-17 22:43:06.38 UTC
2021-11-17 22:43:06.38 UTC
null
8,239,061
null
1,618,532
null
1
29
angularjs
37,501
<p>Remember, in Angular, DOM access should happen from within directives. Here's a simple directive that sets a variable based on the <code>scrollTop</code> of the window.</p> <pre><code>app.directive('scrollPosition', function($window) { return { scope: { scroll: '=scrollPosition' }, link: function(scope, element, attrs) { var windowEl = angular.element($window); var handler = function() { scope.scroll = windowEl.scrollTop(); } windowEl.on('scroll', scope.$apply.bind(scope, handler)); handler(); } }; }); </code></pre> <p>It's not apparent to me exactly what end result you're looking for, so here's a simple demo app that sets the height of an element to <code>1px</code> if the window is scrolled down more than 50 pixels: <a href="http://jsfiddle.net/BinaryMuse/Z4VqP/" rel="noreferrer">http://jsfiddle.net/BinaryMuse/Z4VqP/</a></p>
13,461,027
Why does the standard differentiate between direct-list-initialization and copy-list-initialization?
<p>We know that <code>T v(x);</code> is called <em>direct-initialization</em>, while <code>T v = x;</code> is called <em>copy-initialization</em>, meaning that it will construct a temporary <code>T</code> from <code>x</code> that will get copied / moved into <code>v</code> (which is most likely elided).</p> <p>For list-initialization, the standard differentiates between two forms, depending on the context. <code>T v{x};</code> is called <em>direct-list-initialization</em> while <code>T v = {x};</code> is called <em>copy-list-initialization</em>:</p> <p><code>§8.5.4 [dcl.init.list] p1</code></p> <blockquote> <p>[...] List-initialization can occur in direct-initialization or copy-initialization contexts; list-initialization in a direct-initialization context is called <em>direct-list-initialization</em> and list-initialization in a copy-initialization context is called <em>copy-list-initialization</em>. [...]</p> </blockquote> <p>However, there are only two more references each in the whole standard. For direct-list-initialization, it's mentioned when creating temporaries like <code>T{x}</code> (<code>§5.2.3/3</code>). For copy-list-initialization, it's for the expression in return statements like <code>return {x};</code> (<code>§6.6.3/2</code>).</p> <p>Now, what about the following snippet?</p> <pre><code>#include &lt;initializer_list&gt; struct X{ X(X const&amp;) = delete; // no copy X(X&amp;&amp;) = delete; // no move X(std::initializer_list&lt;int&gt;){} // only list-init from 'int's }; int main(){ X x = {42}; } </code></pre> <p>Normally, from the <code>X x = expr;</code> pattern, we expect the code to fail to compile, because the move constructor of <code>X</code> is defined as <code>delete</code>d. However, the latest versions of Clang and GCC compile the above code just fine, and after digging a bit (and finding the above quote), that seems to be correct behaviour. The standard only ever defines the behaviour for the whole of list-initialization, and doesn't differentiate between the two forms at all except for the above mentioned points. Well, atleast as far as I can see, anyways.</p> <p>So, to summarize my question again:</p> <p><strong>What is the use of splitting list-initialization into its two forms if they (apparently) do the exact same thing?</strong></p>
13,461,382
1
2
null
2012-11-19 19:47:51.65 UTC
20
2015-09-08 08:39:23.997 UTC
2015-09-08 08:39:23.997 UTC
null
1,938,163
null
500,104
null
1
40
c++|c++11|language-lawyer|list-initialization
3,866
<p>Because they <em>don't</em> do the exact same thing. As stated in 13.3.1.7 [over.match.list]:</p> <blockquote> <p>In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.</p> </blockquote> <p>In short, you can only use implicit conversion in copy-list-initialization contexts.</p> <p>This was explicitly added to make uniform initialization not, um, uniform. Yeah, I know how stupid that sounds, but bear with me.</p> <p>In 2008, <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2640.pdf" rel="noreferrer">N2640 was published (PDF)</a>, taking a look at the current state of uniform initialization. It looked specifically at the difference between direct initialization (<code>T{...}</code>) and copy-initialization (<code>T = {...}</code>).</p> <p>To summarize, the concern was that <code>explicit</code> constructors would effectively become pointless. If I have some type <code>T</code> that I want to be able to be constructed from an integer, but I don't want implicit conversion, I label the constructor explicit.</p> <p>Then somebody does this:</p> <pre><code>T func() { return {1}; } </code></pre> <p>Without the current wording, this will call my <code>explicit</code> constructor. So what good is it to make the constructor <code>explicit</code> if it doesn't change much?</p> <p>With the current wording, you need to at least use the name directly:</p> <pre><code>T func() { return T{1}; } </code></pre>
13,353,213
Gradient of n colors ranging from color 1 and color 2
<p>I often work with <code>ggplot2</code> that makes gradients nice (<a href="http://www.r-bloggers.com/ggtutorial-day-5-gradient-colors-and-brewer-palettes/" rel="noreferrer">click here for an example</a>). I have a need to work in base and I think <code>scales</code> can be used there to create color gradients as well but I'm severely off the mark on how. The basic goal is generate a palette of n colors that ranges from x color to y color. The solution needs to work in base though. This was a starting point but there's no place to input an n. </p> <pre><code> scale_colour_gradientn(colours=c("red", "blue")) </code></pre> <p>I am well aware of:</p> <pre><code>brewer.pal(8, "Spectral") </code></pre> <p>from <code>RColorBrewer</code>. I'm looking more for the approach similar to how <code>ggplot2</code> handles gradients that says I have these two colors and I want 15 colors along the way. How can I do that?</p>
13,353,264
5
3
null
2012-11-12 23:16:53.253 UTC
51
2022-08-18 18:45:32.233 UTC
2018-11-01 23:26:42.433 UTC
null
2,291,248
null
1,000,343
null
1
127
r|gradient
161,872
<p><code>colorRampPalette</code> could be your friend here:</p> <pre><code>colfunc &lt;- colorRampPalette(c("black", "white")) colfunc(10) # [1] "#000000" "#1C1C1C" "#383838" "#555555" "#717171" "#8D8D8D" "#AAAAAA" # [8] "#C6C6C6" "#E2E2E2" "#FFFFFF" </code></pre> <p>And just to show it works:</p> <pre><code>plot(rep(1,10),col=colfunc(10),pch=19,cex=3) </code></pre> <p><img src="https://i.stack.imgur.com/dGQU0.png" alt="enter image description here"></p>
13,520,162
Ruby capitalize every word first letter
<p>I need to make the first character of every word uppercase, and make the rest lowercase...</p> <pre><code>manufacturer.MFA_BRAND.first.upcase </code></pre> <p>is only setting the first letter uppercase, but I need this:</p> <pre><code>ALFA ROMEO =&gt; Alfa Romeo AUDI =&gt; Audi BMW =&gt; Bmw ONETWO THREE FOUR =&gt; Onetwo Three Four </code></pre>
13,520,207
8
0
null
2012-11-22 21:23:59.107 UTC
38
2020-07-08 22:43:13.867 UTC
2015-02-27 04:18:41.037 UTC
null
2,317,829
null
1,187,490
null
1
184
ruby|string
119,325
<p>try this:</p> <pre><code>puts 'one TWO three foUR'.split.map(&amp;:capitalize).join(' ') #=&gt; One Two Three Four </code></pre> <p>or</p> <pre><code>puts 'one TWO three foUR'.split.map(&amp;:capitalize)*' ' </code></pre>
20,638,351
Find row in datatable with specific id
<p>I have two columns in a datatable:</p> <pre><code>ID, Calls. </code></pre> <p>How do I find what the value of Calls is <code>where ID = 5</code>?</p> <p>5 could be anynumber, its just for example. Each row has a unique ID. </p>
20,638,486
8
2
null
2013-12-17 15:38:33.163 UTC
12
2017-10-07 14:28:22.547 UTC
null
null
null
null
383,691
null
1
45
c#|datatable|datarow
251,858
<p>Make a string criteria to search for, like this:</p> <pre><code>string searchExpression = "ID = 5" </code></pre> <p>Then use the <code>.Select()</code> method of the <code>DataTable</code> object, like this:</p> <pre><code>DataRow[] foundRows = YourDataTable.Select(searchExpression); </code></pre> <p>Now you can loop through the results, like this:</p> <pre><code>int numberOfCalls; bool result; foreach(DataRow dr in foundRows) { // Get value of Calls here result = Int32.TryParse(dr["Calls"], out numberOfCalls); // Optionally, you can check the result of the attempted try parse here // and do something if you wish if(result) { // Try parse to 32-bit integer worked } else { // Try parse to 32-bit integer failed } } </code></pre>
20,709,267
Big O notation Log Base 2 or Log Base 10
<p>When articles/question state that the Big O running time of the algorithm is O(LogN) .</p> <p>For example Quicksort has a Big O running time of O (LogN) where the it is Log base 10 but Height of binary tree is O(LogN+1) where it is Log base 2</p> <p><strong>Question</strong></p> <p>1)I am confused over whether is it Log base 10 or Log base 2 as different articles use different bases for their Logarithm . </p> <p>2) Does it make a difference if its Log base 2 or Log base 10??</p> <p>3)Can we assume it mean Log base 10 when we see O(LogN)???</p>
20,709,295
3
2
null
2013-12-20 17:50:13.65 UTC
13
2013-12-20 18:16:09.917 UTC
null
null
null
null
1,832,057
null
1
41
algorithm|big-o|logarithm
66,524
<p>I think it does not matter what is the base of the log as the relative complexity is the same irrespective of the base used.</p> <p>So you can think of it as O(log<sub>2</sub>X) = O(log<sub>10</sub>X) </p> <p>Also to mention that logarithms are related by some constant.</p> <p><img src="https://i.stack.imgur.com/xxDnx.png" alt="enter image description here"></p> <p>So <h1>log₁₀(<em>x</em>) = log₂(<em>x</em>) / log₂(10)</h1></p> <p>So most of the time we generally disregard constants in complexity analysis, and hence we say that the base doesn't matter.</p> <p>Also you may find that the base is considered to be 2 most of the time like in <a href="http://en.wikipedia.org/wiki/Merge_sort">Merge Sort</a>. The tree has a height of <code>log₂ n</code>, since the node has two branches.</p> <blockquote> <p>1)I am confused over whether is it Log base 10 or Log base 2 as different articles use different bases for their Logarithm .</p> </blockquote> <p>So as explained above this change of base doesn't matter.</p> <blockquote> <p>2) Does it make a difference if its Log base 2 or Log base 10??</p> </blockquote> <p>No it does not matter.</p> <blockquote> <p>3)Can we assume it mean Log base 10 when we see O(LogN)???</p> </blockquote> <p>Yes you can assume that provided you know the base conversion rule.</p>
28,432,401
Replacing callbacks with promises in Node.js
<p>I have a simple node module which connects to a database and has several functions to receive data, for example this function:</p> <hr> <p><strong>dbConnection.js:</strong></p> <pre><code>import mysql from 'mysql'; const connection = mysql.createConnection({ host: 'localhost', user: 'user', password: 'password', database: 'db' }); export default { getUsers(callback) { connection.connect(() =&gt; { connection.query('SELECT * FROM Users', (err, result) =&gt; { if (!err){ callback(result); } }); }); } }; </code></pre> <p>The module would be called this way from a different node module:</p> <hr> <p><strong>app.js:</strong></p> <pre><code>import dbCon from './dbConnection.js'; dbCon.getUsers(console.log); </code></pre> <p>I would like to use promises instead of callbacks in order to return the data. So far I've read about nested promises in the following thread: <a href="https://stackoverflow.com/questions/15913448/writing-clean-code-with-nested-promises">Writing Clean Code With Nested Promises</a>, but I couldn't find any solution that is simple enough for this use case. What would be the correct way to return <code>result</code> using a promise?</p>
28,433,034
8
4
null
2015-02-10 13:03:51.607 UTC
42
2021-03-09 18:34:10.783 UTC
2021-03-09 18:34:10.783 UTC
null
3,198,711
null
3,198,711
null
1
95
javascript|node.js|promise
96,507
<h3>Using the <code>Promise</code> class</h3> <p>I recommend to take a look at <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer">MDN's Promise docs</a> which offer a good starting point for using Promises. Alternatively, I am sure there are many tutorials available online.:)</p> <p><strong>Note:</strong> Modern browsers already support ECMAScript 6 specification of Promises (see the MDN docs linked above) and I assume that you want to use the native implementation, without 3rd party libraries.</p> <p>As for an actual example...</p> <p>The basic principle works like this:</p> <ol> <li>Your API is called</li> <li>You create a new Promise object, this object takes a single function as constructor parameter</li> <li>Your provided function is called by the underlying implementation and the function is given two functions - <code>resolve</code> and <code>reject</code></li> <li>Once you do your logic, you call one of these to either fullfill the Promise or reject it with an error</li> </ol> <p>This might seem like a lot so here is an actual example.</p> <pre><code>exports.getUsers = function getUsers () { // Return the Promise right away, unless you really need to // do something before you create a new Promise, but usually // this can go into the function below return new Promise((resolve, reject) =&gt; { // reject and resolve are functions provided by the Promise // implementation. Call only one of them. // Do your logic here - you can do WTF you want.:) connection.query('SELECT * FROM Users', (err, result) =&gt; { // PS. Fail fast! Handle errors first, then move to the // important stuff (that's a good practice at least) if (err) { // Reject the Promise with an error return reject(err) } // Resolve (or fulfill) the promise with data return resolve(result) }) }) } // Usage: exports.getUsers() // Returns a Promise! .then(users =&gt; { // Do stuff with users }) .catch(err =&gt; { // handle errors }) </code></pre> <h3>Using the async/await language feature (Node.js >=7.6)</h3> <p>In Node.js 7.6, the v8 JavaScript compiler was upgraded with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="noreferrer">async/await support</a>. You can now declare functions as being <code>async</code>, which means they automatically return a <code>Promise</code> which is resolved when the async function completes execution. Inside this function, you can use the <code>await</code> keyword to wait until another Promise resolves.</p> <p>Here is an example:</p> <pre><code>exports.getUsers = async function getUsers() { // We are in an async function - this will return Promise // no matter what. // We can interact with other functions which return a // Promise very easily: const result = await connection.query('select * from users') // Interacting with callback-based APIs is a bit more // complicated but still very easy: const result2 = await new Promise((resolve, reject) =&gt; { connection.query('select * from users', (err, res) =&gt; { return void err ? reject(err) : resolve(res) }) }) // Returning a value will cause the promise to be resolved // with that value return result } </code></pre>
28,467,068
How to add a row to a data frame in R?
<p>In R, how do you add a new row to a data frame once the data frame has already been initialized?</p> <p>So far I have this:</p> <pre class="lang-r prettyprint-override"><code>df &lt;- data.frame("hi", "bye") names(df) &lt;- c("hello", "goodbye") #I am trying to add "hola" and "ciao" as a new row de &lt;- data.frame("hola", "ciao") merge(df, de) # Adds to the same row as new columns # Unfortunately, I couldn't find an rbind() solution that wouldn't give me an error </code></pre> <p>Any help would be appreciated</p>
28,468,977
15
7
null
2015-02-12 00:10:10.207 UTC
38
2022-05-11 17:23:53.717 UTC
2022-02-01 14:38:02.003 UTC
null
2,473,891
null
1,634,753
null
1
192
r|dataframe
703,478
<p>Like @Khashaa and @Richard Scriven point out in comments, you have to set consistent column names for all the data frames you want to append. </p> <p>Hence, you need to explicitly declare the columns names for the second data frame, <code>de</code>, then use <code>rbind()</code>. You only set column names for the first data frame, <code>df</code>:</p> <pre><code>df&lt;-data.frame("hi","bye") names(df)&lt;-c("hello","goodbye") de&lt;-data.frame("hola","ciao") names(de)&lt;-c("hello","goodbye") newdf &lt;- rbind(df, de) </code></pre>
9,547,728
Handle selected event in autocomplete textbox using bootstrap Typeahead?
<p>I want to run JavaScript function just after <strong>user select a value</strong> using <strong>autocomplete textbox bootstrap Typeahead</strong>.</p> <p>I'm searching for something like <strong>selected</strong> event.</p>
15,674,546
9
2
null
2012-03-03 16:35:18.72 UTC
2
2022-02-17 09:49:16.39 UTC
2022-02-17 08:56:45.997 UTC
null
2,678,603
null
1,040,425
null
1
26
autocomplete|textbox|typeahead
49,924
<pre><code>$('.typeahead').on('typeahead:selected', function(evt, item) { // do what you want with the item here }) </code></pre>
9,334,618
Rounded Button in Android
<p>I want to create rounded buttons in an Android program. I have looked at <a href="https://stackoverflow.com/questions/3646415/how-to-create-edittext-with-rounded-corners/3646629#3646629">How to create EditText with rounded corners?</a></p> <p>What I want to achieve is:</p> <ol> <li>Rounded Edge Buttons</li> <li>Change Button background/appearance on different states (Like Onclick, Focus)</li> <li>Use my own PNG for the background and not create a shape.</li> </ol>
9,335,683
10
2
null
2012-02-17 20:02:16.013 UTC
40
2021-06-02 09:41:09.58 UTC
2017-05-23 11:47:32.423 UTC
null
-1
null
1,159,192
null
1
84
android|android-button|rounded-corners
233,235
<p>You can do a rounded corner button without resorting to an ImageView.</p> <p>A background selector resource, <code>button_background.xml</code>:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt; &lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;!-- Non focused states --&gt; &lt;item android:state_focused=&quot;false&quot; android:state_selected=&quot;false&quot; android:state_pressed=&quot;false&quot; android:drawable=&quot;@drawable/button_unfocused&quot; /&gt; &lt;item android:state_focused=&quot;false&quot; android:state_selected=&quot;true&quot; android:state_pressed=&quot;false&quot; android:drawable=&quot;@drawable/button_unfocused&quot; /&gt; &lt;!-- Focused states --&gt; &lt;item android:state_focused=&quot;true&quot; android:state_selected=&quot;false&quot; android:state_pressed=&quot;false&quot; android:drawable=&quot;@drawable/button_focus&quot; /&gt; &lt;item android:state_focused=&quot;true&quot; android:state_selected=&quot;true&quot; android:state_pressed=&quot;false&quot; android:drawable=&quot;@drawable/button_focus&quot; /&gt; &lt;!-- Pressed --&gt; &lt;item android:state_pressed=&quot;true&quot; android:drawable=&quot;@drawable/button_press&quot; /&gt; &lt;/selector&gt; </code></pre> <p>For each state, a drawable resource, e.g. button_press.xml:</p> <pre><code>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:shape=&quot;rectangle&quot;&gt; &lt;stroke android:width=&quot;1dp&quot; android:color=&quot;#FF404040&quot; /&gt; &lt;corners android:radius=&quot;6dp&quot; /&gt; &lt;gradient android:startColor=&quot;#FF6800&quot; android:centerColor=&quot;#FF8000&quot; android:endColor=&quot;#FF9700&quot; android:angle=&quot;90&quot; /&gt; &lt;/shape&gt; </code></pre> <p>Note the <code>corners</code> element, this gets you rounded corners!</p> <p>Then set the background drawable on the button:</p> <pre><code>android:background=&quot;@drawable/button_background&quot; </code></pre> <p><strong>EDIT (9/2018)</strong>: The same technique can be used to create a circular button. A circle is really just a square button with radius size set to 1/2 the side of the square</p> <p>Additionally, in the example above the <code>stroke</code> and <code>gradient</code> aren't necessary elements, they are just examples and ways that you'll be able to see the rounded corner shape</p>
16,055,458
Install a service handler for URI scheme from webpage
<p>When accessing Google Mail or Google Calendar from Chrome, small icon appears in addressbar allowing to install custom service handler for URI scheme (marked with red square in picture).</p> <p><img src="https://i.stack.imgur.com/cT6Ch.png" alt="Icon for installing custom service handler"></p> <p>Tooltip for icon is: <code>This page wants to install a service handler</code>. When I click icon and allow Google Mail to handle <code>mailto:</code> links, all <code>mailto:</code> links are opening in Chrome.</p> <p>Is it possible to create webpage that will be able to install custom handler for my custom URI scheme just like Google Mail do?</p>
16,131,948
1
0
null
2013-04-17 08:43:05.88 UTC
11
2013-04-21 14:05:53.5 UTC
2013-04-21 14:05:53.5 UTC
null
1,580,941
null
1,105,235
null
1
19
javascript|google-chrome|gmail|uri|uri-scheme
4,472
<p>For Chrome (13+), Firefox (3.0+) and Opera (11.60+) it is possible to register web application as service handler for custom URI scheme using JavaScript API:</p> <pre><code>window.navigator.registerProtocolHandler(protocol, uri, title); </code></pre> <ul> <li><code>protocol</code> is the protocol the site wishes to handle, specified as a string.</li> <li><code>uri</code> is the URI to the handler as a string. You can include "%s" to indicate where to insert the escaped URI of the document to be handled.</li> <li><code>title</code> is the title of the handler presented to the user as a string.</li> </ul> <p>Specifically for Chrome there is a limitation that does not allow to use custom schemes that don't start with <code>web+</code> prefix (except standard ones: <code>mailto</code>, <code>mms</code>, <code>nntp</code>, <code>rtsp</code> and <code>webcal</code>). So if you want to register your web app as service handler as GMail do, you should write something like this:</p> <pre><code>navigator.registerProtocolHandler("mailto", "https://www.example.com/?uri=%s", "Example Mail"); </code></pre> <p>or</p> <pre><code>navigator.registerProtocolHandler("web+myscheme", "https://www.example.com/?uri=%s", "My Cool App"); </code></pre> <p>Pay attention at URI pattern, it have to contain <code>%s</code> which will be replaced with actual URI of the link user clicks. For example:</p> <pre><code>&lt;a href="web+myscheme:some+data"&gt;Open in "My Cool App"&lt;/a&gt; </code></pre> <p>will trigger <code>GET</code> request to <code>http://www.example.com/?uri=web%2Bmyscheme%3Asome%20data</code></p> <p>Here are some useful links:</p> <ul> <li>Standard <a href="http://www.whatwg.org/specs/web-apps/current-work/#custom-handlers">http://www.whatwg.org/specs/web-apps/current-work/#custom-handlers</a></li> <li>MDN <a href="https://developer.mozilla.org/en-US/docs/DOM/navigator.registerProtocolHandler">https://developer.mozilla.org/en-US/docs/DOM/navigator.registerProtocolHandler</a></li> <li>HTML5ROCKS <a href="http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler">http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler</a></li> </ul>
16,530,060
Deserializing a json string with restsharp
<p>I have a string that comes out of a database which is in Json format.</p> <p>I have tried to deserialize it with:</p> <pre><code>RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); var x = deserial .Deserialize&lt;Customer&gt;(myStringFromDB) </code></pre> <p>But the <code>.Deserialize</code> function expects an <code>IRestResponse</code></p> <p>Is there a way to use RestSharp to just deserialize raw strings?</p>
16,530,226
2
1
null
2013-05-13 19:54:53.83 UTC
16
2021-04-29 17:56:11.847 UTC
2021-04-29 17:43:46.783 UTC
null
316,799
null
172,861
null
1
51
c#|json|rest|asp.net-web-api|restsharp
103,052
<p>There are sereval ways to do this. A very popular library to handle json is the <a href="http://json.codeplex.com/" rel="noreferrer"><code>Newtonsoft.Json</code></a>. Probably you already have it on your asp.net project but if not, you could add it from <code>nuget</code>.</p> <p>Considering you have a response object, include the following namespaces and call the static method <code>DeserializeObject&lt;T&gt;</code> from <code>JsonConvert</code> class:</p> <pre class="lang-cs prettyprint-override"><code>using Newtonsoft.Json; using RestSharp; </code></pre> <pre class="lang-cs prettyprint-override"><code>return JsonConvert.DeserializeObject&lt;T&gt;(response.Content); </code></pre> <p>On the <code>response.Content</code>, you will have the raw result, so just deserialize this string to a json object. The <code>T</code> in the case is the type you need to deserialize.</p> <p>For example:</p> <pre class="lang-cs prettyprint-override"><code>var customerDto = JsonConvert.DeserializeObject&lt;CustomerDto&gt;(response.Content); </code></pre> <p><strong>Update</strong></p> <p>Recently, Microsoft has added a namespace <code>System.Text.Json</code> which handle json format on the .Net platform. You could use it calling the <code>JsonSerializer.Deserialize&lt;T&gt;</code> static method:</p> <pre class="lang-cs prettyprint-override"><code>using System.Text.Json; </code></pre> <pre class="lang-cs prettyprint-override"><code>var customer = JsonSerializer.Deserialize&lt;Customer&gt;(jsonContent); </code></pre>
58,000,680
Django: Safely Remove Old Migrations?
<p>I've got a Django app with a lot of out-of-date migrations. I'd like to remove the old migrations and start fresh. </p> <p>The app has 14 different "migrations" folders.</p> <p>Here is what a few of them look like:</p> <p><a href="https://i.stack.imgur.com/plNGh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/plNGh.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/4H9E3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4H9E3.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/tscCr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tscCr.png" alt="enter image description here"></a></p> <p>Is it safe to remove <em>all</em> the contents from each of these folders? Or, do I have to make sure to only remove <em>some</em> of the files -- and if so which files?</p>
58,000,915
5
2
null
2019-09-18 21:02:13.793 UTC
18
2021-06-02 22:15:21.763 UTC
null
null
null
null
364,966
null
1
16
django|python-3.x|django-models|django-migrations
25,577
<p>You should <strong>never</strong> just delete migrations before unapplying them, or it will be a nightmare when you want to apply new migrations.</p> <p>To unapply migrations you should do the following:</p> <ol> <li><p>Use the <code>python manage.py migrate your_app_name XXXX</code> in case you want to unapply migrations after the XXXX migration. Otherwise use <code>python manage.py migrate your_app_name zero</code> to completely unapply all migrations.</p> </li> <li><p>Remove the <code>.pyc</code> files under /migrations/_<em>pycache</em>_/ that you have unapplied.</p> </li> <li><p>Remove the <code>.py</code> files under migrations/ that you have unapplied.</p> </li> </ol> <p>Now you can create new migrations without any headaches.</p> <p>If what you're looking for is to squash all the migrations into one, do the steps above removing all migrations and then run <code>python manage.py makemigrations your_app_name</code> to create a single migration file. After that just run <code>python manage.py migrate your_app_name</code> and you're done.</p>
58,099,933
I want to get members count in discord bot but it gives error
<p>I want to get members count in discord bot but it gives error. I search for it through internet for this and i don't find it! Here is code:</p> <pre><code>const Commando = require('discord.js-commando'); const bot = new Commando.Client({commandPrefix: '$'}); const TOKEN = 'here is token'; const MIN_INTERVAL = 3 * 1000; const guild = bot.guilds.get("394805546450026496"); bot.registry.registerGroup('connectc', 'Connectc'); bot.registry.registerGroup('defaultc', 'Defaultc'); bot.registry.registerDefaults(); bot.registry.registerCommandsIn(__dirname + "/commands") bot.on('ready', function(){ console.log("Ready"); setInterval(function(){ var memberCount = guild.members.filter(member =&gt; !member.user.bot).size; var memberCountChannel = bot.channels.get("547805078787194891"); memberCountChannel.setName("Osoby: "+ memberCount +" "); }, MIN_INTERVAL); }); bot.login(TOKEN); </code></pre> <p>And here error:</p> <pre><code>C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18 var memberCount = guild.members.filter(member =&gt; !member.user.bot).size; ^ TypeError: Cannot read property 'members' of undefined at CommandoClient.&lt;anonymous&gt; (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18:29) at CommandoClient.emit (events.js:194:15) at WebSocketConnection.triggerReady (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:125:17) at WebSocketConnection.checkIfReady (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:141:61) at GuildCreateHandler.handle (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\node_modules\discord.js\src\client\websocket\packets\handlers\GuildCreate.js:13:31) at WebSocket.onMessage (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\node_modules\ws\lib\event-target.js:120:16) at WebSocket.emit (events.js:189:13) </code></pre> <p>Please help me!</p>
58,103,544
5
2
null
2019-09-25 13:48:20.92 UTC
null
2022-05-31 10:47:42.653 UTC
null
null
null
null
11,959,283
null
1
1
node.js|count|bots|discord.js|member
41,720
<p>From your error results that the <strong>guild</strong> is <strong>undefined</strong>. I ran the code and it's working as expected.</p> <pre><code>module.exports.run = async (client, message, arguments) =&gt; { const guild = client.guilds.get("566596189827629066"); setInterval(function () { var memberCount = guild.members.filter(member =&gt; !member.user.bot).size; var memberCountChannel = client.channels.get("626462657817477131"); memberCountChannel.setName(`${guild.name} has ${memberCount} members!`); }, 1000); }; </code></pre> <p><a href="https://i.stack.imgur.com/pQZK6.png" rel="nofollow noreferrer">Image</a></p> <p>Please, double-check that <strong>394805546450026496</strong> is a valid guild-id and not a channel-id/user-id. If it is, check if the bot is in the mentioned guild.</p> <p>Another thing, it's recommended to see if a guild is available before performing operations or reading data from it. You can check this with <a href="https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=available" rel="nofollow noreferrer">guild.available</a>.</p>
17,607,240
Mixing static and dynamic sections in a grouped table view
<p>I need a grouped <code>UITableView</code> similar to the one for Twitter accounts in Settings app:</p> <p><img src="https://i.stack.imgur.com/TGKET.jpg" alt="Twitter accounts"></p> <p>That is, a sort of form or menu where some of the sections have a beforehand known set of static cells, and some other sections have to be dynamic and allow inserting additional rows the same way the "Add Account" does here. I'm managing the <code>UITableView</code> in a <code>.xib</code> file. For the static cells, I have separated <code>.xib</code> files that I can load within the <code>cellForRowAtIndexPath:</code> method in the view controller.</p> <p>How should I handle this kind of table? I don´t find any example code. </p> <p>How the <code>cellForRowAtIndexPath:</code> method should look like? May I need to keep <code>strong</code> properties for the static cells? Would it be better to design each static cell directly within the same <code>.xib</code> file where the table view is, and to set outlets for them? (Though this does not allow to reuse my custom cells design...)</p> <p>I need some guidelines for achieving this and correctly managing cells and memory. Thanks in advance</p>
17,607,902
2
5
null
2013-07-12 03:57:02.893 UTC
14
2013-07-12 05:23:05.797 UTC
null
null
null
null
1,833,423
null
1
10
ios|dynamic|uitableview|static
19,753
<p>Dynamic prototype cells can behave like static ones if you just return the cell without adding any content in cellForRowAtIndexPath, so you can have both "static like" cells and dynamic ones (where the number of rows and the content are variable) by using dynamic prototypes.</p> <p>In the example below, I started with a table view controller in IB (with a grouped table view), and changed the number of dynamic prototype cells to 3. I adjusted the size of the first cell to 80, and added a UIImageView and two labels. The middle cell is a Basic style cell, and the last one is another custom cell with a single centered label. I gave them each their own identifier. This is what it looks like in IB:</p> <p><img src="https://i.stack.imgur.com/DLMRI.png" alt="enter image description here"></p> <p>Then in code, I did this:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five"]; [self.tableView reloadData]; } -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 3; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (section == 1) return self.theData.count; return 1; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) return 80; return 44; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; if (indexPath.section == 0) { cell = [tableView dequeueReusableCellWithIdentifier:@"TitleCell" forIndexPath:indexPath]; }else if (indexPath.section == 1) { cell = [tableView dequeueReusableCellWithIdentifier:@"DataCell" forIndexPath:indexPath]; cell.textLabel.text = self.theData[indexPath.row]; }else if (indexPath.section == 2) { cell = [tableView dequeueReusableCellWithIdentifier:@"ButtonCell" forIndexPath:indexPath]; } return cell; } </code></pre> <p>As you can see, for the "static like" cells, I just return the cell with the correct identifier, and I get exactly what I set up in IB. The result at runtime will look like your posted image with three sections.</p>
22,245,250
ORACLE Casting DATE to TIMESTAMP WITH TIME ZONE WITH OFFSET
<p>I need to cast a DATE value in a query to a TIMESTAMP WITH TIME ZONE, but currently I'm getting the TimeZone Region ('Europe / Paris') which is not valid to be used by EF. </p> <p>For example, when doing this:</p> <pre><code>select CAST(FECHA AS TIMESTAMP WITH TIME ZONE) from test; </code></pre> <p>I currently get this output:</p> <pre><code>07/03/14 09:22:00,000000000 EUROPE/PARIS </code></pre> <p>But I need it to be like:</p> <pre><code>07/03/14 09:22:00,000000000 +01:00 </code></pre> <p>Any idea how to accomplish this?</p>
22,245,382
3
2
null
2014-03-07 08:39:57.187 UTC
7
2015-10-27 18:11:21.583 UTC
null
null
null
null
1,152,186
null
1
15
sql|oracle|timestamp-with-timezone
95,079
<p>You can cast the <code>DATE</code> to a <code>TIMESTAMP</code>, then use <a href="http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions068.htm#SQLRF00644"><code>FROM_TZ</code></a> to convert this timestamp to a timestamp with time zone:</p> <pre><code>SQL&gt; SELECT from_tz(CAST (SYSDATE AS TIMESTAMP), '+01:00') tz FROM dual; TZ ------------------------------------------------- 07/03/14 09:47:06,000000 +01:00 </code></pre>
22,017,723
Regex for Umlaut
<p>I am using JS Animated Contact Form with this line of validation regex:</p> <pre><code>rx:{".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, other fields... </code></pre> <p>I just found out, that I can't enter name like "Müller". The regex will not accept this. What do I have to do, to allow also Umlauts?</p>
22,017,800
6
3
null
2014-02-25 14:51:20.69 UTC
9
2021-12-08 10:19:34.637 UTC
2014-02-25 17:11:00.76 UTC
null
1,223,293
null
1,555,112
null
1
32
javascript|regex|forms
60,539
<p>You should use in your regex unicode codes for characters, like <code>\u0080</code>. For German language, I found following table:</p> <pre><code>Zeichen Unicode ------------------------------ Ä, ä \u00c4, \u00e4 Ö, ö \u00d6, \u00f6 Ü, ü \u00dc, \u00fc ß \u00df </code></pre> <p>(source <a href="http://javawiki.sowas.com/doku.php?id=java:unicode">http://javawiki.sowas.com/doku.php?id=java:unicode</a>)</p>
19,350,258
how to check screen on/off status in onStop()?
<p>as mentioned <a href="https://stackoverflow.com/a/3407269/1986618">here</a>, when the screen goes off, the <code>onStop()</code> of current Activity will be called. I need to check the screen on/off status when the <code>onStop()</code> of my <code>Activity</code> is called. so I have registered a <code>BroadcastReceiver</code> for these actions(<code>ACTION_SCREEN_ON</code> AND <code>ACTION_SCREEN_OFF</code>) to record the current on/off status(and they work properly, I have logged!).<br> but when I turn off the screen and check the on/off status in the <code>onStop</code> , it says the screen is on. why? I think the receiver must receive the <code>ACTION_SCREEN_OFF</code> before <code>onStop</code> is called so what's wrong?</p>
19,350,470
4
6
null
2013-10-13 21:03:17.7 UTC
15
2022-08-22 09:56:59.043 UTC
2017-05-23 12:26:23.81 UTC
null
-1
null
1,986,618
null
1
29
android|android-activity|android-broadcast
27,782
<p>You can try to use PowerManager system service for this purpose, here is example and <a href="http://developer.android.com/reference/android/os/PowerManager.html#isScreenOn%28%29">official documentation</a> (note this method was added in API level 7):</p> <pre><code>PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); </code></pre> <p>EDIT:</p> <p>isScreenOn() method is deprecated API level 21. You should use isInteractive instead:</p> <pre><code>boolean isScreenOn = pm.isInteractive(); </code></pre> <p><a href="http://developer.android.com/reference/android/os/PowerManager.html#isInteractive()">http://developer.android.com/reference/android/os/PowerManager.html#isInteractive()</a></p>
30,645,986
Toolbar will not collapse with Scrollview as child of CoordinatorLayout
<p>I am trying to follow the Google Docs on using the CoordinatorLayout but i am having an issue with the ScrollView inside the CoordinatorLayout. Basically, the Toolbar normally would collapse with a RecyclerView or a Listview when scrolling down. Now with a ScrollView it will not collapse. </p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;ScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" &gt; &lt;TextView android:id="@+id/tv_View" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:text="@string/filler" style="@style/TextAppearance.AppCompat.Large" /&gt; &lt;/ScrollView&gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre>
30,646,837
5
2
null
2015-06-04 14:03:17.693 UTC
13
2017-04-08 22:31:02.797 UTC
null
null
null
null
3,844,132
null
1
65
android|toolbar|android-scrollview|android-toolbar|coordinator-layout
29,943
<p>The <code>ScrollView</code> does not cooperate with the <code>CoordinatorLayout</code>. You have to use <code>NestedScrollView</code> instead of <code>ScrollView</code></p>
37,057,711
Unexpected end of JSON input from an ajax call
<p>I've been working on a delete post functionality in my project. It all works fine in PHP, but now I'd like to do that in Ajax, to prevent the refresh and all.</p> <p>Anyway, when I perform my ajax call, I get an error:</p> <pre><code>SyntaxError: Unexpected end of JSON input at Object.parse (native) at n.parseJSON (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:6401) at Ab (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:8347) at z (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:11804) at XMLHttpRequest.&lt;anonymous&gt; (http://localhost/imdstagram/public/js/jquery-2.2.3.min.js:4:15680) </code></pre> <p>It says that this error is on line 35, line 35 sends me to </p> <pre><code>console.log(error); </code></pre> <p>Anyway, to give you a better view, here is my Ajax call:</p> <pre><code>$(document).ready(function(){ $(".post__delete").on("click", function(e){ var postDeleteID = $('.deleteID').val(); $.ajax({ url: "ajax/deletePost.php", type: "POST", data: JSON.stringify(postDeleteID), dataType: 'json', contentType: false, cache: false, processData: false, success: function(data) { }, error: function (request, status, error) { console.log(error); } }); e.preventDefault(); }); }); </code></pre> <p>And my deletePost.php code:</p> <pre><code>&lt;?php include_once("../classes/Post.class.php"); session_start(); $post = new Post(); if(!empty($_POST)){ $deletePostID = $_POST['deletePostID']; $post-&gt;deletePost($deletePostID); if($post-&gt;deletePost($deletePostID)){ $status['delete'] = "success"; } else { $status['delete'] = "failed"; } header('Content-Type: application/json; charset=utf-8', true); echo json_encode($status); } ?&gt; </code></pre> <p>I've tried many things like changing the dataType and contentType, but nothing seems to work out. </p>
37,057,786
4
3
null
2016-05-05 18:26:47.63 UTC
1
2021-04-16 17:42:38.233 UTC
2017-03-26 13:54:16.927 UTC
null
472,495
null
4,281,551
null
1
8
javascript|php|jquery|json|ajax
49,916
<p>Your request is wrong, you should not be sending json if you expect to use the $_POST super global. Send it as regular url encoded form data</p> <pre><code> $.ajax({ url: "ajax/deletePost.php", type: "POST", data: {postDeleteID: postDeleteID}, dataType: 'json', cache: false, success: function(data) { }, error: function (request, status, error) { console.log(error); } }); </code></pre>
18,638,741
The type 'Company.Model.User' and the type 'Company.Core.Model.User' both have the same simple name of 'User' and so cannot be used in the same model
<p>I have a base entity class <code>MyCompany.Core.Model.User</code> which is to be used for common properties of a <code>User</code> entity:</p> <pre><code>public class User { public string Username { get; set; } public string Usercode { get; set; } } </code></pre> <p>I also have a base mapping class <code>MyCompany.Core.Model.UserMap</code> to setup the code first mappings for the base <code>User</code> class:</p> <pre><code>public class UserMap&lt;TUser&gt; : EntityMapBase&lt;TUser&gt; where TUser : User { public UserMap() { // Primary Key this.HasKey(t =&gt; t.Usercode); // Table &amp; Column Mappings this.ToTable("Users"); this.Property(t =&gt; t.Username).HasColumnName("Username"); this.Property(t =&gt; t.Usercode).HasColumnName("UserCode"); } } </code></pre> <p>In a separate assembly I have a derived class <code>MyCompany.Model.User</code> that inherits from the base <code>User</code> class and extends it with some additional properties:</p> <pre><code>public class User : Core.User { public string Surname { get; set; } } </code></pre> <p>In addition I have a derived mapping class <code>MyCompany.Model.UserMap</code> to provide the additional configuration for the additional properties:</p> <pre><code>public class UserMap : Core.UserMap&lt;User&gt; { public UserMap() { this.Property(t =&gt; t.Surname).HasColumnName("Surname"); } } </code></pre> <p>However when adding <code>MyCompany.Model.User</code> to the context and registering the <code>MyCompany.Model.UserMap</code> I'm getting the following error:</p> <p><em>The type 'MyCompany.Model.User' and the type 'MyCompany.Core.Model.User' both have the same simple name of 'User' and so cannot be used in the same model. All types in a given model must have unique simple names. Use 'NotMappedAttribute' or call Ignore in the Code First fluent API to explicitly exclude a property or type from the model.</em></p> <p>This <a href="http://blog.oneunicorn.com/2013/03/11/ef6-nested-types-and-more-for-code-first/" rel="noreferrer">link</a> indicates that you can't have the same "simple name" in the model twice.</p> <p><strong>Why is the base class "simple name" being registered in the model, and is there a way around it in order to implement this sort of entity inheritance?</strong> </p> <p>I suspect the simple solution would be to rename the derived class; however I would prefer to avoid this as there may be many derivations in multiple contexts.</p> <p><em>Note: Using Entity Framework 6.0.0-rc1 (prerelease)</em></p>
22,466,391
4
3
null
2013-09-05 14:15:16.177 UTC
1
2022-04-24 08:02:14.417 UTC
null
null
null
null
295,813
null
1
36
entity-framework|inheritance|ef-code-first|entity|entity-framework-6
10,572
<p>This is a limitation of EF that I reported in 2012 <a href="https://entityframework.codeplex.com/workitem/483" rel="noreferrer">https://entityframework.codeplex.com/workitem/483</a> that is still not implemented in 6.0.2. EF uses a flat internal architecture and does not recognize namespaces. Might be coming in EF7 but not before. For now the only solutions is to rename the two classes to unique class names irrespective of the namespace they are in. IMHO, this is an significant limitation within EF. Just consider a class named Category and how many different namespaces it could be used within across a domain.</p>
23,275,877
OpenCV: get perspective matrix from translation & rotation
<p>I'm trying to verify my camera calibration, so I'd like to rectify the calibration images. I expect that this will involve using a call to <code>warpPerspective</code> but I do not see an obvious function that takes the camera matrix, and the rotation and translation vectors to generate the perspective matrix for this call.</p> <p>Essentially I want to do the process described <a href="https://engineering.purdue.edu/kak/courses-i-teach/ECE661.08/solution/hw2_s2.pdf" rel="nofollow noreferrer">here</a> (see especially the images towards the end) but starting with a known camera model and pose.</p> <p>Is there a straightforward function call that takes the camera intrinsic and extrinsic parameters and computes the perspective matrix for use in <code>warpPerspective</code>?</p> <p>I'll be calling <code>warpPerspective</code> after having called <code>undistort</code> on the image.</p> <p>In principle, I could derive the solution by solving the system of equations defined at the top of the <a href="http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html" rel="nofollow noreferrer">opencv camera calibration documentation</a> after specifying the constraint <code>Z=0</code>, but I figure that there must be a canned routine that will allow me to orthorectify my test images.</p> <p>In my seearches, I'm finding it hard to wade through all of the stereo calibration results -- I only have one camera, but want to rectify the image under the constraint that I'm only looking a a planar test pattern.</p>
23,293,723
2
4
null
2014-04-24 17:32:17.45 UTC
13
2020-02-19 10:22:09.01 UTC
2020-02-19 10:22:09.01 UTC
null
14,637
null
1,497,199
null
1
14
opencv|camera-calibration
10,807
<p>Actually there is no need to involve an orthographic camera. Here is how you can get the appropriate perspective transform.</p> <p>If you calibrated the camera using <code>cv::calibrateCamera</code>, you obtained a camera matrix <code>K</code> a vector of lens distortion coefficients <code>D</code> for your camera and, for each image that you used, a rotation vector <code>rvec</code> (which you can convert to a 3x3 matrix <code>R</code> using <code>cv::rodrigues</code>, <a href="http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#rodrigues" rel="noreferrer">doc</a>) and a translation vector <code>T</code>. Consider one of these images and the associated <code>R</code> and <code>T</code>. After you called <code>cv::undistort</code> using the distortion coefficients, the image will be like it was acquired by a camera of projection matrix <code>K * [ R | T ]</code>.</p> <p>Basically (as @DavidNilosek intuited), you want to cancel the rotation and get the image as if it was acquired by the projection matrix of form <code>K * [ I | -C ]</code> where <code>C=-R.inv()*T</code> is the camera position. For that, you have to apply the following transformation:</p> <pre><code>Hr = K * R.inv() * K.inv() </code></pre> <p>The only potential problem is that the warped image might go outside the visible part of the image plane. Hence, you can use an additional translation to solve that issue, as follows:</p> <pre><code> [ 1 0 | ] Ht = [ 0 1 | -K*C/Cz ] [ 0 0 | ] </code></pre> <p>where Cz is the component of C along the Oz axis. </p> <p>Finally, with the definitions above, <code>H = Ht * Hr</code> is a rectifying perspective transform for the considered image.</p>
5,096,630
How to split string using delimiter char using T-SQL?
<p>I have this long string in one of the columns of the table. I want to get only specific information:- My Table structure:-</p> <pre><code>Col1 = '123' Col2 = 'AAAAA' Col3 = 'Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800' </code></pre> <p>My select statement is:-</p> <pre><code>Select col1, col2, col3 from Table01 </code></pre> <p>But in Col3 I just need 'Client Name's value which is 'B B BOB'. </p> <p>In Col3 -</p> <ul> <li><p>Column delimiter is '|' pipe char (eg. 'Client ID = 4356hy') </p></li> <li><p>Key Value delimiter is ' = ' equal to sign with one white space (leading and trailing).</p></li> </ul> <p>Please help.</p>
5,096,929
4
2
null
2011-02-23 20:23:03.103 UTC
3
2015-05-18 14:52:01.31 UTC
2011-02-23 20:25:04.007 UTC
null
13,302
null
584,933
null
1
8
sql|sql-server|sql-server-2005|tsql
115,811
<p>For your specific data, you can use</p> <pre><code>Select col1, col2, LTRIM(RTRIM(SUBSTRING( STUFF(col3, CHARINDEX('|', col3, PATINDEX('%|Client Name =%', col3) + 14), 1000, ''), PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3 from Table01 </code></pre> <h3>EDIT - charindex vs patindex</h3> <p>Test</p> <pre><code>select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800' into t1m from master..spt_values a cross join master..spt_values b where a.number &lt; 100 -- (711704 row(s) affected) set statistics time on dbcc dropcleanbuffers dbcc freeproccache select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m drop table #tmp1 dbcc dropcleanbuffers dbcc freeproccache select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m drop table #tmp2 set statistics time off </code></pre> <p>Timings</p> <pre><code>CHARINDEX: SQL Server Execution Times (1): CPU time = 5656 ms, elapsed time = 6418 ms. SQL Server Execution Times (2): CPU time = 5813 ms, elapsed time = 6114 ms. SQL Server Execution Times (3): CPU time = 5672 ms, elapsed time = 6108 ms. PATINDEX: SQL Server Execution Times (1): CPU time = 5906 ms, elapsed time = 6296 ms. SQL Server Execution Times (2): CPU time = 5860 ms, elapsed time = 6404 ms. SQL Server Execution Times (3): CPU time = 6109 ms, elapsed time = 6301 ms. </code></pre> <p>Conclusion</p> <p>The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.</p>
43,404,877
Pandas how to concat two dataframes without losing the column headers
<p>I have the following toy code: </p> <pre><code> import pandas as pd df = pd.DataFrame() df["foo"] = [1,2,3,4] df2 = pd.DataFrame() df2["bar"]=[4,5,6,7] df = pd.concat([df,df2], ignore_index=True,axis=1) print(list(df)) </code></pre> <p>Output: <code>[0,1]</code><br> Expected Output: <code>[foo,bar]</code> (order is not important)<br> Is there any way to concatenate two dataframes without losing the original column headers, if I can guarantee that the headers will be unique?<br> Iterating through the columns and then adding them to one of the DataFrames comes to mind, but is there a pandas function, or <code>concat</code> parameter that I am unaware of?</p> <p>Thanks!</p>
43,406,062
1
3
null
2017-04-14 03:41:54.513 UTC
4
2017-04-14 06:19:18.487 UTC
null
null
null
null
5,699,807
null
1
22
python|pandas
48,410
<p>As stated in <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-with-mixed-ndims" rel="noreferrer">merge, join, and concat</a> documentation, ignore index will remove all name references and use a range (0...n-1) instead. So it should give you the result you want once you remove <code>ignore_index</code> argument or set it to false (default).</p> <pre><code>df = pd.concat([df, df2], axis=1) </code></pre> <p>This will join your df and df2 based on indexes (same indexed rows will be concatenated, if other dataframe has no member of that index it will be concatenated as nan). </p> <p>If you have different indexing on your dataframes, and want to concatenate it this way. You can either create a temporary index and join on that, or set the new dataframe's columns after using concat(..., ignore_index=True).</p>
18,572,401
jQuery select change show/hide div event
<p>I am trying to create a form which when the select element 'parcel' is selected it will show a div but when it is not selected I would like to hide the div. Here is my markup at the moment:</p> <p>This is my HTML so far..</p> <pre><code> &lt;div class="row"&gt; Type &lt;select name="type" id="type" style="margin-left:57px; width:153px;"&gt; &lt;option ame="l_letter" value="l_letter"&gt;Large Letter&lt;/option&gt; &lt;option name="letter" value="letter"&gt;Letter&lt;/option&gt; &lt;option name="parcel" value="parcel"&gt;Parcel&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="row" id="row_dim"&gt; Dimensions &lt;input type="text" name="length" style="margin-left:12px;" class="dimension" placeholder="Length"&gt; &lt;input type="text" name="width" class="dimension" placeholder="Width"&gt; &lt;input type="text" name="height" class="dimension" placeholder="Height"&gt; &lt;/div&gt; </code></pre> <p>This is my jQuery so far..</p> <pre><code> $(function() { $('#type').change(function(){ $('#row_dim').hide(); $("select[@name='parcel']:checked").val() == 'parcel').show(); }); }); </code></pre>
18,572,585
10
0
null
2013-09-02 11:39:09.8 UTC
10
2022-06-20 06:36:58.567 UTC
null
null
null
null
2,716,389
null
1
11
jquery|html|hide|show
149,541
<p>Use following JQuery. <a href="http://jsfiddle.net/Y3pW9/" rel="noreferrer">Demo</a></p> <pre><code>$(function() { $('#row_dim').hide(); $('#type').change(function(){ if($('#type').val() == 'parcel') { $('#row_dim').show(); } else { $('#row_dim').hide(); } }); }); </code></pre>
18,619,785
Counting frequency of characters in a string using JavaScript
<p>I need to write some kind of loop that can count the frequency of each letter in a string.</p> <p>For example: <code>&quot;aabsssd&quot;</code></p> <p>output: <code>a:2, b:1, s:3, d:1</code></p> <p>Also want to map same character as property name in object. Any good idea how to do this?</p> <p>I am not sure how to do it.</p> <p>This is where I am so far:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; function counter(x) { var count = 0, temp = []; x = x.split(''); console.log(x); for (var i = 0, len = x.length; i &lt; len; i++) { if (x[i] == "a") { count++; } } return count; } var a = "aabbddd"; console.log(counter(a));</code></pre> </div> </div> </p>
18,619,975
21
6
null
2013-09-04 17:02:06.627 UTC
16
2022-06-04 09:48:44.86 UTC
2021-03-16 15:09:27.297 UTC
null
6,904,888
null
2,522,642
null
1
20
javascript
76,290
<p>Here you go:</p> <pre><code>function getFrequency(string) { var freq = {}; for (var i=0; i&lt;string.length;i++) { var character = string.charAt(i); if (freq[character]) { freq[character]++; } else { freq[character] = 1; } } return freq; }; </code></pre>
15,407,652
How can I run `git diff --staged` with Fugitive?
<p>The command <code>:Gdiff</code> is equivalent to running <code>git diff</code> on that file.</p> <p>What's the equivalent for <code>git diff --staged</code> or <code>git diff --cached</code>?</p>
25,443,177
7
0
null
2013-03-14 11:13:43.52 UTC
8
2022-07-21 09:34:14.96 UTC
null
null
null
null
247,696
null
1
29
vim-fugitive
6,279
<p>I've found a way to do this. Run <code>:Git</code>, you should get a window with contents like the following:</p> <pre><code># Head: master # Merge: origin/master # Help: g? # # Staged (1) # M example.txt # </code></pre> <p>Scroll down to the staged file, <code>example.txt</code>, and press <kbd>d</kbd><kbd>d</kbd>. This will open a diff view, comparing what's in HEAD and what's in the index. You'll notice on the bar on the bottom that both the filenames are special Fugitive filenames.</p> <p>Also while in <code>:Git</code> preview window, you can press <kbd>g</kbd><kbd>?</kbd>, which will list all the mappings valid in the current context.</p>
15,006,554
git: merge branch and use meaningful merge commit message?
<p>After I merge a feature branch back to main branch I usually need to do a merge commit by default. But I'd like to use the original commit messages from my feature branch in this commit instead of "merge branch XXX". </p> <p>How should I do that?</p>
15,030,847
5
0
null
2013-02-21 15:52:32.42 UTC
12
2020-03-02 03:13:31.213 UTC
null
null
null
null
987,846
null
1
41
git|version-control|branching-and-merging
47,736
<p>I found that after doing the merge commit. I can add an amendment commit "git ci --amend" to change the commit message, which does exactly what I asked for. I'll accept my own answer as the correct answer.</p> <p>Simon Boudrias and ranendra gave relevant answers that are also effective in a different way. So I voted them up.</p>
14,978,296
Unable to start activity:UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
<p>I want to write a <code>ListView</code> in basic format but I get an error:</p> <pre><code>UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView </code></pre> <p>and:</p> <pre><code>androidview.LayoutInfalater.inflate(LayoutInflater.java: some numbers....like 720,658...so on) </code></pre> <p>I know something should be done here in the adapter class:</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub RelativeLayout rv = new RelativeLayout(c); TextView tv = new TextView(c); TextView tv1 = new TextView(c); ImageView imgv = new ImageView(c); tv.setText(s[position]); tv1.setText(i[position]); imgv.setImageResource(d[position]); rv.addView(tv); rv.addView(tv1); rv.addView(imgv); return rv; } </code></pre> <p>What should I do to solve the problems</p> <p>The LOGCAT:</p> <pre><code>02-20 16:40:24.967: E/Trace(1715): error opening trace file: No such file or directory (2) 02-20 16:40:25.819: W/ResourceType(1715): No package identifier when getting value for resource number 0x000020d0 02-20 16:40:25.819: D/AndroidRuntime(1715): Shutting down VM 02-20 16:40:25.819: W/dalvikvm(1715): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 02-20 16:40:25.857: E/AndroidRuntime(1715): FATAL EXCEPTION: main 02-20 16:40:25.857: E/AndroidRuntime(1715): android.content.res.Resources$NotFoundException: String resource ID #0x20d0 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.content.res.Resources.getText(Resources.java:229) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.TextView.setText(TextView.java:3620) 02-20 16:40:25.857: E/AndroidRuntime(1715): at com.example.systemzap2.adapt.getView(adapt.java:59) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.AbsListView.obtainView(AbsListView.java:2271) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.ListView.measureHeightOfChildren(ListView.java:1244) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.ListView.onMeasure(ListView.java:1156) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.View.measure(View.java:15172) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.View.measure(View.java:15172) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.View.measure(View.java:15172) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.LinearLayout.measureVertical(LinearLayout.java:833) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.View.measure(View.java:15172) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 02-20 16:40:25.857: E/AndroidRuntime(1715): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.View.measure(View.java:15172) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.Choreographer.doCallbacks(Choreographer.java:555) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.Choreographer.doFrame(Choreographer.java:525) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.os.Handler.handleCallback(Handler.java:615) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.os.Handler.dispatchMessage(Handler.java:92) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.os.Looper.loop(Looper.java:137) 02-20 16:40:25.857: E/AndroidRuntime(1715): at android.app.ActivityThread.main(ActivityThread.java:4745) 02-20 16:40:25.857: E/AndroidRuntime(1715): at java.lang.reflect.Method.invokeNative(Native Method) 02-20 16:40:25.857: E/AndroidRuntime(1715): at java.lang.reflect.Method.invoke(Method.java:511) 02-20 16:40:25.857: E/AndroidRuntime(1715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 02-20 16:40:25.857: E/AndroidRuntime(1715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 02-20 16:40:25.857: E/AndroidRuntime(1715): at dalvik.system.NativeStart.main(Native Method) </code></pre>
14,978,952
5
4
null
2013-02-20 11:05:53.717 UTC
9
2021-01-31 18:45:56.953 UTC
2013-02-20 11:42:51.677 UTC
null
493,939
null
2,082,031
null
1
41
android|android-listview|android-adapterview
42,713
<blockquote> <p>what should i do???</p> </blockquote> <p>Correct your code.</p> <blockquote> <p>UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView</p> </blockquote> <p>A subclass of <code>AdapterView</code> like a <code>ListView</code> <strong>can't</strong> have children manually added either in the layout file or added in code. So if you have this in one of your layouts:</p> <pre><code>&lt;ListView // .. other attributes&gt; &lt;// other views &lt;-- notice the children of the ListView tag &lt;/ListView&gt; </code></pre> <p><strong>don't do it</strong>, as this will call the <code>addView</code> method of <code>ListView</code>, throwing the exception. Instead use:</p> <pre><code>&lt;ListView // .. other attributes /&gt; &lt; // other views </code></pre> <p>You also <strong>can't</strong> use any of the <code>addView</code> methods of <code>ListView</code> in code like this:</p> <pre><code>listViewReference.addView(anotherView); // &lt;-- don't do it </code></pre> <p>Also, if you use the <code>LayoutInflater.inflate</code> method in the code of the <code>Activity</code> or the adapter(its <code>getView</code> method), <strong>don't pass</strong> the <code>ListView</code> as the second parameter. For example, <strong>don't use</strong>:</p> <pre><code>convertView = inflator.inflate(R.layout.child_rows, parent); </code></pre> <p>as in Tamilarasi Sivaraj's answer as that will throw the exception again. Instead use:</p> <pre><code>convertView = inflator.inflate(R.layout.child_rows, parent, false); </code></pre> <p>Related to the exception you posted in the question, it appears you use the <code>setText</code> method with an <code>int</code>(one of the <code>s</code> or <code>i</code> arrays being an <code>int</code> array). The problem is that in this case <code>TextView</code> will think you're trying to set the text using a string resource like this <code>R.string.astring</code>. The <code>int</code> you pass is not a string resource so an exception will be thrown. If <code>s</code> or <code>i</code> is an <code>int</code> and you're trying to show it in the <code>TextView</code> use this instead:</p> <pre><code>tv.setText(String.valueOf(s[position])); // assuming s is the int array </code></pre>
15,213,211
Update an Android app (without Google Play store visit)
<p>I wrote a Beta version of the application. It will be available for download through the web (I will not publish it to the Play Market). Is it possible to update this application without Play Market visit when the new version will be released?</p>
15,213,350
5
3
null
2013-03-04 23:35:56.073 UTC
63
2021-07-06 14:22:15.843 UTC
2021-07-06 14:22:15.843 UTC
null
2,638,235
null
2,105,213
null
1
65
android|google-play-services|google-play-core
93,414
<p>Absolutely. You will need to build a mechanism, though, for your app to call home to the server, find out if there's a newer version of the app, and if there is, pull it down and install it. Once you've determined that you do need to pull down an update, you can do that with something similar to this AsyncTask:</p> <pre><code>protected String doInBackground(String... sUrl) { String path = "/sdcard/YourApp.apk"; try { URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); // download the file InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(path); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { Log.e("YourApp", "Well that didn't work out so well..."); Log.e("YourApp", e.getMessage()); } return path; } // begin the installation by opening the resulting file @Override protected void onPostExecute(String path) { Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive" ); Log.d("Lofting", "About to install new .apk"); this.context.startActivity(i); } </code></pre>
15,257,555
Rails: How to reference images in CSS within Rails 4
<p>There's a strange issue with Rails 4 on Heroku. When images are compiled they have hashes added to them, yet the reference to those files from within CSS don't have the proper name adjusted. Here's what I mean. I have a file called logo.png. Yet when it shows up on heroku it is viewed as:</p> <pre><code>/assets/logo-200a00a193ed5e297bb09ddd96afb953.png </code></pre> <p>However the CSS still states:</p> <pre><code>background-image:url("./logo.png"); </code></pre> <p>The result: the image doesn't display. Anybody run into this? How can this be resolved?</p>
15,591,726
17
2
null
2013-03-06 20:40:55.01 UTC
80
2020-08-13 21:26:00.887 UTC
2020-08-13 21:26:00.887 UTC
null
10,907,864
null
812,939
null
1
212
ruby-on-rails|heroku|ruby-on-rails-4
169,060
<p>Sprockets together with Sass has <a href="http://guides.rubyonrails.org/asset_pipeline.html#css-and-sass" rel="noreferrer">some nifty helpers</a> you can use to get the job done. Sprockets will <em>only</em> process these helpers if your stylesheet file extensions are either <code>.css.scss</code> or <code>.css.sass</code>.</p> <hr> <p><strong>Image specific helper:</strong></p> <pre><code>background-image: image-url("logo.png") </code></pre> <hr> <p><strong>Agnostic helper:</strong></p> <pre><code>background-image: asset-url("logo.png", image) background-image: asset-url($asset, $asset-type) </code></pre> <hr> <p>Or if you want to embed the image data in the css file:</p> <pre><code>background-image: asset-data-url("logo.png") </code></pre>
38,098,763
PySide - PyQt : How to make set QTableWidget column width as proportion of the available space?
<p>I'm developing a computer application with <em>PySide</em> and I'm using the QTableWidget. Let's say my table has 3 columns, but the data they contain is very different, like (for each row) a long sentence in the first column, then 3-digit numbers in the two last columns. I'd like <strong>to have my table resize in order to adjust its size to the data</strong>, or at least to be able <strong>to set the column sizes as (say) 70/15/15 % of the available space</strong>.</p> <p>What is the best way to do this ?</p> <p>I've tried <code>table.horizontalHeader().setResizeMode(QHeaderView.Stretch)</code> after reading <a href="https://stackoverflow.com/questions/11839813/how-to-make-qtablewidgets-columns-assume-the-maximum-space">this question</a> but it makes 3 columns of the same size.</p> <p>I've also tried <code>table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)</code> thanks to <a href="https://stackoverflow.com/users/3770506/fabio">Fabio</a>'s <a href="https://stackoverflow.com/questions/38098763/pyside-pyqt-how-to-make-set-qtablewidget-column-width-as-proportion-of-the-a?noredirect=1#comment63632916_38098763">comment</a> but it doesn't fill all the available space as needed.</p> <p>Neither <code>Interactive</code>, <code>Fixed</code>, <code>Stretch</code>, <code>ResizeToContents</code> from the <a href="http://doc.qt.io/qt-4.8/qheaderview.html#ResizeMode-enum" rel="noreferrer">QHeaderView documentation</a> seem to give me what I need (see second edit).</p> <p>Any help would be appreciated, even if it is for <em>Qt/C++</em> ! Thank you very much.</p> <hr> <p><strong>EDIT :</strong> I found kind of a workaround but it's still not what I'm looking for :</p> <pre><code>header = table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) </code></pre> <p>It would be better if there existed a <code>setStretchFirstSection</code> method, but unfortunately there does not seem to be one.</p> <hr> <p><strong>EDIT 2 :</strong></p> <p>The only thing that can be modified in the table is the last column, the user can enter a number in it. Red arrows indicates what I'd like to have.</p> <p>Here's what happens with <code>Stretch</code><a href="https://i.stack.imgur.com/NCFXM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NCFXM.png" alt="Stretch"></a></p> <p>Here's what happens with <code>ResizeToContents</code> <a href="https://i.stack.imgur.com/DZeGg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DZeGg.png" alt="ResizeToContents"></a></p>
38,129,829
8
3
null
2016-06-29 11:53:39.08 UTC
14
2022-09-19 03:56:38.01 UTC
2017-05-23 12:32:11.663 UTC
null
-1
null
5,018,771
null
1
38
python|qt|user-interface|pyqt|pyside
93,929
<p>This can be solved by setting the resize-mode for each column. The first section must stretch to take up the available space, whilst the last two sections just resize to their contents:</p> <p>PyQt4:</p> <pre><code>header = self.table.horizontalHeader() header.setResizeMode(0, QtGui.QHeaderView.Stretch) header.setResizeMode(1, QtGui.QHeaderView.ResizeToContents) header.setResizeMode(2, QtGui.QHeaderView.ResizeToContents) </code></pre> <p>PyQt5:</p> <pre><code>header = self.table.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents) </code></pre>
28,294,509
Accessing Kotlin extension functions from Java
<p>Is it possible to access extension functions from Java code?</p> <p>I defined the extension function in a Kotlin file.</p> <pre><code>package com.test.extensions import com.test.model.MyModel /** * */ public fun MyModel.bar(): Int { return this.name.length() } </code></pre> <p>Where <code>MyModel</code> is a (generated) java class. Now, I wanted to access it in my normal java code:</p> <pre><code>MyModel model = new MyModel(); model.bar(); </code></pre> <p>However, that doesn't work. <strong>The IDE won't recognize the <code>bar()</code> method and compilation fails.</strong> </p> <p>What does work is using with a static function from kotlin:</p> <pre><code>public fun bar(): Int { return 2*2 } </code></pre> <p>by using <code>import com.test.extensions.ExtensionsPackage</code> so my IDE seems to be configured correctly.</p> <p>I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.</p> <p>What am I doing wrong? Is this even possible?</p>
28,364,983
9
3
null
2015-02-03 08:37:56.023 UTC
20
2021-02-27 18:32:08.57 UTC
2015-02-03 08:55:46.37 UTC
null
1,096,567
null
1,096,567
null
1
226
java|kotlin|extension-function
67,721
<p>All Kotlin functions declared in a file will be compiled by default to static methods in a class within the same package and with a name derived from the Kotlin source file (First letter capitalized and <em>".kt"</em> extension replaced with the <em>"Kt"</em> suffix). Methods generated for extension functions will have an additional first parameter with the extension function receiver type.</p> <p>Applying it to the original question, Java compiler will see Kotlin source file with the name <em>example.kt</em></p> <pre><code>package com.test.extensions public fun MyModel.bar(): Int { /* actual code */ } </code></pre> <p>as if the following Java class was declared</p> <pre><code>package com.test.extensions class ExampleKt { public static int bar(MyModel receiver) { /* actual code */ } } </code></pre> <p>As nothing happens with the extended class from the Java point of view, you can't just use dot-syntax to access such methods. But they are still callable as normal Java static methods:</p> <pre><code>import com.test.extensions.ExampleKt; MyModel model = new MyModel(); ExampleKt.bar(model); </code></pre> <p>Static import can be used for ExampleKt class:</p> <pre><code>import static com.test.extensions.ExampleKt.*; MyModel model = new MyModel(); bar(model); </code></pre>
8,186,113
RVM: specify a ruby version to use
<p>I know how to use RVM, but now I have a weird problem, which I do not understand why.</p> <p>Here is the simple story (I am using Ubuntu):</p> <p>I have created a Rails project, the direcotry of this project is "bookstore/".</p> <p>I go to project directory by <code>cd bookstore</code> , and type command <code>rvm list</code> like following:</p> <pre><code>bookstore/$ rvm list rvm rubies ruby-1.9.2-p136 [ i386 ] ruby-1.8.7-p352 [ i386 ] ruby-1.8.7-p330 [ i386 ] ruby-1.8.6-p420 [ i386 ] ruby-1.9.2-p290 [ i386 ] </code></pre> <p>Since I did not see the <code>=&gt;</code> arrow sign which is supposed to indicate the current ruby version in use, so I specify the ruby version with the following <strong>RVM</strong> command:</p> <pre><code>bookstore/$ rvm use ruby-1.9.2-p290 Using /home/usr/.rvm/gems/ruby-1.9.2-p290 </code></pre> <p>Now, if I <code>rvm list</code> I see my project is using <strong>ruby v1.9.2</strong> :</p> <pre><code>bookstore/$ rvm list rvm rubies ruby-1.9.2-p136 [ i386 ] ruby-1.8.7-p352 [ i386 ] ruby-1.8.7-p330 [ i386 ] ruby-1.8.6-p420 [ i386 ] =&gt; ruby-1.9.2-p290 [ i386 ] </code></pre> <p><strong>Every thing works fine at this point!</strong></p> <p><strong>But</strong>, if now I <strong>open a new terminal window</strong> on Ubuntu, and <code>cd</code> to the project directory, and run the command <code>rvm list</code> again, I got:</p> <pre><code>bookstore/$ rvm list rvm rubies ruby-1.9.2-p136 [ i386 ] ruby-1.8.7-p352 [ i386 ] ruby-1.8.7-p330 [ i386 ] ruby-1.8.6-p420 [ i386 ] ruby-1.9.2-p290 [ i386 ] </code></pre> <p>Where is the <code>=&gt;</code> to indicate the ruby version I specified previously? <strong>Why it again needs me to specify the ruby version?</strong> </p> <p>It happens always when I <strong>open a new terminal window</strong>. How to have my project "remember" the ruby version I have specified? </p>
8,186,256
2
0
null
2011-11-18 17:05:31.607 UTC
9
2012-09-29 16:39:23.233 UTC
2011-11-18 17:18:49.2 UTC
null
249,630
null
475,850
null
1
21
ruby-on-rails|ruby-on-rails-3|ruby-on-rails-3.1|rvm
15,854
<p>Dave is right, you should set a default. But also, look into defining an <a href="http://beginrescueend.com/workflow/rvmrc/" rel="noreferrer"><code>.rvmrc</code></a> file on a per-project or per-machine basis. I use project-specific rvmrc files, so I can use different rubies and gemsets for each project, and changing into the directory automatically switches to that project's ruby/gemset.</p> <p>For example, my rvmrc for company site project:</p> <pre><code>brett@bender:~/Sites/bearded/bearded(master)$ cat .rvmrc rvm 1.9.3@bearded </code></pre> <p><strong>Edit:</strong> For explicitness' sake, to solve your problem using an rvmrc file, do the following (assuming you already installed the ruby version you want and created a gemset for this project's gems):</p> <ol> <li>Create a file in <code>bookstore/</code> directory named <code>.rvmrc</code> (in your favorite editor)</li> <li>Add <code>rvm ruby-1.9.2-p290</code> to the file and save it (you can use <code>rvm ruby-1.9.2-p290@gemset_name</code> if you have a gemset you want to default to)</li> <li>Change directory out of your bookstore directory, then change back into it.</li> <li>RVM should ask you if you want to trust this .rvmrc file (yes)</li> <li>RVM should have automatically switched your active ruby and gemset to the ones specified in your rvmrc file for that project.</li> </ol> <p>Also note that if your RVM is older than version 1.8.0 you will need to turn on rvmrc file support (versions 1.8.0+ have it turned on by default). The link at the top of my question contains instructions if you're so inclined.</p>
8,184,512
Ajax Forms with Rails 3 - Best Practice?
<h1>What is considered the Rails Way for Ajax Forms</h1> <p>Until today I thought the way I use Rails forms + jQuery UJS was the right way to do it, but the upgrade to jQuery 1.7 'broked' the way I did it so far.</p> <h2>How to do this?</h2> <p>I want to use Ajax with my forms. The ajax response should either render the form again (e.g. when errors occur) or redirect to a success page. (It should maybe do more, like showing modals, but I want to keep this example simple).</p> <h3>1. Using EJS and $('#formid').html(...) </h3> <p>That is what I did until to date. My ajax response was an ejs template which returned javascript code to render the form again (with errors) or depending if it was an error redirected the user to success page: </p> <pre><code>&lt;% unless @success_submit %&gt; $('#form_wrapper').html('&lt;%= escape_javacsript( render :partial =&gt; 'form' ) %&gt;'); &lt;% else %&gt; document.location = '/success_thank_you'; &lt;% endif %&gt; </code></pre> <p>Now imagine the form contains an error message div like</p> <pre><code>&lt;div class="error_message"&gt;BlaBla&lt;/div&gt; </code></pre> <p>To add a nice effect I had a general jQuery.live event bound on ajax complete which highlighted errors.</p> <pre><code>$('form').live('ajax:complete', function() { // do stuff like highlighting all error messages in that form }); </code></pre> <p>That doesn't work with jQuery1.7 + jquery-ujs anymore (probably by good reasons). So I guess the way I did it was not right.</p> <h3>2. Using above way but repeat myself</h3> <p>Instead of binding the ajax:complete event I could do the "error highlighting stuff" in the EJS like</p> <pre><code>$('#form_wrapper').html('&lt;%= escape_javascript( render :partial =&gt; 'form' ) %&gt;'); $('#form_wrapper form .error_message').fadeIn(); </code></pre> <p>But that would mean I would have to repeat the second line in almost each EJS which renders forms. And of course I want to keep it DRY. </p> <h3>3. Ajax response renders pure html, ajax:complete event handles display </h3> <p>A complete different solution would be that the ajax response simply would render pure html and my custom ajax:complete handler would take care of displaying the form. The handler would look like</p> <pre><code>$('form').live('ajax:success', function(ev, data, status, xhr) { $(this).html(data); // and e.g. highlight stuff $(this).children('.error_message').fadeIn(); }); </code></pre> <p>That would work. But now what should I do if my server decides not to render the form again (e.g. after successful signup) but instead redirect to another url or showing a modal form. The server could respond with something like that</p> <pre><code>&lt;script&gt; document.location = '/success.blabla/'; &lt;/script&gt; </code></pre> <p>But is that a good solution ?</p> <h3>4. Custom JSON protocol </h3> <p>Probably a good solution would be to use version 3 but instead of simply replacing the current form with the returned html we could create some custom json protocol. That way we could even let the server respond with stuff like</p> <ol> <li>first show modal ( like 'Signup Success')</li> <li>redirect to login page</li> </ol> <p>The ajax:success handler could check if the response is pure html, in that case it would replace the current form with the html code. But if the response is a JSON array it would handle that, e.g. server responds with </p> <pre><code>{ html: '&lt;%= render :partial =&gt; 'something' %&gt;', show_modal: '&lt;%= render :partial =&gt; 'modal_template' %&gt;', redirect_after_modal: '/login_page' } </code></pre> <p>The ajax:success handler would have handle it like </p> <pre><code>$('form').live('ajax:success', function(ev, data, status, xhr) { // try parsing json if (data.json['show_modal') { // show modal code.... }; if (data.json['redirect']) { document.location=data.json['redirect']);... }); </code></pre> <h2>How are you doing this stuff </h2> <p>Obviously there are many ways how you handle ajax forms. But how are you doing it, and what is considered best practice with Rails ?</p>
8,185,848
2
0
null
2011-11-18 15:06:44.213 UTC
14
2013-05-20 17:35:32.633 UTC
2011-11-18 15:28:56.317 UTC
null
927,963
null
927,963
null
1
22
ruby-on-rails|ajax|forms|unobtrusive-javascript
8,344
<p>So, I was able to boil your issue down to jquery only, and sure enough, it <a href="http://jsfiddle.net/nAaMd/4/" rel="noreferrer">works in jquery 1.6.4</a>, but <a href="http://jsfiddle.net/nAaMd/5/" rel="noreferrer">not in jquery 1.7</a>.</p> <p>It seems that if you replace an element in the DOM, and then trigger an event on the jquery object created from the original element, 1.6.4 would still trigger the event in the elements original location and allow it to propagate up the DOM. 1.7, however, will not trigger the element (which makes more sense).</p> <p>I just did a search through the jquery 1.7 changelog and sure enough, here are the two tickets which rectified this behavior: <a href="http://bugs.jquery.com/ticket/9951" rel="noreferrer">9951</a> and <a href="http://bugs.jquery.com/ticket/10489" rel="noreferrer">10489</a>.</p> <p>To answer your question about what <em>is</em> the best practice for accomplishing something like this, I would say, take control over what order your events fire. jQuery automatically executes JS returned in ajax responses, which means you have no control over when that happens.</p> <p>The easiest way to modify your code would be to return the HTML partial itself, and then use jquery to replace the form with the returned HTML in the <code>ajax:complete</code> or <code>ajax:success</code>/<code>ajax:error</code> handlers. This way you can be sure that things happen in the exact order you want.</p> <p>To see how exactly to accomplish this, try reading [my articles]:</p> <ul> <li><a href="http://www.alfajango.com/blog/rails-3-remote-links-and-forms/" rel="noreferrer">http://www.alfajango.com/blog/rails-3-remote-links-and-forms/</a></li> <li><a href="http://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/" rel="noreferrer">http://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/</a></li> <li><a href="http://railsdog.com/blog/2011/02/28/callbacks-in-jquery-ujs-in-rails3/" rel="noreferrer">http://railsdog.com/blog/2011/02/28/callbacks-in-jquery-ujs-in-rails3/</a></li> </ul> <p>Or see <a href="https://github.com/rails/jquery-ujs/wiki" rel="noreferrer">the jquery-ujs wiki</a> for these links and more.</p>
8,992,716
Installing Oracle 11g on OSX
<p>I would like to run a complete SOA/OSB development environment on OSX.<br> Unfortunately, Oracle 11g (SOA and OSB) is missing OSX installers.</p> <p>Is it possible to run a <strong>native development environment</strong> on OSX ?</p> <p>I need Oracle Enterprise Pack Extensions, OSB extension, jDeveloper and SOA composites to work natively.</p>
8,992,735
2
3
null
2012-01-24 19:17:42.593 UTC
8
2015-05-07 03:48:42.783 UTC
2015-05-07 03:48:42.783 UTC
null
258,689
null
258,689
null
1
17
macos|oracle11g|soa|jdeveloper|osb
46,815
<p>Yes! The fact that Oracle doesn't provide a OSX installer doesn't mean these product shouldn't work natively. Most of them are actually 100% Java.</p> <p>Please follow the instructions below to install you development environment.</p> <p>Instructions are for 11g 11.1.1.4.0 but were also tested with 11.1.1.5.0. The trick is to run the installer via a Linux VM and migrate the files to OSX.</p> <h2>Linux VM Installation</h2> <p>It doesn't really matter if you get a 32 or 64 bits Linux distribution. However, the installation folder should be the same on Linux and MacOS.</p> <ol> <li>Download VirtualBox and create a Virtual Machine for Linux. Since we are dealing with Oracle products, rather user their linux distribution: look for this file on google <strong>OracleLinux-R5-U7-Server-i386-dvd.iso</strong></li> <li>With the VM installed, up and running, boot into Linux.</li> <li>Install JDK 1.6 for Linux 32 bits</li> </ol> <p>Download the following software, oracle offers native installers for windows and Linux. However you should stick to generic downloads as much as possible. Some of these packages come in several zips, extract files according to oracle directions.</p> <ul> <li>Weblogic &amp; coherence: wls1034_generic.jar</li> <li>OEPE: oepe-helios-all-in-one-11.1.1.6.1.201010012100-win32-x86_64.zip</li> <li>jDeveloper: jdevstudio11114install.jar</li> <li>OSB: ofm_osb_generic_11.1.1.4.0</li> <li>SOA: soa_generic_11.1.1.4.0</li> </ul> <p>Install the software in the following order</p> <ol> <li>Weblogic &amp; Coherence: run with <strong>java -Xmx1024m -jar -Dos.name=unix wls1034_generic.jar</strong></li> <li>OEPE extract act in a folder called /oepe</li> <li>OSB Disk1/runInstaller - Make sure OSB IDE extensions are being installed (in OEPE)</li> <li>SOA Disk1/runInstaller</li> <li>jDeveloper</li> </ol> <h2>OSX Installation</h2> <h3>Middleware</h3> <p>Here comes the trick, copy the oOracle Middleware folder from your Linux VM to OSX. Make sure the location is the same. For instance if you installed under /Oracle/Middleware on Linux, you should copy to /Oracle/Middleware on OSX.</p> <h3>Fix JVM</h3> <p>For some obscure reasons, Oracle installers don't recognize the Apple JVM. While not mandatory, it is good practices to fix the issue with the following script.</p> <pre><code> $ sudo mkdir -p /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/jre/lib $ cd /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/jre/lib $ sudo ln -s /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/classes/classes.jar rt.jar </code></pre> <h3>OEPE</h3> <ol> <li>Download the following software (64bits please!) <strong>oepe-helios-all-in-one-11.1.1.6.2.201111102323-macosx-cocoa-x86_64.zip</strong></li> <li>Extract the file into /oepemac</li> <li>Right click on Eclipse.app</li> <li>On the opened menu, choose “Show Package Contents”</li> <li><p>Edit file “/Contents/MacOS/eclipse.ini”, append the following lines</p> <p>-Dweblogic.home=/Oracle/Middleware/wlserver_10.3<br> -Dharvester.home=/Oracle/Middleware/Oracle_OSB1/harvester<br> -Dosb.home=/Oracle/Middleware/Oracle_OSB1<br> -Dosgi.bundlefile.limit=750<br> -Dosgi.nl=en_US </p></li> <li><p>Now copy the file <strong>oracle.osb.ide.link</strong> from the folder “oepe/dropins” to “oepemac/dropins” (both under your middleware home).</p></li> </ol> <h3>Oracle XE</h3> <p>Oracle_XE is unfortunately not supported on OSX. we will need to run it via a VirtualBox appliance. The good news is that Oracle provides a easy to install RPM.</p> <ol> <li>Download <strong>oracle-xe-10.2.0.1-1.0.i386.rpm</strong></li> <li>Under Linux, as root, run 'rpm -i oracle-xe-10.2.0.1-1.0.i386.rpm'</li> <li>Next step is to download and run <strong>Oracle RCU</strong> to prepare the data model, please refer to the next section for directions.</li> </ol> <p>For reference, we allocated 1cpu, 600MB of ram to our Linux/OracleXE VM.</p> <h2>Next Steps</h2> <p>Configure your web logic development domain. Please refer to this document for instructions. <strong>Quick Start Guide for Oracle® SOA Suite 11gR1 (11.1.1.5.0).pdf</strong></p> <h3>Fix startup scripts</h3> <p>Finally, you will need to fix domain startup script as follows</p> <p>------------- user_projects/domains/DEVdomain/bin/setDomainEnv.sh -------------</p> <pre><code>index f74490c..8d75c6c 100755 @@ -108,7 +108,7 @@ else else JAVA_VENDOR="Unknown" export JAVA_VENDOR - JAVA_HOME="/usr/java/jdk1.6.0_21" + JAVA_HOME=`/usr/libexec/java_home` export JAVA_HOME fi fi </code></pre> <p>------------ user_projects/domains/DEVdomain/bin/setSOADomainEnv.sh ------------</p> <pre><code>index 8c6743b..b92cfa4 100755 @@ -144,6 +144,15 @@ case ${PLATFORM_TYPE} in fi export USER_MEM_ARGS ;; +#----------------------------------------------------- +# OSX +#----------------------------------------------------- +Darwin) + + USER_MEM_ARGS="${PORT_MEM_ARGS}" + export USER_MEM_ARGS + + ;; #----------------------------------------------------- # Sun OS </code></pre>
8,761,633
How to find the actual printable area? (PrintDocument)
<p>Why is finding out this magic Rectangle so difficult?</p> <p>In the OnPrintPage event I have PrintPageEventArgs and I am trying to draw using the Graphics within the bounds of the maximum printable area.</p> <p>I have tried using PageBounds, PrintableArea, Graphics.VisibleClipBounds, etc. All fail to consistently get the drawing area, especially when switching from Landscape to Portrait layout. PrintableArea does not seem to ever change when you switch from Landscape to Portrait.</p> <p>I have also noticed that there is a difference in how Graphics.VisibleClipBounds is set depending on if I'm doing a print preview and an actual print. In a preview it always shows Portrait width/height, so I have to check if it is a preview and I have to manually swap the width/height when it is a Landscape.</p> <p>I need an algorithm to calculate the printable area <strong>as it relates to the current Graphics context</strong>, not an arbitrary theoretical print area that isn't used in actual drawing.</p> <hr> <p>My concern is dealing with the Graphics matrix offset. So far I have noticed severe inconsistencies between how the Graphics context is pre-translated using the hard margins depending on factors like:</p> <ul> <li>If OriginAtMargins is true or false (not behaving as I would think)</li> <li>If I'm printing to a printer, or using the PrintPreviewControl (I have to check if this is a print to preview or a print to page to handle the translation properly)</li> <li>If I'm using my printer at home or my printer at work (both behave differently)</li> </ul> <p>Is there a standard way to handle this? Should I just reset the matrix? When I set OriginAtMargins to true, the Graphics is pre-translated to 84,84, but my margins are 100,100. The hard margins are 16,16. Shouldn't it be translated to 100,100? Since 0,0 should be at the page bounds, not the hard margins.</p> <p>Basically my method should always work at getting the best printable rectangle. I just need a consistent, device-independent way of making sure that my drawing origin (0, 0) is at the top-left of the page in order for the above Rectangle to be of any use to me.</p>
8,841,688
3
3
null
2012-01-06 17:11:47.683 UTC
32
2017-04-27 02:39:05.827 UTC
2012-01-10 15:20:00.36 UTC
null
852,555
null
852,555
null
1
47
c#|printing|gdi+|printdocument
50,895
<p>Your question lacks a little clarity as to what the "best" rectangle is. I'm going to assume you mean the largest rectangle that will be 100% visible when printed.</p> <p>So lets start by making sure we understand what the print document graphics object "origins" are and how the OriginAtMargins property affects this origin.</p> <blockquote> <p>OriginAtMargins - Gets or sets a value indicating whether the position of a graphics object associated with a page is located just inside the user-specified margins or at the <strong>top-left corner of the <em>printable area</em></strong> of the page.<br> - <a href="http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx" rel="noreferrer" title="PrintDocument Class Definition on MSDN">PrintDocument Class Definition on MSDN</a></p> </blockquote> <p>So with <code>OriginAtMargins</code> set to <code>false</code> (default) the graphics object will be adjusted to the PrintableArea rectangle (about 5/32 from each page edge for my laser printer, old laser printers may be more, new inkjets may print right to the edge, software PDF printers will print right to the edge). So 0,0 in my graphics object is actually 16,16 on the physical page of my laser printer (your printer may be different).</p> <p>With the default 1 inch page margins and <code>OriginAtMargins</code> set to <code>true</code>, the graphics object will be adjusted to the 100,100,650,1100 rectangle for a normal portrait letter page. This is one inch inside each physical page edge. So 0,0 in your graphics object is actually 100,100 on the physical page.</p> <p>Margins are also known as "soft margins" as they are defined in software and not affected by the physical printing device. This means they will be applied to the current page size in software and reflect the actual page dimension portrait or landscape.</p> <p>PrintableArea is also known as "hard margins" which reflect the physical limitations of your printing device. This will vary from printer to printer, from manufacturer to manufacturer. Because these are hardware measurements, they do not rotate when you set the page to landscape/portrait. The physical limitations won't change on the printer regardless of software print settings, so we need to make sure we apply them on the correct axis depending on our software settings for the print document (orientation).</p> <p>So following the rough model of the sample code you posted, here's a PrintDocument.PrintPage event handler that will draw a rectangle as large as possible while still being visible (with the default <code>PrintDocument.OriginsAtMargins</code> being <code>false</code>). If you set <code>PrintDocument.OriginsAtMargins</code> to <code>true</code> it will draw a rectangle as large as possible while still being visible inside the configured soft margins (defaults to 1" from page edges).</p> <pre><code>PrintAction printAction = PrintAction.PrintToFile; private void printDocument_BeginPrint(object sender, PrintEventArgs e) { // Save our print action so we know if we are printing // a preview or a real document. printAction = e.PrintAction; // Set some preferences, our method should print a box with any // combination of these properties being true/false. printDocument.OriginAtMargins = false; //true = soft margins, false = hard margins printDocument.DefaultPageSettings.Landscape = false; } private void printDocument_PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; // If you set printDocumet.OriginAtMargins to 'false' this event // will print the largest rectangle your printer is physically // capable of. This is often 1/8" - 1/4" from each page edge. // ---------- // If you set printDocument.OriginAtMargins to 'false' this event // will print the largest rectangle permitted by the currently // configured page margins. By default the page margins are // usually 1" from each page edge but can be configured by the end // user or overridden in your code. // (ex: printDocument.DefaultPageSettings.Margins) // Grab a copy of our "soft margins" (configured printer settings) // Defaults to 1 inch margins, but could be configured otherwise by // the end user. You can also specify some default page margins in // your printDocument.DefaultPageSetting properties. RectangleF marginBounds = e.MarginBounds; // Grab a copy of our "hard margins" (printer's capabilities) // This varies between printer models. Software printers like // CutePDF will have no "physical limitations" and so will return // the full page size 850,1100 for a letter page size. RectangleF printableArea = e.PageSettings.PrintableArea; // If we are print to a print preview control, the origin won't have // been automatically adjusted for the printer's physical limitations. // So let's adjust the origin for preview to reflect the printer's // hard margins. if (printAction == PrintAction.PrintToPreview) g.TranslateTransform(printableArea.X, printableArea.Y); // Are we using soft margins or hard margins? Lets grab the correct // width/height from either the soft/hard margin rectangles. The // hard margins are usually a little wider than the soft margins. // ---------- // Note: Margins are automatically applied to the rotated page size // when the page is set to landscape, but physical hard margins are // not (the printer is not physically rotating any mechanics inside, // the paper still travels through the printer the same way. So we // rotate in software for landscape) int availableWidth = (int)Math.Floor(printDocument.OriginAtMargins ? marginBounds.Width : (e.PageSettings.Landscape ? printableArea.Height : printableArea.Width)); int availableHeight = (int)Math.Floor(printDocument.OriginAtMargins ? marginBounds.Height : (e.PageSettings.Landscape ? printableArea.Width : printableArea.Height)); // Draw our rectangle which will either be the soft margin rectangle // or the hard margin (printer capabilities) rectangle. // ---------- // Note: we adjust the width and height minus one as it is a zero, // zero based co-ordinates system. This will put the rectangle just // inside the available width and height. g.DrawRectangle(Pens.Red, 0, 0, availableWidth - 1, availableHeight - 1); } </code></pre> <p>The two lines that determine available width and available height are what I think you were looking for in your question. Those two lines take into account whether you want soft margins or hard margins and whether the print document is configured for landscape or portrait.</p> <p>I used <code>Math.Floor()</code> for the easy way out to just drop anything past the decimal (ex: 817.96 -> 817) just to make sure the available width and height was just inside the available dimensions. I'm "failing safe" here, if you wanted to you could maintain float based co-ordinates (instead of int), just be careful to watch for rounding errors that will result in the clipped graphics (if it rounds 817.96 up to 818 and then the printer driver decides that's no longer visible).</p> <p>I tested this procedure in both portrait and landscape with both hard margins and soft margins on a Dell 3115CN, a Samsung SCX-4x28 and CutePDF software printer. If this didn't adequately address your question, consider revising your question to clarify "magic rectangle" and "best rectangle".</p> <hr> <p><strong>EDIT: Notes About "Soft Margins"</strong></p> <p>Soft margins are applied in software and do not take into consideration the hardware limitations of the printer. This is intentional and by design. You can set the soft margins outside the printable area if you want and the output may be clipped by your printer's driver. If this is undesirable for your application, you need to adjust the margins in your program code. Either you can prevent the user from selecting margins outside the printable area (or warn them if they do) or you can enforce some min/max conditions in your code when you actually start printing (drawing) the document.</p> <p><strong>Example Case:</strong> If you set the page margins to 0,0,0,0 in Microsoft Word 2007 a warning dialog pops up that reads "One or more margins are set outside the printable area of the page. Choose the Fix button to increase the appropriate margins." If you click fix, Word will simply copy the hard margins into the soft margins, so the dialog now shows 0.16" for all margins (my laser printer's capabilities).</p> <p>This is expected behavior. It is not a bug/problem with Microsoft Word if the printed page is clipped because the user ignored this warning and used 0,0,0,0 page margins. This is the same in your application. You need to enforce the limits for whatever if appropriate in your use case. Either with a warning dialog, or you can force the limit more strongly in code (don't offer a choice to the user).</p> <hr> <h2>Alternative Strategy</h2> <p>Alright so maybe you don't want to just get the hard margins, but rather get the soft margins and then enforce that the soft margins remain inside the printable area when printing. Let's develop another strategy here.</p> <p>In this example I will use the origins at margins, and allow the user to select any margin they want, but I'm going to enforce in code that the selected margin not be outside the printable area. If the selected margins are outside the printable area, I'm simply going to adjust them to be inside the printable area.</p> <pre><code>PrintAction printAction = PrintAction.PrintToFile; private void printDocument_BeginPrint(object sender, PrintEventArgs e) { // Save our print action so we know if we are printing // a preview or a real document. printAction = e.PrintAction; // We ALWAYS want true here, as we will implement the // margin limitations later in code. printDocument.OriginAtMargins = true; // Set some preferences, our method should print a box with any // combination of these properties being true/false. printDocument.DefaultPageSettings.Landscape = false; printDocument.DefaultPageSettings.Margins.Top = 100; printDocument.DefaultPageSettings.Margins.Left = 0; printDocument.DefaultPageSettings.Margins.Right = 50; printDocument.DefaultPageSettings.Margins.Bottom = 0; } private void printDocument_PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; // If you set printDocumet.OriginAtMargins to 'false' this event // will print the largest rectangle your printer is physically // capable of. This is often 1/8" - 1/4" from each page edge. // ---------- // If you set printDocument.OriginAtMargins to 'false' this event // will print the largest rectangle permitted by the currently // configured page margins. By default the page margins are // usually 1" from each page edge but can be configured by the end // user or overridden in your code. // (ex: printDocument.DefaultPageSettings.Margins) // Grab a copy of our "hard margins" (printer's capabilities) // This varies between printer models. Software printers like // CutePDF will have no "physical limitations" and so will return // the full page size 850,1100 for a letter page size. RectangleF printableArea = e.PageSettings.PrintableArea; RectangleF realPrintableArea = new RectangleF( (e.PageSettings.Landscape ? printableArea.Y : printableArea.X), (e.PageSettings.Landscape ? printableArea.X : printableArea.Y), (e.PageSettings.Landscape ? printableArea.Height : printableArea.Width), (e.PageSettings.Landscape ? printableArea.Width : printableArea.Height) ); // If we are printing to a print preview control, the origin won't have // been automatically adjusted for the printer's physical limitations. // So let's adjust the origin for preview to reflect the printer's // hard margins. // ---------- // Otherwise if we really are printing, just use the soft margins. g.TranslateTransform( ((printAction == PrintAction.PrintToPreview) ? realPrintableArea.X : 0) - e.MarginBounds.X, ((printAction == PrintAction.PrintToPreview) ? realPrintableArea.Y : 0) - e.MarginBounds.Y ); // Draw the printable area rectangle in PURPLE Rectangle printedPrintableArea = Rectangle.Truncate(realPrintableArea); printedPrintableArea.Width--; printedPrintableArea.Height--; g.DrawRectangle(Pens.Purple, printedPrintableArea); // Grab a copy of our "soft margins" (configured printer settings) // Defaults to 1 inch margins, but could be configured otherwise by // the end user. You can also specify some default page margins in // your printDocument.DefaultPageSetting properties. RectangleF marginBounds = e.MarginBounds; // This intersects the desired margins with the printable area rectangle. // If the margins go outside the printable area on any edge, it will be // brought in to the appropriate printable area. marginBounds.Intersect(realPrintableArea); // Draw the margin rectangle in RED Rectangle printedMarginArea = Rectangle.Truncate(marginBounds); printedMarginArea.Width--; printedMarginArea.Height--; g.DrawRectangle(Pens.Red, printedMarginArea); } </code></pre>
5,161,552
Python Curses Handling Window (Terminal) Resize
<p>This is two questions really:</p> <ul> <li>how do I resize a curses window, and</li> <li>how do I deal with a terminal resize in curses?</li> </ul> <p>Is it possible to know when a window has changed size?</p> <p>I really can't find any good doc, not even covered on <a href="http://docs.python.org/library/curses.html" rel="noreferrer">http://docs.python.org/library/curses.html</a></p>
5,192,143
5
0
null
2011-03-01 23:10:49.193 UTC
4
2020-01-03 19:23:04.843 UTC
2014-05-30 12:39:53.1 UTC
null
193,376
null
193,376
null
1
31
python|resize|curses
26,703
<p>Terminal resize event will result in the <code>curses.KEY_RESIZE</code> key code. Therefore you can handle terminal resize as part of a standard main loop in a curses program, waiting for input with <code>getch</code>.</p>
5,412,499
android - reverse the order of an array
<p>I have an array of objects.</p> <p>Is it possible to make a new array that is a copy of this array, but in reverse order? I was looking for something like this. </p> <pre><code>// my array ArrayList&lt;Element&gt; mElements = new ArrayList&lt;Element&gt;(); // new array ArrayList&lt;Element&gt; tempElements = mElements; tempElements.reverse(); // something to reverse the order of the array </code></pre>
5,412,542
5
0
null
2011-03-23 22:33:38.247 UTC
7
2021-05-04 14:56:11.543 UTC
null
null
null
null
401,183
null
1
62
android|arrays|reverse
53,119
<p>You can do this in two steps:</p> <pre><code>ArrayList&lt;Element&gt; tempElements = new ArrayList&lt;Element&gt;(mElements); Collections.reverse(tempElements); </code></pre>
5,227,567
Web automation using .NET
<p>I am a very newbie programmer. Does anyone of you know how to do Web automation with <code>C#</code>? Basically, I just want auto implement some simple action on the web. After I have opened up the web link, i just want to perform the actions below automatically.</p> <ol> <li>Automatically Input some value and Click on "Run" button.</li> <li>Check In the ComboBox and Click on "Download" button.</li> </ol> <p>How can I do it with <code>C#</code>? My friend introduce me to use Powershell but I guess .Net do provide this kind of library too. Any suggestion or link for me to refer? </p>
5,227,644
7
1
null
2011-03-08 02:14:40.563 UTC
10
2019-01-25 10:01:10.08 UTC
2015-06-28 23:20:43.1 UTC
null
3,970,411
null
500,529
null
1
17
c#|.net
44,980
<p>You can use the <code>System.Windows.Forms.WebBrowser</code> control (<a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser%28v=vs.110%29.aspx" rel="noreferrer">MSDN Documentation</a>). For testing, it allows your to do the things that could be done in a browser. It easily executes JavaScript without any additional effort. If something went wrong, you will be able to visually see the state that the site is in.</p> <p>example:</p> <pre><code>private void buttonStart_Click(object sender, EventArgs e) { webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); webBrowser1.Navigate("http://www.wikipedia.org/"); } void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { HtmlElement search = webBrowser1.Document.GetElementById("searchInput"); if(search != null) { search.SetAttribute("value", "Superman"); foreach(HtmlElement ele in search.Parent.Children) { if (ele.TagName.ToLower() == "input" &amp;&amp; ele.Name.ToLower() == "go") { ele.InvokeMember("click"); break; } } } } </code></pre> <hr> <p>To answer your question: how to check a checkbox</p> <p>for the HTML:</p> <pre><code>&lt;input type="checkbox" id="testCheck"&gt;&lt;/input&gt; </code></pre> <p>the code:</p> <pre><code>search = webBrowser1.Document.GetElementById("testCheck"); if (search != null) search.SetAttribute("checked", "true"); </code></pre> <p>actually, the specific "how to" depends greatly on what is the actual HTML.</p> <hr> <p>For handling your multi-threaded problem:</p> <pre><code>private delegate void StartTestHandler(string url); private void StartTest(string url) { if (InvokeRequired) Invoke(new StartTestHandler(StartTest), url); else { webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); webBrowser1.Navigate(url); } } </code></pre> <p><code>InvokeRequired</code>, checks whether the current thread is the UI thread (actually, the thread that the form was created in). If it is not, then it will try to run StartTest in the required thread.</p>
5,375,817
android pinch zoom
<p>My layout contains buttons, textviews, etc. Is it possible to implement pinch zoom in my layout?</p>
5,376,108
7
0
null
2011-03-21 09:33:47.61 UTC
30
2022-03-24 06:10:19.297 UTC
2018-10-15 10:56:37.86 UTC
null
3,623,128
null
487,219
null
1
48
android|pinchzoom|zooming
115,554
<p><strong>Updated Answer</strong></p> <p>Code can be found here : <a href="https://developer.android.com/training/gestures/scale#kotlin" rel="nofollow noreferrer">official-doc</a></p> <p><strong>Answer Outdated</strong></p> <p>Check out the following links which may help you</p> <p>Best examples are provided in the below links, which you can refactor to meet your requirements.</p> <ol> <li><p><a href="http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-6-implementing-the-pinch-zoom-gesture/1847" rel="nofollow noreferrer">Implementing the pinch zoom gesture</a></p> </li> <li><p><a href="http://code.google.com/p/android-pinch/" rel="nofollow noreferrer">Android-pinch</a></p> </li> <li><p><a href="http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html" rel="nofollow noreferrer">GestureDetector.SimpleOnGestureListener</a></p> </li> </ol>
5,111,572
How to test for $null array in PowerShell
<p>I'm using an array variable in PowerShell 2.0. If it does not have a value, it will be $null, which I can test for successfully:</p> <pre><code>PS C:\&gt; [array]$foo = $null PS C:\&gt; $foo -eq $null True </code></pre> <p>But when I give it a value, the test for $null does not return anything:</p> <pre><code>PS C:\&gt; [array]$foo = @("bar") PS C:\&gt; $foo -eq $null PS C:\&gt; </code></pre> <p>How can "-eq $null" give no results? It's either $null or it's not.</p> <p>What is the correct way to determine if an array is populated vs. $null?</p>
5,111,680
7
0
null
2011-02-24 22:55:47.41 UTC
14
2022-01-03 02:53:23.553 UTC
null
null
null
null
550,712
null
1
63
powershell|null
196,483
<p>It's an array, so you're looking for Count to test for contents.</p> <p>I'd recommend</p> <pre><code>$foo.count -gt 0 </code></pre> <p>The &quot;why&quot; of this is related to how PSH handles comparison of collection objects</p>
5,003,285
How can interfaces replace the need for multiple inheritance when have existing classes
<p>First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not support multiple inheritance and I know that using interfaces should be an alternative. But I don't get it and see my dilemma:</p> <p>I have to make changes on a very very large and complex tool written in Java. In this tool there is a data structure built with many different class objects with a linked member hierarchy. Anyway...</p> <ul> <li>I have one class <code>Tagged</code> which has multiple methods and returns an object tag depending on the object's class. It needs members and static variables.</li> <li>And a second class called <code>XMLElement</code> allows to link objects and in the end generate a XML file. I also need member and static variables here.</li> <li>Finally, I have these many many data classes which nearly all should extend <code>XMLElement</code> and some of them <code>Tagged</code>.</li> </ul> <p>Ok ok, this won't work since it's only possible to extend just one class. I read very often that everything with Java is ok and there is no need for having multiple inheritance. I believe, but I don't see how an interface should replace inheritance. </p> <ol> <li>It makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think). </li> <li>I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.</li> </ol> <p>I really don't get it so please can somebody explain me how to handle this?</p>
5,003,384
10
2
null
2011-02-15 11:51:55.99 UTC
19
2019-01-07 03:59:18.893 UTC
2013-06-28 12:37:22.377 UTC
null
545,127
null
500,774
null
1
56
java|inheritance|interface|multiple-inheritance
34,199
<p>You should probably favor composition (and delegation) over inheritance :</p> <pre><code>public interface TaggedInterface { void foo(); } public interface XMLElementInterface { void bar(); } public class Tagged implements TaggedInterface { // ... } public class XMLElement implements XMLElementInterface { // ... } public class TaggedXmlElement implements TaggedInterface, XMLElementInterface { private TaggedInterface tagged; private XMLElementInterface xmlElement; public TaggedXmlElement(TaggedInterface tagged, XMLElementInterface xmlElement) { this.tagged = tagged; this.xmlElement = xmlElement; } public void foo() { this.tagged.foo(); } public void bar() { this.xmlElement.bar(); } public static void main(String[] args) { TaggedXmlElement t = new TaggedXmlElement(new Tagged(), new XMLElement()); t.foo(); t.bar(); } } </code></pre>
12,153,009
OpenSSL C example of AES-GCM using EVP interfaces
<p>For AES-GCM encryption/decryption, I tried this, but it has a problem.</p> <pre><code>ctx = EVP_CIPHER_CTX_new(); //Get the cipher. cipher = EVP_aes_128_gcm (); #define GCM_IV "000000000000" #define GCM_ADD "0000" #define TAG_SIZE 16 #define ENC_SIZE 64 //Encrypt the data first. //Set the cipher and context only. retv = EVP_EncryptInit (ctx, cipher, NULL, NULL); //Set the nonce and tag sizes. //Set IV length. [Optional for GCM]. retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_IVLEN, strlen((const char *)GCM_IV), NULL); //Now initialize the context with key and IV. retv = EVP_EncryptInit (ctx, NULL, (const unsigned char *)keybuf, (const unsigned char *)GCM_IV); //Add Additional associated data (AAD). [Optional for GCM] retv = EVP_EncryptUpdate (ctx, NULL, (int *)&amp;enclen, (const unsigned char *)GCM_ADD, strlen(GCM_ADD)); //Now encrypt the data. retv = EVP_EncryptUpdate (ctx, (unsigned char *)encm, (int *)&amp;enclen, (const unsigned char *)msg, _tcslen (msg) *sizeof(Char)); //Finalize. retv = EVP_EncryptFinal (ctx, (unsigned char *)encm + enclen, (int *)&amp;enclen2); enclen += enclen2; //Append authentication tag at the end. retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, TAG_SIZE, (unsigned char *)encm + enclen); //DECRYPTION PART //Now Decryption of the data. //Then decrypt the data. //Set just cipher. retv = EVP_DecryptInit(ctx, cipher, NULL, NULL); //Set Nonce size. retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_IVLEN, strlen((const char *)GCM_IV), NULL); //Set Tag from the data. retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_TAG, TAG_SIZE, (unsigned char *)encm + enclen); //Set key and IV (nonce). retv = EVP_DecryptInit (ctx, NULL, (const unsigned char*)keybuf, (const unsigned char *)GCM_IV); //Add Additional associated data (AAD). retv = EVP_DecryptUpdate (ctx, NULL, (int *)&amp;declen, (const unsigned char *)GCM_ADD, strlen((const char *)GCM_ADD)); //Decrypt the data. retv = EVP_DecryptUpdate (ctx, decm, (int *)&amp;declen, (const unsigned char *)encm, enclen); //Finalize. retv = EVP_DecryptFinal (ctx, (unsigned char*)decm + declen, (int *)&amp;declen2); </code></pre> <p>This code is working fine (with some modifications). It is encrypting and decrypting the message. The problem is that when cipher text is modified before decryption, it still decrypts the text (however, wrong). As per my understanding of authenticated encryption, in such cases, it should not decrypt the modified cipher texts.</p> <p>Where am I wrong? Can I get any suitable example of AES-GCM using EVP interfaces of OpenSSL?</p>
13,045,182
4
1
null
2012-08-28 04:57:12.937 UTC
9
2017-04-28 17:25:27.457 UTC
2012-08-28 05:57:37.56 UTC
null
440,558
null
1,629,262
null
1
15
c|openssl|aes|aes-gcm
54,281
<p>Here is an example to encrypt and decrypt 128 bytes every call to update for example:</p> <pre><code> int howmany, dec_success, len; const EVP_CIPHER *cipher; switch(key_len) { case 128: cipher = EVP_aes_128_gcm ();break; case 192: cipher = EVP_aes_192_gcm ();break; case 256: cipher = EVP_aes_256_gcm ();break; default:break; } // Encrypt EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit (ctx, cipher, KEY, IV); EVP_EncryptUpdate (ctx, NULL, &amp;howmany, AAD, aad_len); len = 0; while(len &lt;= in_len-128) { EVP_EncryptUpdate (ctx, CIPHERTEXT+len, &amp;howmany, PLAINTEXT+len, 128); len+=128; } EVP_EncryptUpdate (ctx, CIPHERTEXT+len, &amp;howmany, PLAINTEXT+len, in_len - len); EVP_EncryptFinal (ctx, TAG, &amp;howmany); EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, 16, TAG); EVP_CIPHER_CTX_free(ctx); // Decrypt ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit (ctx, cipher, KEY, IV); EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_TAG, 16, ref_TAG); EVP_DecryptInit (ctx, NULL, KEY, IV); EVP_DecryptUpdate (ctx, NULL, &amp;howmany, AAD, aad_len); len = 0; while(len &lt;= in_len-128) { EVP_DecryptUpdate (ctx, decrypted_CT+len, &amp;howmany, CIPHERTEXT+len, 128); len+=128; } EVP_DecryptUpdate (ctx, decrypted_CT+len, &amp;howmany, CIPHERTEXT+len, in_len-len); dec_success = EVP_DecryptFinal (ctx, dec_TAG, &amp;howmany); EVP_CIPHER_CTX_free(ctx); </code></pre> <p>In the end you should check that the value of dec_success is 1. If you modify the CIPHERTEXT, before you decrypt it, you should get value of 0.</p>
12,484,310
ValueError: Dimension mismatch
<p>I use <a href="http://scipy.org/">SciPy</a> and <a href="http://scikit-learn.org/stable/">scikit-learn</a> to train and apply a Multinomial Naive Bayes Classifier for binary text classification. Precisely, I use the module <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer"><code>sklearn.feature_extraction.text.CountVectorizer</code></a> for creating sparse matrices that hold word feature counts from text and the module <a href="http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB"><code>sklearn.naive_bayes.MultinomialNB</code></a> as the classifier implementation for training the classifier on training data and applying it on test data.</p> <p>The input to the <code>CountVectorizer</code> is a list of text documents represented as unicode strings. The training data is much larger than the test data. My code looks like this (simplified):</p> <pre><code>vectorizer = CountVectorizer(**kwargs) # sparse matrix with training data X_train = vectorizer.fit_transform(list_of_documents_for_training) # vector holding target values (=classes, either -1 or 1) for training documents # this vector has the same number of elements as the list of documents y_train = numpy.array([1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, ...]) # sparse matrix with test data X_test = vectorizer.fit_transform(list_of_documents_for_testing) # Training stage of NB classifier classifier = MultinomialNB() classifier.fit(X=X_train, y=y_train) # Prediction of log probabilities on test data X_log_proba = classifier.predict_log_proba(X_test) </code></pre> <p><strong>Problem:</strong> As soon as <a href="http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB.predict_log_proba"><code>MultinomialNB.predict_log_proba()</code></a> is called, I get <code>ValueError: dimension mismatch</code>. According to the IPython stacktrace below, the error occurs in SciPy:</p> <pre><code>/path/to/my/code.pyc --&gt; 177 X_log_proba = classifier.predict_log_proba(X_test) /.../sklearn/naive_bayes.pyc in predict_log_proba(self, X) 76 in the model, where classes are ordered arithmetically. 77 """ --&gt; 78 jll = self._joint_log_likelihood(X) 79 # normalize by P(x) = P(f_1, ..., f_n) 80 log_prob_x = logsumexp(jll, axis=1) /.../sklearn/naive_bayes.pyc in _joint_log_likelihood(self, X) 345 """Calculate the posterior log probability of the samples X""" 346 X = atleast2d_or_csr(X) --&gt; 347 return (safe_sparse_dot(X, self.feature_log_prob_.T) 348 + self.class_log_prior_) 349 /.../sklearn/utils/extmath.pyc in safe_sparse_dot(a, b, dense_output) 71 from scipy import sparse 72 if sparse.issparse(a) or sparse.issparse(b): --&gt; 73 ret = a * b 74 if dense_output and hasattr(ret, "toarray"): 75 ret = ret.toarray() /.../scipy/sparse/base.pyc in __mul__(self, other) 276 277 if other.shape[0] != self.shape[1]: --&gt; 278 raise ValueError('dimension mismatch') 279 280 result = self._mul_multivector(np.asarray(other)) </code></pre> <p>I have no idea why this error occurs. Can anybody please explain it to me and provide a solution for this problem? Thanks a lot in advance!</p>
12,485,573
2
0
null
2012-09-18 20:16:32.51 UTC
8
2020-11-27 05:48:08.4 UTC
2020-08-30 12:01:03.563 UTC
null
1,968
null
1,125,413
null
1
29
python|numpy|scipy|scikit-learn
27,903
<p>Sounds to me, like you just need to use <code>vectorizer.transform</code> for the test dataset, since the training dataset fixes the vocabulary (you cannot know the full vocabulary including the training set afterall). Just to be clear, thats <code>vectorizer.transform</code> instead of <code>vectorizer.fit_transform</code>.</p>
12,474,908
How to get all static properties and its values of a class using reflection
<p>I hava a class like this:</p> <pre><code>public class tbl050701_1391_Fields { public static readonly string StateName = "State Name"; public static readonly string StateCode = "State Code"; public static readonly string AreaName = "Area Name"; public static readonly string AreaCode = "Area Code"; public static readonly string Dore = "Period"; public static readonly string Year = "Year"; } </code></pre> <p>I want to write some statement that returns a <code>Dictionary&lt;string, string&gt;</code> that has these values:</p> <pre><code>Key Value -------------------------------------------- "StateName" "State Name" "StateCode" "State Code" "AreaName" "Area Name" "Dore" "Period" "Year" "Year" </code></pre> <p>I have this code for getting one property value:</p> <pre><code>public static string GetValueUsingReflection(object obj, string propertyName) { var field = obj.GetType().GetField(propertyName, BindingFlags.Public | BindingFlags.Static); var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty; return fieldValue; } </code></pre> <p>How I can get all properties and their values?</p>
12,474,951
1
1
null
2012-09-18 10:13:50.687 UTC
4
2021-10-05 05:35:49.107 UTC
2016-11-04 16:04:33.513 UTC
null
216,074
null
648,723
null
1
47
c#|reflection
27,937
<blockquote> <p>how I can get all properties and their values?</p> </blockquote> <p>Well to start with, you need to distinguish between <em>fields</em> and <em>properties</em>. It looks like you've got fields here. So you'd want something like:</p> <pre><code>public static Dictionary&lt;string, string&gt; GetFieldValues(object obj) { return obj.GetType() .GetFields(BindingFlags.Public | BindingFlags.Static) .Where(f =&gt; f.FieldType == typeof(string)) .ToDictionary(f =&gt; f.Name, f =&gt; (string) f.GetValue(null)); } </code></pre> <p>Note: null parameter is necessary for GetValue for this to work since the fields are static and don't belong to an instance of the class.</p>
12,239,169
How to select records without duplicate on just one field in SQL?
<p>I have a table with 3 columns like this: </p> <pre><code>+------------+---------------+-------+ | Country_id | country_title | State | +------------+---------------+-------+ </code></pre> <p>There are many records in this table. Some of them have <code>state</code> and some other don't. Now, imagine these records: </p> <pre><code>1 | Canada | Alberta 2 | Canada | British Columbia 3 | Canada | Manitoba 4 | China | </code></pre> <p>I need to have country names without any duplicate. Actually I need their <code>id</code> and <code>title</code>, What is the best SQL command to make this? I used <code>DISTINCT</code> in the form below but I could not achieve an appropriate result. </p> <pre><code>SELECT DISTINCT title,id FROM tbl_countries ORDER BY title </code></pre> <p>My desired result is something like this: </p> <pre><code>1, Canada 4, China </code></pre>
12,239,289
8
8
null
2012-09-02 19:43:10.3 UTC
21
2020-03-18 11:25:19.977 UTC
2015-04-28 07:02:25.397 UTC
null
4,519,059
null
789,090
null
1
79
sql|select|duplicates|distinct
537,130
<p>Try this:</p> <pre><code>SELECT MIN(id) AS id, title FROM tbl_countries GROUP BY title </code></pre>
18,777,873
Convert RGB to black OR white
<p>How would I take an RGB image in Python and convert it to black and white? Not grayscale, I want each pixel to be either fully black (0, 0, 0) or fully white (255, 255, 255).</p> <p>Is there any built-in functionality for getting it done in the popular Python image processing libraries? If not, would the best way be just to loop through each pixel, if it's closer to white set it to white, if it's closer to black set it to black?</p>
18,778,280
8
4
null
2013-09-13 03:34:51.953 UTC
21
2021-12-11 12:44:31.713 UTC
2021-12-11 12:44:31.713 UTC
null
17,650,189
null
1,034,736
null
1
46
python|opencv|numpy|python-imaging-library
86,562
<h1>Scaling to Black and White</h1> <p>Convert to grayscale and then scale to white or black (whichever is closest).</p> <p>Original:</p> <p><img src="https://i.stack.imgur.com/H334L.png" alt="meow meow tied up cat"></p> <p>Result:</p> <p><img src="https://i.stack.imgur.com/muT5j.png" alt="Black and white Cat, Pure"></p> <h2>Pure Pillow implementation</h2> <p>Install <code>pillow</code> if you haven't already:</p> <pre><code>$ pip install pillow </code></pre> <p><a href="https://github.com/python-imaging/Pillow">Pillow</a> (or PIL) can help you work with images effectively.</p> <pre><code>from PIL import Image col = Image.open("cat-tied-icon.png") gray = col.convert('L') bw = gray.point(lambda x: 0 if x&lt;128 else 255, '1') bw.save("result_bw.png") </code></pre> <p>Alternatively, you can use <a href="https://github.com/python-imaging/Pillow">Pillow</a> with <a href="http://www.numpy.org/">numpy</a>. </p> <h2>Pillow + Numpy Bitmasks Approach</h2> <p>You'll need to install numpy:</p> <pre><code>$ pip install numpy </code></pre> <p>Numpy needs a copy of the array to operate on, but the result is the same.</p> <pre><code>from PIL import Image import numpy as np col = Image.open("cat-tied-icon.png") gray = col.convert('L') # Let numpy do the heavy lifting for converting pixels to pure black or white bw = np.asarray(gray).copy() # Pixel range is 0...255, 256/2 = 128 bw[bw &lt; 128] = 0 # Black bw[bw &gt;= 128] = 255 # White # Now we put it back in Pillow/PIL land imfile = Image.fromarray(bw) imfile.save("result_bw.png") </code></pre> <h1>Black and White using Pillow, with dithering</h1> <p>Using <a href="https://github.com/python-imaging/Pillow">pillow</a> you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)</p> <pre><code>from PIL import Image image_file = Image.open("cat-tied-icon.png") # open colour image image_file = image_file.convert('1') # convert image to black and white image_file.save('/tmp/result.png') </code></pre> <p>Original:</p> <p><img src="https://i.stack.imgur.com/mvvu0.png" alt="meow meow color cat"></p> <p>Converted:</p> <p><img src="https://i.stack.imgur.com/LsIJ0.png" alt="meow meow black and white cat"></p> <h1>Black and White using Pillow, without dithering</h1> <pre><code>from PIL import Image image_file = Image.open("cat-tied-icon.png") # open color image image_file = image_file.convert('1', dither=Image.NONE) # convert image to black and white image_file.save('/tmp/result.png') </code></pre>
3,877,178
Using God to monitor Unicorn - Start exited with non-zero code = 1
<p>I am working on a God script to monitor my Unicorns. I started with GitHub's examples script and have been modifying it to match my server configuration. Once God is running, commands such as <code>god stop unicorn</code> and <code>god restart unicorn</code> work just fine. </p> <p>However, <code>god start unicorn</code> results in <code>WARN: unicorn start command exited with non-zero code = 1</code>. The weird part is that if I copy the start script directly from the config file, it starts right up like a brand new mustang.</p> <p>This is my start command:</p> <pre><code>/usr/local/bin/unicorn_rails -c /home/my-linux-user/my-rails-app/config/unicorn.rb -E production -D </code></pre> <p>I have declared all paths as absolute in the config file. Any ideas what might be preventing this script from working?</p>
3,878,267
3
0
null
2010-10-06 21:51:46.153 UTC
7
2016-05-30 09:25:55.467 UTC
null
null
null
null
467,359
null
1
42
ruby-on-rails|ruby|linux|unicorn|god
5,394
<p>I haven't used unicorn as an app server, but I've used god for monitoring before.</p> <p>If I remember rightly when you start god and give your config file, it automatically starts whatever you've told it to watch. Unicorn is probably already running, which is why it's throwing the error.</p> <p>Check this by running <code>god status</code> once you've started god. If that's not the case you can check on the command line what the comand's exit status is:</p> <p><code>/usr/local/bin/unicorn_rails -c /home/my-linux-user/my-rails-app/config/unicorn.rb -E production -D;</code> <code>echo $?;</code></p> <p>that echo will print the exit status of the last command. If it's zero, the last command reported no errors. Try starting unicorn twice in a row, I expect the second time it'll return 1, because it's already running.</p> <p>EDIT:</p> <p>including the actual solution from comments, as this seems to be a popular response:</p> <p>You can set an explicit user and group if your process requires to be run as a specific user.</p> <pre><code>God.watch do |w| w.uid = 'root' w.gid = 'root' # remainder of config end </code></pre>
36,805,784
How to join two collections in mongoose
<p>I have two Schema defined as below:</p> <pre><code>var WorksnapsTimeEntry = BaseSchema.extend({ student: { type: Schema.ObjectId, ref: 'Student' }, timeEntries: { type: Object } }); var StudentSchema = BaseSchema.extend({ firstName: { type: String, trim: true, default: '' // validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, lastName: { type: String, trim: true, default: '' // validate: [validateLocalStrategyProperty, 'Please fill in your last name'] }, displayName: { type: String, trim: true }, municipality: { type: String } }); </code></pre> <p>And I would like to loop thru each student and show it's time entries. So far I have this code which is obviously not right as I still dont know how do I join WorksnapTimeEntry schema table.</p> <pre><code>Student.find({ status: 'student' }) .populate('student') .exec(function (err, students) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } _.forEach(students, function (student) { // show student with his time entries.... }); res.json(students); }); </code></pre> <p>Any one knows how do I achieve such thing?</p>
36,806,448
3
9
null
2016-04-23 02:00:39.053 UTC
9
2021-04-13 12:13:59.643 UTC
2016-04-23 03:54:37.34 UTC
null
5,031,275
null
1,480,897
null
1
22
node.js|mongodb|mongoose|mongodb-query
74,009
<p>You don't want <code>.populate()</code> here but instead you want two queries, where the first matches the <code>Student</code> objects to get the <code>_id</code> values, and the second will use <a href="https://docs.mongodb.org/manual/reference/operator/query/in/" rel="noreferrer"><code>$in</code></a> to match the respective <code>WorksnapsTimeEntry</code> items for those "students".</p> <p>Using <a href="https://github.com/caolan/async#waterfall" rel="noreferrer"><code>async.waterfall</code></a> just to avoid some indentation creep:</p> <pre><code>async.waterfall( [ function(callback) { Student.find({ "status": "student" },{ "_id": 1 },callback); }, function(students,callback) { WorksnapsTimeEntry.find({ "student": { "$in": students.map(function(el) { return el._id }) },callback); } ], function(err,results) { if (err) { // do something } else { // results are the matching entries } } ) </code></pre> <p>If you really must, then you can <code>.populate("student")</code> on the second query to get populated items from the other table.</p> <p>The reverse case is to query on <code>WorksnapsTimeEntry</code> and return "everything", then filter out any <code>null</code> results from <code>.populate()</code> with a "match" query option:</p> <pre><code>WorksnapsTimeEntry.find().populate({ "path": "student", "match": { "status": "student" } }).exec(function(err,entries) { // Now client side filter un-matched results entries = entries.filter(function(entry) { return entry.student != null; }); // Anything not populated by the query condition is now removed }); </code></pre> <p>So that is not a desirable action, since the "database" is not filtering what is likely the bulk of results.</p> <p>Unless you have a good reason not to do so, then you probably "should" be "embedding" the data instead. That way the properties like <code>"status</code>" are already available on the collection and additional queries are not required.</p> <p>If you are using a NoSQL solution like MongoDB you should be embracing it's concepts, rather than sticking to relational design principles. If you are consistently modelling relationally, then you might as well use a relational database, since you won't be getting any benefit from the solution that has other ways to handle that.</p>
43,651,446
General error: 1364 Field 'user_id' doesn't have a default value
<p>I am trying to assign the user_id with the current user but it give me this error</p> <pre><code>SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`updated_at`, `created_at`) values (2017-04-27 10:29:59, 2017-04-27 10:29:59)) </code></pre> <p>here is my method</p> <pre><code>//PostController Post::create(request([ 'body' =&gt; request('body'), 'title' =&gt; request('title'), 'user_id' =&gt; auth()-&gt;id() ])); </code></pre> <p>with these fillables</p> <pre><code>//Post Model protected $fillable = ['title', 'body', 'user_id'] </code></pre> <p>However this method do the job</p> <pre><code>//PostController auth()-&gt;user()-&gt;publish(new Post(request(['title' ,'body']))); //Post Model public function publish(Post $post) { $this-&gt;posts()-&gt;save($post); } </code></pre> <p>any idea why this fail? <a href="https://i.stack.imgur.com/A1Q5q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/A1Q5q.png" alt="enter image description here"></a></p>
43,706,069
15
15
null
2017-04-27 07:37:59.977 UTC
11
2020-10-06 08:42:28.193 UTC
2019-07-26 12:24:28.97 UTC
null
2,519,416
null
7,567,356
null
1
36
php|laravel
226,223
<p>So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote</p> <pre><code>Post::create(request([ // &lt;= the error is Here!!! 'body' =&gt; request('body'), 'title' =&gt; request('title'), 'user_id' =&gt; auth()-&gt;id() ])); </code></pre> <p>actually, there is no need for the request function warping the body of the create function.</p> <pre><code>// this is right Post::create([ 'body' =&gt; request('body'), 'title' =&gt; request('title'), 'user_id' =&gt; auth()-&gt;id() ]); </code></pre>
10,930,261
Two y axis in core plot graph with different axis scales
<p>I am programming a app where I have graph with two y axis and one x axis.left y axis has range from 0 to 20 so there are 20 majorTick axis.Right y axis has range from 0 to 10,so I want left y axis to be labelled for every alternate majorTickAxis.</p> <p>here is my code snippet</p> <pre><code>//code CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace; float xmax=10.0; float xmin=0.0; plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xmin) length:CPTDecimalFromFloat(xmax-xmin)]; float ymax=20.0; float ymin=0.0; float ymax2=10.0; plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin) length:CPTDecimalFromFloat(ymax-ymin)]; // Grid line styles CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle]; majorGridLineStyle.lineWidth = 0.75; majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.75]; CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle]; minorGridLineStyle.lineWidth = 0.25; minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1]; CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle]; redLineStyle.lineWidth = 2.0; redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5]; CPTMutableLineStyle *greenLineStyle = [CPTMutableLineStyle lineStyle]; greenLineStyle.lineWidth = 2.0; greenLineStyle.lineColor = [[CPTColor greenColor] colorWithAlphaComponent:0.5]; // Axes CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet; CPTXYAxis *x = axisSet.xAxis; x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0"); x.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:@"1"] decimalValue]; x.minorTicksPerInterval = 4; x.labelOffset = 3.0f; x.title = @"Time"; x.titleOffset = 20.0; x.titleLocation = CPTDecimalFromFloat((xmax+xmin)/2); x.majorGridLineStyle= majorGridLineStyle; x.minorGridLineStyle=minorGridLineStyle; CPTXYAxis *y = axisSet.yAxis; y.majorIntervalLength = CPTDecimalFromString(@"1.0"); y.majorTickLength=2.0f; y.minorTicksPerInterval = 4; y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0); y.labelExclusionRanges = [NSArray arrayWithObjects: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0) length:CPTDecimalFromInteger(0.0)],Nil]; y.majorGridLineStyle= majorGridLineStyle; y.minorGridLineStyle=minorGridLineStyle; CPTXYAxis *y2 = [[(CPTXYAxis *)[CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease]; y2.plotSpace =plotSpace; y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(xmax); y2.majorGridLineStyle=majorGridLineStyle; y2.minorGridLineStyle=minorGridLineStyle; y2.minorTicksPerInterval = 4; y2.majorIntervalLength = CPTDecimalFromString(@"1.0"); y2.labelOffset = 10.0; y2.coordinate =CPTCoordinateY; y2.axisLineStyle = x.axisLineStyle; y2.labelTextStyle = x.labelTextStyle; y2.labelOffset = -30.0f; y2.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(ymax2)]; y2.title = @"Temperature"; y2.titleLocation = CPTDecimalFromInteger(5.0); y2.titleTextStyle =x.titleTextStyle; y2.titleOffset =-45.0f; y2.labelExclusionRanges = [NSArray arrayWithObjects: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0) length:CPTDecimalFromInteger(0.0)],Nil]; self.graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil]; // Create a plot that uses the data source method for red graph CPTScatterPlot *redPlot = [[[CPTScatterPlot alloc] init] autorelease]; redPlot.identifier = @"red Plot";; CPTMutableLineStyle *lineStyle = [[redPlot.dataLineStyle mutableCopy] autorelease]; lineStyle.miterLimit = 1.0f; redPlot.dataLineStyle = redLineStyle; redPlot.dataSource = self; redPlot.interpolation = CPTScatterPlotInterpolationStepped; [self.graph addPlot:redPlot]; // Create a plot that uses the data source method for green graph CPTScatterPlot *greenPlot = [[[CPTScatterPlot alloc] init] autorelease]; greenPlot.identifier = @"green Plot";; CPTMutableLineStyle *greenlineStyle = [[greenPlot.dataLineStyle mutableCopy] autorelease]; greenlineStyle.miterLimit = 1.0f; greenPlot.dataLineStyle = greenLineStyle; greenPlot.dataSource = self; [self.graph addPlot:greenPlot]; // Add some data NSMutableArray *newData = [NSMutableArray arrayWithCapacity:100]; NSUInteger i; for ( i = 0; i &lt; 45; i++ ) { id x = [NSNumber numberWithDouble:i * 0.2]; id y = [NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ]; [newData addObject:[NSDictionary dictionaryWithObjectsAndKeys: x, @"x",y, @"y",nil]]; } NSMutableArray *newData1 = [NSMutableArray arrayWithCapacity:100]; for ( i = 0; i &lt; 45; i++ ) { id x =[NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ]; id y2 = [NSNumber numberWithDouble:i * 0.2]; [newData1 addObject:[NSDictionary dictionaryWithObjectsAndKeys: x, @"x",y2, @"y2",nil]]; } self.plotData = newData; self.plotData2=newData1; </code></pre>
10,942,081
1
1
null
2012-06-07 10:46:17.703 UTC
10
2012-06-08 01:39:58.9 UTC
2012-06-07 18:15:40.497 UTC
null
76,810
null
1,441,938
null
1
8
xcode|core-plot
5,647
<p>If you want the two y-axes to have different scales, you need to add another plot space. Use the same <code>xRange</code> for the second plot space, but use a different <code>yRange</code>, e.g.,</p> <pre><code>CPTXYPlotSpace *plotSpace2 = [[[CPTXYPlotSpace alloc] init] autorelease]; plotSpace2.xRange = plotSpace.xRange; plotSpace2.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin) length:CPTDecimalFromFloat(ymax2 - ymin)]; [graph addPlotSpace:plotSpace2]; y2.plotSpace = plotSpace2; </code></pre> <p>Use the <code>majorIntervalLength</code> to control the location of the ticks and grid lines:</p> <pre><code>y.majorIntervalLength = CPTDecimalFromFloat((ymax - ymin) / 10.0f); y2.majorIntervalLength = CPTDecimalFromFloat((ymax2 - ymin) / 10.0f); </code></pre>
11,351,076
SQL: Concatenate column values in a single row into a string separated by comma
<p>Let's say I have a table like this in SQL Server:</p> <pre><code>Id City Province Country 1 Vancouver British Columbia Canada 2 New York null null 3 null Adama null 4 null null France 5 Winnepeg Manitoba null 6 null Quebec Canada 7 Seattle null USA </code></pre> <p>How can I get a query result so that the location is a concatenation of the City, Province, and Country separated by ", ", with nulls omitted. I'd like to ensure that there aren't any trailing comma, preceding commas, or empty strings. For example:</p> <pre><code>Id Location 1 Vancouver, British Columbia, Canada 2 New York 3 Adama 4 France 5 Winnepeg, Manitoba 6 Quebec, Canada 7 Seattle, USA </code></pre>
11,351,622
6
6
null
2012-07-05 19:18:54.177 UTC
3
2018-08-14 10:59:57.1 UTC
2012-07-06 17:27:06.78 UTC
null
542,398
null
188,740
null
1
19
sql-server|tsql|string-concatenation
97,575
<p>I think this takes care of all of the issues I spotted in other answers. No need to test the length of the output or check if the leading character is a comma, no worry about concatenating non-string types, no significant increase in complexity when other columns (e.g. Postal Code) are inevitably added...</p> <pre><code>DECLARE @x TABLE(Id INT, City VARCHAR(32), Province VARCHAR(32), Country VARCHAR(32)); INSERT @x(Id, City, Province, Country) VALUES (1,'Vancouver','British Columbia','Canada'), (2,'New York' , null , null ), (3, null ,'Adama' , null ), (4, null , null ,'France'), (5,'Winnepeg' ,'Manitoba' , null ), (6, null ,'Quebec' ,'Canada'), (7,'Seattle' , null ,'USA' ); SELECT Id, Location = STUFF( COALESCE(', ' + RTRIM(City), '') + COALESCE(', ' + RTRIM(Province), '') + COALESCE(', ' + RTRIM(Country), '') , 1, 2, '') FROM @x; </code></pre> <p>SQL Server 2012 added a new T-SQL function called <a href="http://msdn.microsoft.com/en-us/library/hh231515.aspx"><code>CONCAT</code></a>, but it is not useful here, since you still have to optionally include commas between discovered values, and there is no facility to do that - it just munges values together with no option for a separator. This avoids having to worry about non-string types, but doesn't allow you to handle nulls vs. non-nulls very elegantly.</p>
10,983,396
Fragment onCreateView and onActivityCreated called twice
<p>I'm developing an app using Android 4.0 ICS and fragments.</p> <p>Consider this modified example from the ICS 4.0.3 (API level 15) API's demo example app:</p> <pre><code>public class FragmentTabs extends Activity { private static final String TAG = FragmentTabs.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); bar.addTab(bar.newTab() .setText("Simple") .setTabListener(new TabListener&lt;SimpleFragment&gt;( this, "mysimple", SimpleFragment.class))); if (savedInstanceState != null) { bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab")); Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number")); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("tab", getActionBar().getSelectedNavigationIndex()); } public static class TabListener&lt;T extends Fragment&gt; implements ActionBar.TabListener { private final Activity mActivity; private final String mTag; private final Class&lt;T&gt; mClass; private final Bundle mArgs; private Fragment mFragment; public TabListener(Activity activity, String tag, Class&lt;T&gt; clz) { this(activity, tag, clz, null); } public TabListener(Activity activity, String tag, Class&lt;T&gt; clz, Bundle args) { mActivity = activity; mTag = tag; mClass = clz; mArgs = args; // Check to see if we already have a fragment for this tab, probably // from a previously saved state. If so, deactivate it, because our // initial state is that a tab isn't shown. mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); if (mFragment != null &amp;&amp; !mFragment.isDetached()) { Log.d(TAG, "constructor: detaching fragment " + mTag); FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } } public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); Log.d(TAG, "onTabSelected adding fragment " + mTag); ft.add(android.R.id.content, mFragment, mTag); } else { Log.d(TAG, "onTabSelected attaching fragment " + mTag); ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { Log.d(TAG, "onTabUnselected detaching fragment " + mTag); ft.detach(mFragment); } } public void onTabReselected(Tab tab, FragmentTransaction ft) { Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show(); } } public static class SimpleFragment extends Fragment { TextView textView; int mNum; /** * When creating, retrieve this instance's number from its arguments. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(FragmentTabs.TAG, "onCreate " + (savedInstanceState != null ? ("state " + savedInstanceState.getInt("number")) : "no state")); if(savedInstanceState != null) { mNum = savedInstanceState.getInt("number"); } else { mNum = 25; } } @Override public void onActivityCreated(Bundle savedInstanceState) { Log.d(TAG, "onActivityCreated"); if(savedInstanceState != null) { Log.d(TAG, "saved variable number: " + savedInstanceState.getInt("number")); } super.onActivityCreated(savedInstanceState); } @Override public void onSaveInstanceState(Bundle outState) { Log.d(TAG, "onSaveInstanceState saving: " + mNum); outState.putInt("number", mNum); super.onSaveInstanceState(outState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(FragmentTabs.TAG, "onCreateView " + (savedInstanceState != null ? ("state: " + savedInstanceState.getInt("number")) : "no state")); textView = new TextView(getActivity()); textView.setText("Hello world: " + mNum); textView.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb)); return textView; } } </code></pre> <p>}</p> <p>Here is the output retrieved from running this example and then rotating the phone:</p> <pre><code>06-11 11:31:42.559: D/FragmentTabs(10726): onTabSelected adding fragment mysimple 06-11 11:31:42.559: D/FragmentTabs(10726): onCreate no state 06-11 11:31:42.559: D/FragmentTabs(10726): onCreateView no state 06-11 11:31:42.567: D/FragmentTabs(10726): onActivityCreated 06-11 11:31:45.286: D/FragmentTabs(10726): onSaveInstanceState saving: 25 06-11 11:31:45.325: D/FragmentTabs(10726): onCreate state 25 06-11 11:31:45.340: D/FragmentTabs(10726): constructor: detaching fragment mysimple 06-11 11:31:45.340: D/FragmentTabs(10726): onTabSelected attaching fragment mysimple 06-11 11:31:45.348: D/FragmentTabs(10726): FragmentTabs.onCreate tab: 0 06-11 11:31:45.348: D/FragmentTabs(10726): FragmentTabs.onCreate number: 0 06-11 11:31:45.348: D/FragmentTabs(10726): onCreateView state: 25 06-11 11:31:45.348: D/FragmentTabs(10726): onActivityCreated 06-11 11:31:45.348: D/FragmentTabs(10726): saved variable number: 25 06-11 11:31:45.348: D/FragmentTabs(10726): onCreateView no state 06-11 11:31:45.348: D/FragmentTabs(10726): onActivityCreated </code></pre> <p>My question is, why is the onCreateView and onActivityCreated called twice? The first time with a Bundle with the saved state and the second time with a null savedInstanceState? </p> <p>This is causing problems with retaining the state of the fragment on rotation.</p>
10,996,647
5
1
null
2012-06-11 15:44:50.657 UTC
39
2021-05-28 17:53:51.94 UTC
null
null
null
null
118,006
null
1
106
android|android-fragments|android-4.0-ice-cream-sandwich
109,472
<p>Ok, Here's what I found out. </p> <p>What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)</p> <p>What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:</p> <pre><code>mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); if (mFragment != null &amp;&amp; !mFragment.isDetached()) { Log.d(TAG, "constructor: detaching fragment " + mTag); FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } </code></pre> <p>Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:</p> <pre><code>if (savedInstanceState != null) { bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0)); Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab")); Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number")); } </code></pre> <p>When the tab was selected it would be reattached in the onTabSelected callback. </p> <pre><code>public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); Log.d(TAG, "onTabSelected adding fragment " + mTag); ft.add(android.R.id.content, mFragment, mTag); } else { Log.d(TAG, "onTabSelected attaching fragment " + mTag); ft.attach(mFragment); } } </code></pre> <p>The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time. </p> <p>The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:</p> <pre><code>public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); Log.d(TAG, "onTabSelected adding fragment " + mTag); ft.add(android.R.id.content, mFragment, mTag); } else { if(mFragment.isDetached()) { Log.d(TAG, "onTabSelected attaching fragment " + mTag); ft.attach(mFragment); } else { Log.d(TAG, "onTabSelected fragment already attached " + mTag); } } } </code></pre>
12,821,033
Comparing Datepicker Dates Javascript
<p>I'm trying to compare two <code>datepicker</code> dates and see if they are more than 7 days apart. </p> <p>How would I do this? </p> <p>I would normally just see if their difference is greater than 7, but that won't account for months and such.</p> <p>Here is my code:</p> <pre><code>var datepickerBegin = $("#datepicker_start").val(); var datepickerEnd = $("#datepicker_to").val(); if (datepickerBegin - datepickerEnd &gt; 7) { alert('more than a week apart!') } </code></pre> <p>Any tips?? </p>
12,821,180
6
2
null
2012-10-10 13:53:48.52 UTC
2
2017-05-25 10:51:56.173 UTC
2012-10-10 13:58:44.54 UTC
null
1,635,144
null
1,209,702
null
1
6
javascript|jquery|datepicker
43,102
<p>Use <code>$("#datepicker_xxx").datepicker("getDate")</code> to get the picked date as a <code>Date</code>. Then it's just a matter of </p> <pre><code>end - begin &gt; 7 * 86400 * 1000 </code></pre>
13,000,824
MVC 4 Connectionstring to SQL Server 2012
<p>I've created a brand new MVC 4 application in C# using Visual Studio 2012. I'm trying to connect to a brand new SQL Server 2012 (Standard) instance but I can't seem to get my connection string set correctly.</p> <p>My connection string from my Web.config:</p> <pre><code> &lt;connectionStrings&gt; &lt;add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=MyServerName; Initial Catalog=MyDatabaseName; Integrated Security=False; User ID=MyUserID;Password=MyPassword; MultipleActiveResultSets=True" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>Every time I go to ASP.NET Configuration from within Visual Studio, the page loads, but as soon as I click "Security" I get the following message:</p> <blockquote> <p>There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store. </p> <p>The following message may help in diagnosing the problem: <strong>Unable to connect to SQL Server database.</strong></p> </blockquote> <p>I've verified that my credentials are correct (I can use them to connect via SQL Management Studio). Is there anything else I can check? I'm stumped.</p> <p><strong>UPDATE:</strong> </p> <p>I wasn't able to connect to my default instance from within SQL Management Studio (MSSQLSERVER) so I reinstalled SQL, creating a named instance (LHSQLSERVER). Now I'm able to connect to that instance in SQL Management Studio, but I'm still getting the same error from the ASP.NET Configuration.</p> <p>Another thing to note - the aspnet_regsql tool I ran was from the Framework64\v4.0.30319 folder. Is that correct if I am using .NET 4.5?</p> <p><strong>UPDATE 2:</strong> </p> <p>I've tried replacing my connection string with a connection string to a remote site (i.e. mysite.winhost.com) that I know works, but I'm still getting the same error in the ASP.NET Website Configuration Tool? FWIW I'm also using Windows 8, but I didn't think that would matter.</p> <p>Any thing else I can check?</p> <p><strong>UPDATE 3:</strong> </p> <p>I found <a href="https://stackoverflow.com/questions/11163547/mvc-4-rc-aspnet-regsql-exe">this post</a> that says you don't need the aspnet_regsql tool anymore for MVC 4, so I re-ran the tool removing all the settings, but again, no luck. Has anyone done this with MVC 4 before?</p> <p><strong>UPDATE 4:</strong></p> <p>See my answer below for the solution I found.</p>
13,132,095
5
4
null
2012-10-21 18:29:20.787 UTC
5
2013-01-17 02:45:00.367 UTC
2017-05-23 12:33:44.733 UTC
null
-1
null
592,301
null
1
21
c#|asp.net-mvc-4|visual-studio-2012|sql-server-2012|.net-4.5
91,342
<p>Thanks everyone for the input, I have finally found a solution. I came across <strong><a href="http://www.dwdmbi.com/2012/09/visual-studio-2012-uses.html" rel="nofollow">this article</a></strong> that describes the new Simple Membership that VS 2012 uses for MVC 4. I basically just started over, creating a new database, new MVC 4 project, and just followed the instructions in the article. Sure enough, just "registering" on the web page created the table(s) in my database and stored the user information.</p>
12,714,923
OS X icons size
<p>What size should an application icon and menu bar icon for OS X be? </p> <p>I can deal with small resolution displays but what about Retina - does an icon displayed on the menu bar (e.g. 20 x 20 ) will be smaller or blurred on a new MacBook Pro with Retina display? I reckon that the Application icon will be scaled, so if I'll prepare twice larger than regular it should be OK on Retina.</p> <p>I found an excellent guide for iOS development with sizes specification but I can't find similar size specifications for OS X. </p>
14,551,094
6
0
null
2012-10-03 18:51:39.957 UTC
17
2020-05-27 11:56:29.587 UTC
2012-10-07 17:21:57.443 UTC
null
1,089,245
null
790,757
null
1
30
objective-c|xcode|macos|cocoa|retina-display
29,471
<p>NSStatusBar icons (i.e. Menu bar icons) are different from regular app icons. I have not been able to find an NSStatusBar official icon guideline, but I have to believe that the <a href="http://developer.apple.com/library/mac/#documentation/userexperience/conceptual/applehiguidelines/IconsImages/IconsImages.html#//apple_ref/doc/uid/20000967-TPXREF102%28">Toolbar Icon guideline</a> for buttons is pretty close. It suggests:</p> <ul> <li>Create icons that measure no more than 19x19 pixels.</li> <li>Make the outline sharp and clear.</li> <li>Use a straight-on perspective.</li> <li>Use black (add transparency only as necessary to suggest dimensionality).</li> <li>Use anti-aliasing.</li> <li>Use the PDF format.</li> <li>Make sure the image is visually centered in the control (note that visually centered might not be the same as mathematically centered).</li> </ul> <p>In testing, I've found:</p> <ol> <li>NSStatusBar seems to look best with something 18 pixels high, or less. The <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSStatusBar_Class/Reference/Reference.html">systemStatusBar has a thickness of 22</a>.</li> <li>While it lists PDF format, I've been using png without issue.</li> <li>If you want your icon to be white on blue when it's selected, you need to provide the alternateImage as a separate white version of your icon.</li> </ol> <p>Code sample:</p> <pre><code>myStatusItem = [[NSStatusBar systemStatusBar]statusItemWithLength:NSSquareStatusItemLength]; NSImage *statusImage = [NSImage imageNamed:@"Status.png"]; [myStatusItem setImage:statusImage]; NSImage *altStatusImage = [NSImage imageNamed:@"StatusHighlighted"]; [myStatusItem setAlternateImage:altStatusImage]; [myStatusItem setHighlightMode:YES]; [myStatusItem setMenu:self.myStatusMenu]; </code></pre>
12,750,778
Booleans in ConfigParser always return True
<p>This is my example script:</p> <pre><code>import ConfigParser config = ConfigParser.ConfigParser() config.read('conf.ini') print bool(config.get('main', 'some_boolean')) print bool(config.get('main', 'some_other_boolean')) </code></pre> <p>And this is <code>conf.ini</code>:</p> <pre><code>[main] some_boolean: yes some_other_boolean: no </code></pre> <p>When running the script, it prints <code>True</code> twice. Why? It should be <code>False</code>, as <code>some_other_boolean</code> is set to <code>no</code>.</p>
12,750,865
2
0
null
2012-10-05 16:57:23.173 UTC
2
2012-10-05 17:08:58.27 UTC
null
null
null
null
1,447,941
null
1
32
python|boolean|configparser
20,747
<p>Use <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.getboolean" rel="noreferrer"><code>getboolean()</code></a>:</p> <pre><code>print config.getboolean('main', 'some_boolean') print config.getboolean('main', 'some_other_boolean') </code></pre> <p>From the <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.getboolean" rel="noreferrer">Python manual</a>:</p> <blockquote> <pre><code>RawConfigParser.getboolean(section, option) </code></pre> <p>A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are "1", "yes", "true", and "on", which cause this method to return True, and "0", "no", "false", and "off", which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError.</p> </blockquote> <p>The <code>bool()</code> constructor converts an empty string to False. Non-empty strings are True. <code>bool()</code> doesn't do anything special for "false", "no", etc.</p> <pre><code>&gt;&gt;&gt; bool('false') True &gt;&gt;&gt; bool('no') True &gt;&gt;&gt; bool('0') True &gt;&gt;&gt; bool('') False </code></pre>
13,202,845
Removing help_text from Django UserCreateForm
<p>Probably a poor question, but I'm using Django's UserCreationForm (slightly modified to include email), and I would like to remove the help_text that Django automatically displays on the HTML page. </p> <p>On the Register portion of my HTML page, it has the Username, Email, Password1 &amp; Password 2 fields. But underneath Username is "Required. 30 characters or fewer. Letters, digits, and @... only." And under Password Confirmation (Password 2), it says "Enter the same password as above for verification." </p> <p>How do I remove these?</p> <pre><code>#models.py class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True) def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user class Meta: model = User fields = ("username", "email", "password1", "password2") exclude = ('username.help_text') #views.py def index(request): r = Movie.objects.all().order_by('-pub_date') form = UserCreateForm() return render_to_response('qanda/index.html', {'latest_movie_list': r, 'form':form}, context_instance = RequestContext(request)) #index.html &lt;form action = "/home/register/" method = "post" id = "register"&gt;{% csrf_token %} &lt;h6&gt; Create an account &lt;/h6&gt; {{ form.as_p }} &lt;input type = "submit" value = "Create!"&gt; &lt;input type = "hidden" name = "next" value = "{{ next|escape }}" /&gt; &lt;/form&gt; </code></pre>
13,203,077
10
0
null
2012-11-02 20:49:02.54 UTC
7
2021-07-24 16:20:32.563 UTC
null
null
null
null
1,669,543
null
1
33
python|django|django-models|django-registration
23,866
<p>You can set <code>help_text</code> of fields to None in <code>__init__</code></p> <pre><code>from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True) def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None print UserCreateForm() </code></pre> <p>output:</p> <pre><code>&lt;tr&gt;&lt;th&gt;&lt;label for="id_username"&gt;Username:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id="id_username" type="text" name="username" maxlength="30" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_password1"&gt;Password:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input type="password" name="password1" id="id_password1" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_password2"&gt;Password confirmation:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input type="password" name="password2" id="id_password2" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_email"&gt;Email:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input type="text" name="email" id="id_email" /&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>If you are doing too many changes, in such cases it is better to just override the fields e.g.</p> <pre><code>class UserCreateForm(UserCreationForm): password2 = forms.CharField(label=_("Whatever"), widget=MyPasswordInput </code></pre> <p>but in your case my solution will work very well.</p>
13,162,372
Using absolute unix paths in windows with python
<p>I'm creating an application that stores blob files into the hard drive, but this script must run in both linux and windows, the issue is that i want to give it an absolute path from the filesystem root and not one relative to the project files, this because im using git and dont want to deal with excluding all these files from syncing.</p> <p>So i would like to have something like this:</p> <pre><code>path = '/var/lib/blob_files/' file = open(path+'myfile.blob', 'w') </code></pre> <p>and get a file in unix at:</p> <pre><code>/var/lib/blob_files/myfile.blob </code></pre> <p>and in windows at:</p> <pre><code>C:\var\lib\blob_files\myfile.blob </code></pre> <p>it could also be relative to the user home folder (/home/user in unix and C:/Users/User in windows) but i guess the problem is very similar.</p> <p>How can i achieve this? is there any library or function that can help me transparently to convert this paths without having to ask in what plataform is the scrip running all the time?</p> <p>Of my two options, absolute from root or relative from home folder, which one do you recomend to use?</p> <p>Thanks in advance for any advice on this</p>
13,162,639
3
3
null
2012-10-31 16:19:00.667 UTC
6
2017-12-04 15:15:03.207 UTC
2012-10-31 16:55:53.323 UTC
null
84,131
null
1,712,793
null
1
35
python|windows|unix|path|cross-platform
58,550
<p>Use <code>os.path.abspath()</code>, and also <code>os.path.expanduser()</code> for files relative to the user's home directory:</p> <pre><code>print os.path.abspath("/var/lib/blob_files/myfile.blob") &gt;&gt;&gt; C:\var\lib\blob_files\myfile.blob print os.path.abspath(os.path.expanduser("~/blob_files/myfile.blob")) &gt;&gt;&gt; C:\Users\jerry\blob_files\myfile.blob </code></pre> <p>These will "do the right thing" for both Windows and POSIX paths.</p> <p><code>expanduser()</code> won't change the path if it doesn't have a <code>~</code> in it, so you can safely use it with all paths. Thus, you can easily write a wrapper function:</p> <pre><code>import os def fixpath(path): return os.path.abspath(os.path.expanduser(path)) </code></pre> <p>Note that the drive letter used will be the drive specified by the current working directory of the Python process, usually the directory your script is in (if launching from Windows Explorer, and assuming your script doesn't change it). If you want to force it to always be <code>C:</code> you can do something like this:</p> <pre><code>import os def fixpath(path): path = os.path.normpath(os.path.expanduser(path)) if path.startswith("\\"): return "C:" + path return path </code></pre>
12,902,410
Trying to understand CMTime
<p>I have seen some <a href="https://stackoverflow.com/questions/5808557/avassetwriterinputpixelbufferadaptor-and-cmtime">examples</a> <a href="https://stackoverflow.com/questions/5396800/help-me-understand-cmtime-in-avassetwriter">of</a> <a href="https://stackoverflow.com/questions/4001755/trying-to-understand-cmtime-and-cmtimemake">CMTime</a> (Three separate links), but I still don't get it. I'm using an AVCaptureSession with AVCaptureVideoDataOutput and I want to set the max and min frame rate of the the output. My problem is I just don't understand the CMTime struct.</p> <p>Apparently CMTimeMake(value, timeScale) should give me value frames every 1/timeScale seconds for a total of value/timeScale seconds, or am I getting that wrong?</p> <p>Why isn't this documented anywhere in order to explain what this does?</p> <p>If it does truly work like that, how would I get it to have an indefinite number of frames?</p> <p>If its really simple, I'm sorry, but nothing has clicked just yet.</p>
13,001,917
3
2
null
2012-10-15 19:11:11.393 UTC
23
2022-03-14 11:56:26.03 UTC
2017-05-23 10:31:30.387 UTC
null
-1
null
1,292,230
null
1
73
ios|avcapturesession|cmtime
33,620
<p>A <code>CMTime</code> struct represents a length of time that is stored as rational number (see <a href="https://developer.apple.com/library/mac/#documentation/CoreMedia/Reference/CMTime/Reference/reference.html" rel="noreferrer">CMTime Reference</a>). <code>CMTime</code> has a <code>value</code> and a <code>timescale</code> field, and represents the time <code>value/timescale seconds</code> .</p> <p><code>CMTimeMake</code> is a function that returns a <code>CMTime</code> structure, for example:</p> <pre><code>CMTime t1 = CMTimeMake(1, 10); // 1/10 second = 0.1 second CMTime t2 = CMTimeMake(2, 1); // 2 seconds CMTime t3 = CMTimeMake(3, 4); // 3/4 second = 0.75 second CMTime t4 = CMTimeMake(6, 8); // 6/8 second = 0.75 second </code></pre> <p>The last two time values <code>t3</code> and <code>t4</code> represent the same time value, therefore</p> <pre><code>CMTimeCompare(t3, t4) == 0 </code></pre> <p>If you set the <code>videoMinFrameDuration</code> of a <code>AVCaptureSession</code> is does not make a difference if you set</p> <pre><code>connection.videoMinFrameDuration = CMTimeMake(1, 20); // or connection.videoMinFrameDuration = CMTimeMake(2, 40); </code></pre> <p>In both cases the minimum time interval between frames is set to 1/20 = 0.05 seconds.</p>
30,584,554
How I can remove the unnecessary top padding of the Navigation view?
<p>There's an unnecessary top padding between the header and the first item shown in this picture.</p> <p><img src="https://i.stack.imgur.com/RGuAAl.png" alt="enter image description here"></p> <p>How it can be removed?</p> <p>you can find the source code here: <a href="https://github.com/chrisbanes/cheesesquare">https://github.com/chrisbanes/cheesesquare</a></p>
30,585,374
5
7
null
2015-06-01 22:45:21.993 UTC
9
2019-10-14 11:28:55.517 UTC
2019-10-14 11:28:55.517 UTC
null
2,016,562
null
976,836
null
1
31
android|material-design|android-support-library|android-design-library|android-navigationview
19,705
<p><code>NavigationView</code> seeks to match the material design <a href="http://www.google.com/design/spec/patterns/navigation-drawer.html" rel="noreferrer">specs for the navigation drawer</a> which state an 8dp space between content areas. Generally there are no ways to override <code>NavigationView</code> to specifically break the specifications.</p> <p><img src="https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7SEltaWlHZHFGdU0/patterns_navdrawer_metrics3.png" alt="material design specs"></p>
16,598,549
JSON format for jquery-select2 multi with ajax
<p>I'm thinking in moving from Chosen to Select2 because Select2 has native methods for ajax. Ajax is critical because usualy you have to load a lot of data. </p> <p>I executed sucessfully the example with the JSON of api.rottentomatoes.com/api/</p> <p>I did a JSON file to test the ajax, but it didn't works.</p> <p>I don't know how the JSON should be. It seems that there is no detailed documentation:</p> <p><a href="https://github.com/ivaynberg/select2/issues/920">https://github.com/ivaynberg/select2/issues/920</a></p> <p>I tried unsucessfully several JSON formats, so I tried to copy a JSON format similar to api.rottentomatoes but it doesn't works. </p> <p>I may be missing something stupid.</p> <pre><code>function MultiAjaxAutoComplete(element, url) { $(element).select2({ placeholder: "Search for a movie", minimumInputLength: 1, multiple: true, ajax: { url: url, dataType: 'jsonp', data: function(term, page) { return { q: term, page_limit: 10, apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey }; }, results: function(data, page) { return { results: data.movies }; } }, formatResult: formatResult, formatSelection: formatSelection, /*initSelection: function(element, callback) { var data = []; $(element.val().split(",")).each(function(i) { var item = this.split(':'); data.push({ id: item[0], title: item[1] }); }); //$(element).val(''); callback(data); }*/ }); }; function formatResult(node) { return '&lt;div&gt;' + node.id + '&lt;/div&gt;'; }; function formatSelection(node) { return node.id; }; /*MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');*/ MultiAjaxAutoComplete('#e6', 'https://raw.github.com/katio/Quick-i18n/master/test.json'); $('#save').click(function() { alert($('#e6').val()); }); </code></pre> <p>I did this jsfiddle:</p> <p><a href="http://jsfiddle.net/Katio/H9RZm/4/">http://jsfiddle.net/Katio/H9RZm/4/</a></p>
16,598,788
2
1
null
2013-05-16 22:27:59.597 UTC
4
2018-02-06 11:50:59.097 UTC
null
null
null
null
2,391,782
null
1
18
javascript|jquery|twitter-bootstrap|jquery-select2|jquery-chosen
45,942
<p>If you switched to JSON make sure you switch dataType to JSON from JSONP.</p> <p>The format is specified here: <a href="http://ivaynberg.github.io/select2/#doc-query" rel="noreferrer">http://ivaynberg.github.io/select2/#doc-query</a></p> <p>The JSON should look like this:</p> <pre><code>{results: [choice1, choice2, ...], more: true/false } </code></pre> <p>Basically the only required attribute in the choice is the <code>id</code>. if the option contains other child options (such as in case of optgroup-like choices) then those are specified inside the <code>children</code> attribute.</p> <p>The default choice and selection renderer expect a <code>text</code> attribute in every choice - that's what is used to render the choice.</p> <p>so a complete example of a US state using default renderer might look like this:</p> <pre><code>{ "results": [ { "id": "CA", "text": "California" }, { "id": "CO", "text": "Colarado" } ], "more": false } </code></pre> <p>Hope this gets you started.</p>
16,628,088
Euclidean algorithm (GCD) with multiple numbers?
<p>So I'm writing a program in Python to get the GCD of any amount of numbers.</p> <pre><code>def GCD(numbers): if numbers[-1] == 0: return numbers[0] # i'm stuck here, this is wrong for i in range(len(numbers)-1): print GCD([numbers[i+1], numbers[i] % numbers[i+1]]) print GCD(30, 40, 36) </code></pre> <p>The function takes a list of numbers. This should print 2. However, I don't understand how to use the the algorithm recursively so it can handle multiple numbers. Can someone explain? </p> <p>updated, still not working:</p> <pre><code>def GCD(numbers): if numbers[-1] == 0: return numbers[0] gcd = 0 for i in range(len(numbers)): gcd = GCD([numbers[i+1], numbers[i] % numbers[i+1]]) gcdtemp = GCD([gcd, numbers[i+2]]) gcd = gcdtemp return gcd </code></pre> <hr> <p>Ok, solved it</p> <pre><code>def GCD(a, b): if b == 0: return a else: return GCD(b, a % b) </code></pre> <p>and then use reduce, like</p> <pre><code>reduce(GCD, (30, 40, 36)) </code></pre>
16,628,379
10
3
null
2013-05-18 19:19:31.72 UTC
5
2020-10-24 05:35:36.17 UTC
2013-05-18 19:33:35.26 UTC
null
1,846,280
null
1,846,280
null
1
33
python|math|greatest-common-divisor
52,617
<p>Since GCD is associative, <code>GCD(a,b,c,d)</code> is the same as <code>GCD(GCD(GCD(a,b),c),d)</code>. In this case, Python's <a href="http://docs.python.org/2/library/functions.html#reduce" rel="noreferrer"><code>reduce</code></a> function would be a good candidate for reducing the cases for which <code>len(numbers) &gt; 2</code> to a simple 2-number comparison. The code would look something like this:</p> <pre><code>if len(numbers) &gt; 2: return reduce(lambda x,y: GCD([x,y]), numbers) </code></pre> <p>Reduce applies the given function to each element in the list, so that something like</p> <pre><code>gcd = reduce(lambda x,y:GCD([x,y]),[a,b,c,d]) </code></pre> <p>is the same as doing</p> <pre><code>gcd = GCD(a,b) gcd = GCD(gcd,c) gcd = GCD(gcd,d) </code></pre> <p>Now the only thing left is to code for when <code>len(numbers) &lt;= 2</code>. Passing only two arguments to <code>GCD</code> in <code>reduce</code> ensures that your function recurses at most once (since <code>len(numbers) &gt; 2</code> only in the original call), which has the additional benefit of never overflowing the stack.</p>
4,465,562
How to write W3C compliant multi-level bullet points in HTML?
<p>Is it possible to write W3C compliant multi-level bullet points (unordered list) in HTML?</p> <p>Nested ul can be used, but is not W3C compliant.</p> <pre><code> &lt;ul&gt; &lt;li&gt;myItem 1&lt;/li&gt; &lt;li&gt;myItem 2&lt;/li&gt; &lt;ul&gt; &lt;li&gt;myItem 2a&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;myItem 3&lt;/li&gt; &lt;li&gt;myItem 4&lt;/li&gt; &lt;/ul&gt; </code></pre> <ul> <li>myItem 1</li> <li>myItem 2</li> <ul> <li>myItem 2a</li> </ul> <li>myItem 3</li> <li>myItem 4</li> </ul> <p>In Visual Studio, the above code gives the warning: <strong>Validation (XHTML 1.0 Transitional): Element 'ul' cannot be nested within element 'ul'</strong></p>
4,465,759
2
4
null
2010-12-16 21:31:17.267 UTC
5
2020-07-31 14:48:08.227 UTC
2010-12-16 21:42:01.92 UTC
null
2,699
null
2,699
null
1
49
html|w3c-validation|html-lists
73,208
<p>The only valid child of either a <code>ul</code> or <code>ol</code> is an <code>li</code> element; an <code>li</code> can, however, contain a <code>ul</code> (or <code>ol</code>). To achieve your aim:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;myItem 1&lt;/li&gt; &lt;li&gt;myItem 2&lt;/li&gt; &lt;li style="list-style-type:none"&gt; &lt;ul&gt; &lt;li&gt;myItem 2a&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;myItem 3&lt;/li&gt; &lt;li&gt;myItem 4&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
10,110,035
which database suits my application mysql or mongodb ? using Node.js , Backbone , Now.js
<p>I want to make an application like docs.google.com (without its api,completely on my own server) using frontend : backbone backend : node </p> <p>What database would u think is better ? mysql or mongodb ? Should support good scalability . I am familiar with mysql with php and i will be happy if the answer is mysql. But many tutorials i saw, they used mongodb, why did they use mongodb without mysql ? What should i use ?</p> <p>Can anyone give me link for some sample application(with source) build using backbone , Node , mysql (or mongo) . or atleast app. with Node and mysql </p> <p>Thanks</p>
10,110,334
3
0
null
2012-04-11 16:27:33.573 UTC
8
2019-10-03 17:30:01.283 UTC
null
null
null
null
1,305,989
null
1
22
mysql|node.js|mongodb|backbone.js
24,849
<p>With MongoDB, you can just <em>store</em> JSON objects and retrieve them fully-formed, so you don't really need an ORM layer and you spend less CPU time translating your data back-and-forth. The developers behind MongoDB have also made horizontally scaling the database a higher priority and let you run arbitrary Javascript code to pre-process data on the DB side (allowing map-reduce style filtering of data).</p> <p>But you lose some for these gains: You can't join records. Actually, the JSON structure you store could only be done via joins in SQL, but in MongoDB you only have that one structure to your data, while in SQL you can query differently and get your data represented in alternate ways much easier, so if you need to do a lot of analytics on your database, MongoDB will make that harder.</p> <p>The query language in MongoDB is "rougher", in my opinion, than SQL's, partly because it's less familiar, and partly because the querying features "feel" haphazardly put together, partially to make it valid JSON, and partially because there are literally a couple of ways of doing the same thing, and some are older ways that aren't as useful or regularly-formatted as the others. And there's the added complexity of the array and sub-object types over SQL's simple row-based design, so the syntax has to be able to handle querying for arrays that contain <em>some</em> of the values you defined, contain <em>all</em> of the values you defined, contain <em>only</em> the values you defined, and contain <em>none</em> of the values you defined. The same distinctions apply to object keys and their values, and this makes the query syntax harder to grasp. (And while I can see the need for edge-cases, the <code>$where</code> query parameter, which takes a javascript function that is run on every record of the data and returns a boolean, is a Siren song because you can easily define what objects you want to return or not, but it has to run on <em>every</em> record in the database, no indexes can be used.)</p> <p>So, it depends on what you want to do, but since you say it's for a Google Docs clone, you <em>probably</em> don't care about any representation <em>but</em> the document representation, itself, and you're <em>probably</em> only going to query based on document ID, document name, or the owner's ID/name, nothing too complex in the querying.</p> <p>Then, I'd say being able to take the JSON representation of the document your user is editing, and just throw it into the database and have it automatically index these important fields, is worth the price of learning a new database.</p>
10,120,866
How to unit test with a file upload in mocha
<p>I have an app built on Express.js and I'd like to test the file upload functionality. I'm trying to reproduce the object parsed to req.files (when using express.bodyParser middleware). How can I do this?</p>
10,642,798
8
0
null
2012-04-12 09:25:42.377 UTC
9
2022-06-15 12:00:37.523 UTC
null
null
null
null
999,032
null
1
34
node.js|express
33,981
<p>You can do this directly in Mocha but it's a bit tricky. Here's an example posting an image:</p> <pre><code>var filename = 'x.png' , boundary = Math.random() request(app) .post('/g/' + myDraftGallery._id) .set('Content-Type', 'multipart/form-data; boundary=' + boundary) .write('--' + boundary + '\r\n') .write('Content-Disposition: form-data; name="image"; filename="'+filename+'"\r\n') .write('Content-Type: image/png\r\n') .write('\r\n') .write(fs.readFileSync('test/'+filename)) .write('\r\n--' + boundary + '--') .end(function(res){ res.should.have.status(200) done() }) </code></pre> <p>The <em>name</em> parameter of Content-Disposition is what your file will be accessible as via req.files (so req.files.image for my example) You can also use an array value like this: name="images[]" and your file(s) will be available via an array, e.g: req.files.images[0]</p> <p>Also if you're not already using it you should have a look at this (makes mocha/express testing a ~bit~ easier): <a href="https://github.com/visionmedia/express/blob/master/test/support/http.js" rel="noreferrer">https://github.com/visionmedia/express/blob/master/test/support/http.js</a></p> <p><strong>Edit</strong>: Since express 3-beta5, express uses supertest. To look at the old http.js code look here: <a href="https://github.com/visionmedia/express/blob/3.0.0beta4/test/support/http.js" rel="noreferrer">https://github.com/visionmedia/express/blob/3.0.0beta4/test/support/http.js</a> Or simply move over to supertest..</p>
10,088,706
How can I center elements horizontally or vertically with Twitter Bootstrap?
<p>Is there any way to center html elements vertically or horizontally inside the main parents?</p>
14,642,860
12
0
null
2012-04-10 12:21:34.187 UTC
58
2022-07-21 13:18:02.067 UTC
2022-03-24 12:50:37.447 UTC
null
1,264,804
null
895,174
null
1
295
css|twitter-bootstrap
586,783
<p><strong>Update</strong>: while this answer was likely correct back in early 2013, it should not be used anymore. The proper solution <a href="https://stackoverflow.com/a/40002430/1729885">uses offsets</a>, like so:</p> <pre><code>class=&quot;mx-auto&quot; </code></pre> <hr /> <p>As for other users suggestion there are also native bootstrap classes available like:</p> <pre><code>class=&quot;text-center&quot; class=&quot;pagination-centered&quot; </code></pre>
10,154,568
Postpone code for later execution in python (like setTimeout in javascript)
<p>I have to do a program in python that needs to execute for some time and then (does not matter where it was executing) it must dump information to a file, close the file and then exit.</p> <p>The behavior here is equivalent in JavaScript to using <code>setTimeout(func, 1000000)</code> where its first parameter (func) would be a pointer to the function with the exit code and its second parameter would be the time available to the program to execute.</p> <p>I know how to make this program in C (using SO signals) but with python </p>
15,456,828
4
4
null
2012-04-14 15:01:00.273 UTC
21
2022-06-15 10:58:15.817 UTC
2012-10-13 14:41:56.537 UTC
null
275,567
null
551,625
null
1
63
python
60,779
<p>In practice, a <a href="http://docs.python.org/2/library/threading.html#timer-objects" rel="noreferrer">Timer</a> is probably the simplest way to do what you want. </p> <p>This code will do the following:</p> <ul> <li>After 1 second, it prints "arg1 arg2"</li> <li>After 2 seconds, it prints "OWLS OWLS OWLS"</li> </ul> <p>===</p> <pre><code>from threading import Timer def twoArgs(arg1,arg2): print arg1 print arg2 print "" def nArgs(*args): for each in args: print each #arguments: #how long to wait (in seconds), #what function to call, #what gets passed in r = Timer(1.0, twoArgs, ("arg1","arg2")) s = Timer(2.0, nArgs, ("OWLS","OWLS","OWLS")) r.start() s.start() </code></pre> <p>===</p> <p>The above code will most likely solve your problem.</p> <p>But! There is alternative way, that doesn't use multithreading. It works much more like Javascript, which is single-threaded. </p> <p>For this single-thread version, all you need to do is store the function and its arguments in an object, along with the time at which the function should be run.</p> <p>Once you have the object containing the function call and the timeout, just periodically check if the function is ready to execute. </p> <p>The right way to do this is by making a <a href="http://en.wikipedia.org/wiki/Priority_queue" rel="noreferrer">priority queue</a> to store all of the functions we want to run in the future, as shown in the code below. </p> <p>Just like in Javascript, this approach makes no guarantee that the function will be run exactly on time. A function that takes a very long time to run will delay the functions after it. But it does guarantee that a function will be run <em>no sooner</em> than its timeout.</p> <p>This code will do the following:</p> <ul> <li>After 1 second, it prints "20"</li> <li>After 2 seconds, it prints "132"</li> <li>After 3 seconds, it quits. </li> </ul> <p>===</p> <pre><code>from datetime import datetime, timedelta import heapq # just holds a function, its arguments, and when we want it to execute. class TimeoutFunction: def __init__(self, function, timeout, *args): self.function = function self.args = args self.startTime = datetime.now() + timedelta(0,0,0,timeout) def execute(self): self.function(*self.args) # A "todo" list for all the TimeoutFunctions we want to execute in the future # They are sorted in the order they should be executed, thanks to heapq class TodoList: def __init__(self): self.todo = [] def addToList(self, tFunction): heapq.heappush(self.todo, (tFunction.startTime, tFunction)) def executeReadyFunctions(self): if len(self.todo) &gt; 0: tFunction = heapq.heappop(self.todo)[1] while tFunction and datetime.now() &gt; tFunction.startTime: #execute all the functions that are ready tFunction.execute() if len(self.todo) &gt; 0: tFunction = heapq.heappop(self.todo)[1] else: tFunction = None if tFunction: #this one's not ready yet, push it back on heapq.heappush(self.todo, (tFunction.startTime, tFunction)) def singleArgFunction(x): print str(x) def multiArgFunction(x, y): #Demonstration of passing multiple-argument functions print str(x*y) # Make some TimeoutFunction objects # timeout is in milliseconds a = TimeoutFunction(singleArgFunction, 1000, 20) b = TimeoutFunction(multiArgFunction, 2000, *(11,12)) c = TimeoutFunction(quit, 3000, None) todoList = TodoList() todoList.addToList(a) todoList.addToList(b) todoList.addToList(c) while True: todoList.executeReadyFunctions() </code></pre> <p>===</p> <p>In practice, you would likely have more going on in that while loop than just checking if your timeout functions are ready to go. You might be polling for user input, controlling some hardware, reading data, etc.</p>
8,108,642
Type of integer literals not int by default?
<p>I just answered <a href="https://stackoverflow.com/q/8108171/743214">this question</a>, which asked why iterating until 10 billion in a for loop takes so much longer (the OP actually aborted it after 10 mins) than iterating until 1 billion:</p> <pre><code>for (i = 0; i &lt; 10000000000; i++) </code></pre> <p>Now my and many others' obvious answer was that it was due to the iteration variable being 32-bit (which never reaches 10 billion) and the loop getting an infinite loop.</p> <p>But though I realized this problem, I still wonder what was really going on inside the compiler?</p> <p>Since the literal was not appended with an <code>L</code>, it should IMHO be of type <code>int</code>, too, and therefore 32-bit. So due to overflow it should be a normal <code>int</code> inside the range to be reachable. To actually recognize that it cannot be reached from <code>int</code>, the compiler needs to know that it is 10 billion and therefore see it as a more-than-32-bit constant.</p> <p>Does such a literal get promoted to a fitting (or at least implementation-defined) range (at least 64-bit, in this case) automatically, even if not appended an <code>L</code> and is this standard behaviour? Or is something different going on behind the scenes, like UB due to overflow (is integer overflow actually UB)? Some quotes from the Standard may be nice, if any.</p> <p>Although the original question was C, I also appreciate C++ answers, if any different.</p>
8,108,658
3
7
null
2011-11-13 00:24:41.413 UTC
9
2011-11-15 02:45:56.513 UTC
2017-05-23 11:53:53.593 UTC
null
-1
null
743,214
null
1
36
c++|c|overflow|literals
13,775
<p>As far as C++ is concerned:</p> <p>C++11, [lex.icon] ¶2</p> <blockquote> <p>The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented.</p> </blockquote> <p>And Table 6, for literals without suffixes and decimal constants, gives:</p> <pre><code>int long int long long int </code></pre> <p>(interestingly, for hexadecimal or octal constants also <code>unsigned</code> types are allowed - but each one come <em>after</em> the corresponding signed one in the list)</p> <p>So, it's clear that in that case the constant has been interpreted as a <code>long int</code> (or <code>long long int</code> if <code>long int</code> was too 32 bit).</p> <p>Notice that "too big literals" should result in a compilation error:</p> <blockquote> <p>A program is ill-formed if one of its translation units contains an integer literal that cannot be represented by any of the allowed types.</p> </blockquote> <p>(ibidem, ¶3)</p> <p>which is promptly seen <a href="http://ideone.com/9hujM">in this sample</a>, that reminds us that ideone.com uses 32 bit compilers.</p> <hr /> <p>I saw now that the question was about C... well, it's more or less the same:</p> <p>C99, §6.4.4.1</p> <blockquote> <p>The type of an integer constant is the first of the corresponding list in which its value can be represented.</p> </blockquote> <p>list that is the same as in the C++ standard.</p> <hr /> <p>Addendum: both C99 and C++11 allow also the literals to be of "extended integer types" (i.e. other implementation-specific integer types) if everything else fails. (C++11, [lex.icon] ¶3; C99, §6.4.4.1 ¶5 after the table)</p>
11,714,721
How to set the space between lines in a div without setting line height
<p>I have a div containing elements with display set to inline-block. These contained elements have various heights. The resulting lines in the div have various heights, according to the heights of the elements in them. This is as I want it. But I want to add some space between the lines in the div. For example, elements in adjacent lines with background color set should have a visible gap between them. The common advice for a paragrpah is to set line-height, but this sets the same height for all lines in the div, which I don't want. Is there a way to set a space between the lines without making all the lines the same height and without modifying the contained elements?</p> <p>In a simplified form the HTML content looks like this:</p> <pre><code>&lt;div&gt; &lt;div style="display: inline-block;..."&gt;variable stuff&lt;/div&gt; &lt;div style="display: inline-block;..."&gt;variable stuff&lt;/div&gt; &lt;div style="display: inline-block;..."&gt;variable stuff&lt;/div&gt; &lt;div style="display: inline-block;..."&gt;variable stuff&lt;/div&gt; ... &lt;/div&gt; </code></pre> <p>Each inner div has different content: different height and width.</p> <p>I can style all the inner divs. Pragmatically, I have already done that and have a result I could live with. But I was surprised to see that CSS doesn't have an obvious way to set line spacing (i.e. the space between lines, as opposed to the height of lines: I know about line-height but it is not, directly, line spacing and has the (undesired in this instance) effect of making all the lines the same height - even the lines where all the elements in the line have a low height). I am curious to know if there is a way to set line spacing as a parameter of the outer div, without setting the line height.</p> <p>I think of it as line spacing, but another way to think of it is top and bottom margin on each line in the outer div, rather than on the outer div as a whole, and without overriding the top and bottom margins of all the inner divs (which is what I have done for now) or making all the lines the same height (as line-height does). </p> <p>The only way I can think of to do it without overriding the margins of the inner divs, is by wrapping each in another div, simply to set a common margin. If I do it this way, the margins of the two divs don't collapse, which I can live with. This works well enough in this case, where all the content is divs, but it wouldn't work if I had mixed text and divs (i.e. text interspersed with divs), in which case I would be back to wishing I could find a way to specify line spacing.</p>
11,720,229
4
0
null
2012-07-30 02:19:28.257 UTC
1
2013-01-21 20:58:13.803 UTC
2012-07-30 04:03:21.357 UTC
null
1,339,621
null
1,339,621
null
1
4
html|css
42,999
<p>That can only be done using <code>margin</code> style. You don't need to wrap each contained <code>DIV</code>s with another <code>DIV</code>. Just use the <code>STYLE</code> tag.</p> <p>Here's an example. Border and colorings are added for demo purpose.</p> <pre><code>&lt;style&gt; #container {width:30ex; outline:1px solid black; padding:0 .2em; background:white;} #container&gt;div {display:inline-block; margin:.2em 0; background:#fca;} &lt;/style&gt; &lt;div id="container"&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;div style="height:5em"&gt;variable stuff variable&lt;/div&gt; &lt;div style="height:2em"&gt;variable stuff&lt;/div&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;div style="height:3em"&gt;variable stuff variable stuff&lt;/div&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;div style="height:1em"&gt;variable&lt;/div&gt; &lt;/div&gt; </code></pre>
11,709,391
How to get Doctrine ORM instance in Symfony2 console application?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/7597912/how-can-i-inject-dependencies-to-symfony-console-commands">How can i inject dependencies to Symfony Console commands?</a> </p> </blockquote> <p>I want to make console application, which changes some records from the database (using Cron, every hour). How to get Doctrine ORM instance here?</p> <p>In casual controller, I do this:</p> <pre><code>$this-&gt;getDoctrine(); </code></pre>
11,709,562
1
0
null
2012-07-29 12:51:27.137 UTC
6
2012-07-29 13:19:58.747 UTC
2017-05-23 12:09:55.743 UTC
null
-1
null
1,504,252
null
1
35
symfony|doctrine-orm|console-application
27,037
<p>If you extend from <code>ContainerAwareCommand</code> you should be able to get your service</p> <pre><code>$this-&gt;getContainer()-&gt;get('doctrine'); </code></pre> <p><a href="https://stackoverflow.com/questions/7597912/how-can-i-inject-dependencies-to-symfony-console-commands">Here</a> is similar question</p>
11,643,137
Ternary ? operator vs the conventional If-else operator in c#
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2259741/is-the-conditional-operator-slow">Is the conditional operator slow?</a> </p> </blockquote> <p>I'm a massive user of the <code>?</code> operator in C#. However my project manager frequently warns me that using <code>?</code> operator might cost some performance compared to the <code>If-Else</code> statements in a large scale application. So I'm told to avoid using it. However, I love using it because it is concise and sort of keeps the code clean.</p> <p>Is there such performance overhead when using <code>?</code> operator?</p>
11,643,364
5
9
null
2012-07-25 05:12:58.393 UTC
10
2012-07-25 05:47:52.233 UTC
2017-05-23 11:47:20.577 UTC
null
-1
null
615,798
null
1
44
c#|if-statement|ternary-operator
30,752
<p>I ran 100 million Ternary Operators and 100 million If-Else statements and recorded the performance of each. Here is the code:</p> <pre><code>Stopwatch s = new Stopwatch(); // System.Diagnostics Stopwatch int test = 0; s.Start(); for(int a = 0; a &lt; 100000000; a++) test = a % 50 == 0 ? 1 : 2; s.Stop(); s.Restart(); for(int b = 0; b &lt; 100000000; b++) { if(b % 50 == 0) test = 1; else test = 2; } s.Stop(); </code></pre> <p>Here is the results (ran on an Intel Atom 1.66ghz with 1gb ram and I know, it sucks):</p> <ul> <li><p>Ternary Operator: 5986 milliseconds or 0.00000005986 seconds per each operator.</p></li> <li><p>If-Else: 5667 milliseconds or 0.00000005667 seconds per each statement.</p></li> </ul> <p>Don't forget that I ran 100 million of them, and I don't think 0.00000000319 seconds difference between the two matters that much.</p>
11,524,790
Gradle counterpart to Maven archetype?
<p>What is the Gradle counterpart to Maven archetypes? How can I give other Gradle users a template for the file and directory layout for a new project?</p>
11,525,156
9
0
null
2012-07-17 14:32:19.143 UTC
11
2020-07-07 18:02:13.427 UTC
2012-09-20 08:53:34.01 UTC
null
1,047,365
null
238,134
null
1
71
maven|gradle|maven-archetype
28,843
<p>Gradle doesn't support this (yet). There's a open <a href="http://issues.gradle.org/browse/GRADLE-1289" rel="noreferrer">feature request</a> opened already.</p>
11,456,850
Split a string by commas but ignore commas within double-quotes using Javascript
<p>I'm looking for <code>[a, b, c, "d, e, f", g, h]</code>to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm trying to do this through Javascript. This is what I have so far:</p> <pre><code>str = str.split(/,+|"[^"]+"/g); </code></pre> <p>But right now it's splitting out everything that's in the double-quotes, which is incorrect.</p> <p>Edit: Okay sorry I worded this question really poorly. I'm being given a string not an array.</p> <pre><code>var str = 'a, b, c, "d, e, f", g, h'; </code></pre> <p>And I want to turn <em>that</em> into an array using something like the "split" function.</p>
11,457,952
17
6
null
2012-07-12 16:59:26.483 UTC
32
2022-06-20 15:00:08.37 UTC
2020-02-09 20:21:57.537 UTC
null
1,127,428
null
1,241,292
null
1
78
javascript|regex
95,202
<p>Here's what I would do.</p> <pre><code>var str = 'a, b, c, &quot;d, e, f&quot;, g, h'; var arr = str.match(/(&quot;.*?&quot;|[^&quot;,\s]+)(?=\s*,|\s*$)/g); </code></pre> <p><a href="https://i.stack.imgur.com/E0Tbw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/E0Tbw.png" alt="enter image description here" /></a> /* will match:</p> <pre><code> ( &quot;.*?&quot; double quotes + anything but double quotes + double quotes | OR [^&quot;,\s]+ 1 or more characters excl. double quotes, comma or spaces of any kind ) (?= FOLLOWED BY \s*, 0 or more empty spaces and a comma | OR \s*$ 0 or more empty spaces and nothing else (end of string) ) */ arr = arr || []; // this will prevent JS from throwing an error in // the below loop when there are no matches for (var i = 0; i &lt; arr.length; i++) console.log('arr['+i+'] =',arr[i]); </code></pre>
19,979,518
What is Python's heapq module?
<p>I tried <a href="https://docs.python.org/3/library/heapq.html" rel="noreferrer">"heapq"</a> and arrived at the conclusion that my expectations differ from what I see on the screen. I need somebody to explain how it works and where it can be useful.</p> <p>From the book <a href="http://pymotw.com/2/articles/data_structures.html#sorting" rel="noreferrer">Python Module of the Week</a> under paragraph <strong>2.2 Sorting</strong> it is written</p> <blockquote> <p>If you need to maintain a sorted list as you add and remove values, check out heapq. By using the functions in heapq to add or remove items from a list, you can maintain the sort order of the list with low overhead.</p> </blockquote> <p>Here is what I do and get.</p> <pre><code>import heapq heap = [] for i in range(10): heap.append(i) heap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] heapq.heapify(heap) heapq.heappush(heap, 10) heap [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] heapq.heappop(heap) 0 heap [1, 3, 2, 7, 4, 5, 6, 10, 8, 9] &lt;&lt;&lt; Why the list does not remain sorted? heapq.heappushpop(heap, 11) 1 heap [2, 3, 5, 7, 4, 11, 6, 10, 8, 9] &lt;&lt;&lt; Why is 11 put between 4 and 6? </code></pre> <p>So, as you see the "heap" list is not sorted at all, in fact the more you add and remove the items the more cluttered it becomes. Pushed values take unexplainable positions. What is going on? </p>
19,979,723
4
9
null
2013-11-14 13:54:16.953 UTC
26
2019-11-03 15:50:21.073 UTC
2016-09-10 11:43:39.33 UTC
null
2,183,102
null
1,984,680
null
1
79
python|data-structures|heap|python-module
77,696
<p>The <code>heapq</code> module maintains the <em>heap invariant</em>, which is not the same thing as maintaining the actual list object in sorted order.</p> <p>Quoting from the <a href="http://docs.python.org/2/library/heapq.html" rel="noreferrer"><code>heapq</code> documentation</a>:</p> <blockquote> <p>Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which <code>heap[k] &lt;= heap[2*k+1]</code> and <code>heap[k] &lt;= heap[2*k+2]</code> for all <code>k</code>, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, <code>heap[0]</code>.</p> </blockquote> <p>This means that it is very efficient to find the smallest element (just take <code>heap[0]</code>), which is great for a priority queue. After that, the next 2 values will be larger (or equal) than the 1st, and the next 4 after that are going to be larger than their 'parent' node, then the next 8 are larger, etc.</p> <p>You can read more about the theory behind the datastructure in the <a href="http://docs.python.org/2/library/heapq.html#theory" rel="noreferrer">Theory section of the documentation</a>. You can also watch <a href="http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/" rel="noreferrer">this lecture from the MIT OpenCourseWare Introduction to Algorithms course</a>, which explains the algorithm in general terms.</p> <p>A heap can be turned back into a sorted list very efficiently:</p> <pre><code>def heapsort(heap): return [heapq.heappop(heap) for _ in range(len(heap))] </code></pre> <p>by just popping the next element from the heap. Using <code>sorted(heap)</code> should be faster still, however, as the TimSort algorithm used by Python’s sort will take advantage of the partial ordering already present in a heap.</p> <p>You'd use a heap if you are only interested in the smallest value, or the first <code>n</code> smallest values, especially if you are interested in those values on an ongoing basis; adding new items and removing the smallest is very efficient indeed, more so than resorting the list each time you added a value.</p>
3,743,632
GIS: PostGIS/PostgreSQL vs. MySql vs. SQL Server?
<p><strong>EDIT: I have been using Postgres with PostGIS for a few months now, and I am satisfied.</strong></p> <p>I need to analyze a few million geocoded records, each of which will have latitude and longitude. These records include data of at least three different types, and I will be trying to see if each set influences the other.</p> <p>What database is best for the underlying data store for all this data? Here's my desires:</p> <ul> <li><strong>I'm familiar with the DBMS.</strong> I'm weakest with PostgreSQL, but I am willing to learn if everything else checks out.</li> <li><strong>It does well with GIS queries.</strong> Google searches suggest that PostgreSQL + PostGIS may be the strongest? At least a lot of products seem to use it. MySql's Spatial Extensions seem comparatively minimal?</li> <li><strong>Low cost.</strong> Despite the 10GB DB limit in SQL Server Express 2008 R2, I'm not sure I want to live with this and other limitations of the free version.</li> <li><strong>Not antagonistic with Microsoft .NET Framework.</strong> Thanks to Connector/Net 6.3.4, MySql works well C# and .NET Framework 4 programs. It fully supports .NET 4's Entity Framework. I cannot find any noncommercial PostgreSQL equivalent, although I'm not opposed to paying $180 for Devart's dotConnect for PostgreSQL Professional Edition.</li> <li><strong>Compatible with R.</strong> It appears all 3 of these can talk with R using ODBC, so may not be an issue.</li> </ul> <p>I've already done some development using MySql, but I can change if necessary.</p>
3,743,807
5
5
null
2010-09-18 21:44:53.973 UTC
29
2019-01-02 01:36:54.217 UTC
2011-05-23 04:02:57.65 UTC
null
425,477
null
425,477
null
1
72
mysql|postgresql|gis|geocoding|postgis
52,148
<p>If you are interested in a thorough comparison, I recommend <a href="http://www.bostongis.com/PrinterFriendly.aspx?content_name=sqlserver2008_postgis_mysql_compare" rel="noreferrer">"Cross Compare SQL Server 2008 Spatial, PostgreSQL/PostGIS 1.3-1.4, MySQL 5-6"</a> and/or <a href="http://www.bostongis.com/PrinterFriendly.aspx?content_name=sqlserver2008r2_oracle11gr2_postgis15_compare" rel="noreferrer">"Compare SQL Server 2008 R2, Oracle 11G R2, PostgreSQL/PostGIS 1.5 Spatial Features"</a> by Boston GIS.</p> <p>Considering your points:</p> <ul> <li><strong>I'm familiar with the DBMS:</strong> setting up a PostGIS database on Windows is easy, using PgAdmin3 management is straight-forward too</li> <li><strong>It does well with GIS queries:</strong> PostGIS is definitely strongest of the three, only Oracle Spatial would be comparable but is disqualified if you consider its costs</li> <li><strong>Low cost:</strong> +1 for PostGIS for sure</li> <li><strong>Not antagonistic with Microsoft .NET Framework:</strong> You should at least be able to connect via ODBC (<a href="http://wiki.postgresql.org/wiki/Using_Microsoft_.NET_with_the_PostgreSQL_Database_Server_via_ODBC" rel="noreferrer">see Postgres wiki</a>)</li> <li><strong>Compatible with R:</strong> shouldn't be a problem with any of the three</li> </ul>
3,521,715
Call a Python method by name
<p>If I have an object and a method name in a string, how can I call the method?</p> <pre><code>class Foo: def bar1(self): print 1 def bar2(self): print 2 def callMethod(o, name): ??? f = Foo() callMethod(f, "bar1") </code></pre>
3,521,742
5
2
null
2010-08-19 12:26:28.13 UTC
13
2020-02-27 18:05:13.637 UTC
2010-08-19 12:33:58.47 UTC
null
14,443
null
14,443
null
1
95
python
77,993
<p>Use the built-in <a href="https://docs.python.org/library/functions.html#getattr" rel="noreferrer"><code>getattr()</code></a> function:</p> <pre><code>class Foo: def bar1(self): print(1) def bar2(self): print(2) def call_method(o, name): return getattr(o, name)() f = Foo() call_method(f, "bar1") # prints 1 </code></pre> <p>You can also use <a href="https://docs.python.org/library/functions.html#setattr" rel="noreferrer"><code>setattr()</code></a> for setting class attributes by names.</p>
3,370,271
A migration to add unique constraint to a combination of columns
<p>What I need is a migration to apply unique constraint to a combination of columns. i.e. for a <code>people</code> table, a combination of <code>first_name</code>, <code>last_Name</code> and <code>Dob</code> should be unique.</p>
3,370,333
6
1
null
2010-07-30 09:36:38.68 UTC
32
2022-02-05 17:55:12.907 UTC
2018-02-01 00:41:16.25 UTC
null
2,202,702
null
111,489
null
1
164
ruby-on-rails|database
88,644
<p><code>add_index :people, [:firstname, :lastname, :dob], unique: true</code></p>
3,809,108
How to remove empty paragraph tags from string?
<p>I ran into a slight coding problem with WordPress template. This is the code I use in template:</p> <pre><code>&lt;?php echo teaser(40); ?&gt; </code></pre> <p>In my functions, I use this to strip tags and get content from allowed tags only.</p> <pre><code>&lt;?php function teaser($limit) { $content = explode(' ', get_the_content(), $limit); if (count($content)&gt;=$limit) { array_pop($content); $content = implode(" ",$content).'...'; } else { $content = implode(" ",$content); } $content = preg_replace('/\[.+\]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]&gt;', ']]&amp;gt;', $content); $content = strip_tags($content, '&lt;p&gt;&lt;a&gt;&lt;ul&gt;&lt;li&gt;&lt;i&gt;&lt;em&gt;&lt;strong&gt;'); return $content; } ?&gt; </code></pre> <p>The problem: I use the above code to strip tags from the content, but WordPress already puts image tags within paragraph. So the result is empty paragraph tags where images are stripped. </p> <p>Just for the sake of cleaning up my code and useless empty tags. My question is how to remove empty paragraph tags?</p> <pre><code>&lt;p&gt;&lt;/p&gt; </code></pre> <p>Thanks a lot in advance! :)</p>
3,809,121
7
0
null
2010-09-28 01:40:21.107 UTC
11
2020-04-14 08:50:57.567 UTC
null
null
null
null
77,762
null
1
32
php
64,215
<p>use this regex to remove empty paragraph</p> <pre><code>/&lt;p[^&gt;]*&gt;&lt;\\/p[^&gt;]*&gt;/ </code></pre> <p>example</p> <pre><code>&lt;?php $html = "abc&lt;p&gt;&lt;/p&gt;&lt;p&gt;dd&lt;/p&gt;&lt;b&gt;non-empty&lt;/b&gt;"; $pattern = "/&lt;p[^&gt;]*&gt;&lt;\\/p[^&gt;]*&gt;/"; //$pattern = "/&lt;[^\/&gt;]*&gt;([\s]?)*&lt;\/[^&gt;]*&gt;/"; use this pattern to remove any empty tag echo preg_replace($pattern, '', $html); // output //abc&lt;p&gt;dd&lt;/p&gt;&lt;b&gt;non-empty&lt;/b&gt; ?&gt; </code></pre>
3,703,071
How to hook into the Power button in Android?
<p>On an Android device, where the only buttons are the volume buttons and a power button, I want to make the app react to presses on the power button (long and short). How is this done?</p>
3,715,514
9
1
null
2010-09-13 17:58:49.76 UTC
37
2021-01-05 06:27:09.013 UTC
2010-09-15 07:15:39.803 UTC
null
1,507,543
null
1,507,543
null
1
33
android
82,259
<p>Solution:</p> <pre><code>@Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) { Intent i = new Intent(this, ActivitySetupMenu.class); startActivity(i); return true; } return super.dispatchKeyEvent(event); } </code></pre>
3,772,486
How to fix "Root element is missing." when doing a Visual Studio (VS) Build?
<p>How to fix "Root element is missing." when doing a Visual Studio (VS) Build?</p> <p>Any idea what file I should look at in my solution?</p> <p>Actually, I am getting this error message inside of "Visual Build Pro" when using using the "Make VS 2008" command. This command works just fine when building other solutions (like about 20) and I am not really sure why mine is getting the error. </p> <p>Any help would be very much appreciated. :) </p> <p>I am using VS 2008 and Visual Build Pro 6.7.</p>
3,772,540
32
1
null
2010-09-22 18:29:39.923 UTC
11
2021-11-18 10:12:20.74 UTC
2014-03-29 07:22:15.71 UTC
null
-1
null
4,964
null
1
73
visual-studio-2010|visual-studio|visual-studio-2008|visual-build-professional
282,316
<p>Make sure any XML file (or any file that would be interpreted as an XML file by visual studio) has a correct XML structure - that is, one root element (with any name, I have use <code>rootElement</code> in my example):</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;rootElement&gt; ... &lt;/rootElement&gt; </code></pre>