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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,042,002 | PHP printed boolean value is empty, why? | <p>I am new to PHP. I am implementing a script and I am puzzled by the following:</p>
<pre><code>$local_rate_filename = $_SERVER['DOCUMENT_ROOT']."/ghjr324l.txt";
$local_rates_file_exists = file_exists($local_rate_filename);
echo $local_rates_file_exists."<br>";
</code></pre>
<p>This piece of code displays an empty string, rather than 0 or 1 (or true or false). Why? Documentation seems to indicate that a boolean value is always 0 or 1. What is the logic behind this?</p> | 9,042,016 | 4 | 2 | null | 2012-01-28 00:50:42.217 UTC | 7 | 2021-06-17 07:49:30.74 UTC | 2012-01-28 01:04:27.77 UTC | null | 520,957 | null | 520,957 | null | 1 | 43 | php|boolean|echo | 30,074 | <p>Be careful when you convert back and forth with boolean, <a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.casting" rel="nofollow noreferrer">the manual says</a>:</p>
<blockquote>
<p>A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.</p>
</blockquote>
<p>So you need to do a:</p>
<pre><code>echo (int)$local_rates_file_exists."<br>";
</code></pre> |
9,180,547 | Force a push with SourceTree | <p>I started using SourceTree a few days ago to manage Mercurial repositories with my Mac. Now I ran into the problem when pushing to my remote repository creates a new head on a new branch and I would like to force it.</p>
<p>However, I am not able to find any specific option in SourceTree which allows me to set the force option for a push. Is it just my inability to find it or is there no possibility to set it?</p>
<p>Thanks in advance
Michael</p> | 11,854,406 | 6 | 2 | null | 2012-02-07 17:05:37.077 UTC | 3 | 2020-02-19 07:03:49.353 UTC | 2013-09-30 15:56:59.397 UTC | null | 1,956,010 | null | 694,584 | null | 1 | 48 | mercurial|atlassian-sourcetree | 31,689 | <p>SourceTree is finally going to add force push:
<a href="https://jira.atlassian.com/browse/SRCTREE-1156" rel="noreferrer">https://jira.atlassian.com/browse/SRCTREE-1156</a></p>
<p>Reason:
<a href="https://answers.atlassian.com/questions/54469/how-do-i-perform-a-forced-push-push-f-from-sourcetree" rel="noreferrer">https://answers.atlassian.com/questions/54469/how-do-i-perform-a-forced-push-push-f-from-sourcetree</a></p>
<p>Edit:
It is now added in SourceTree, but you need to turn the option on in the settings.</p> |
16,323,676 | Referencing a composite primary key | <p>I have two tables, with each table having a composite primary key.</p>
<p>One attribute is in both composite primary keys.</p>
<p>How am i supposed to reference the common attribute?? Do i just reference it as a FK in both tables as below? The cust_id and flight_id below are each part of the composite key as well and reference primary keys in other tables. (Ignore the third attribute in the erd for the br_flight table as I choose to use a composite key in the end). </p>
<pre><code>CREATE TABLE BOOKING_REFERENCE (
REFERENCE_ID NVARCHAR(10) NOT NULL,
CUST_ID NUMBER(10)NOT NULL,
STATUS NVARCHAR (1), NOT NULL,
PRIMARY KEY(REFERENCE_ID, CUST_ID),
FOREIGN KEY(REFERENCE_ID) REFERENCES BR_FLIGHT(REFERENCE_ID):
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(CUST_ID);
CREATE TABLE BR_FLIGHT (
REFERENCE_ID NVARCHAR(10) NOT NULL ,
FLIGHT_ID NVARCHAR (10) NOT NULL,
PRIMARY KEY(REFERENCE_ID, FLIGHT_ID),
FOREIGN KEY (REFERENCE_ID) REFERENCES BOOKING_REFERENCE(REFERENCE_ID)
FOREIGN KEY (FLIGHT_ID) REFERENCES FLIGHT(FLIGHT_ID)
);
</code></pre>
<p><img src="https://i.stack.imgur.com/DH9NE.jpg" alt="enter image description here"></p>
<p>Would the above sql work??
Thanks in advance and apologies for the shoddy diagram:)</p> | 16,323,777 | 3 | 1 | null | 2013-05-01 18:01:14.837 UTC | 5 | 2021-09-15 09:00:20.333 UTC | null | null | null | null | 2,205,209 | null | 1 | 16 | sql|oracle|foreign-keys|primary-key|composite-primary-key | 51,708 | <p>Foreign keys have to match the primary/unique key they reference column for column. Since the primary key of <code>BOOKING_REFERENCE</code> is (<code>REFERENCE_ID</code>, <code>CUST_ID</code>), that means that the foreign key from <code>BR_FLIGHT</code> to <code>BOOKING_REFERENCE</code> must consist of 2 columns also. That means you need to add <code>CUST_ID</code> to the <code>BR_FLIGHT</code> table - either that or your <code>BOOKING_REFERENCE</code> primary key is wrong and should just be (<code>REFERENCE_ID</code>).</p>
<p>That said, it doesn't make sense to have foreign keys defined in both directions as you do. The "child" table should reference the "parent" and not vice versa.</p> |
16,327,846 | Bootstrap 3 compatible with current AngularJS bootstrap directives? | <p><strong>Will bootstrap 3 release be compatible with current AngularJS bootstrap directives?</strong></p>
<p>I want to use Bootstrap 2.3.1 directive with AngularJS:</p>
<p><a href="http://angular-ui.github.io/bootstrap/">http://angular-ui.github.io/bootstrap/</a></p>
<p>With the Bootstrap 3.0.0 CSS:</p>
<p><a href="https://github.com/twitter/bootstrap/tree/3.0.0-wip/">https://github.com/twitter/bootstrap/tree/3.0.0-wip/</a></p>
<p><em>Why?</em> </p>
<p>AngularJS team is still working on JS directives for v2.3.1 and will need time to catch up to v3.0.0. I want to start using v3 CSS grid syntax now.</p>
<p><a href="https://github.com/angular-ui/bootstrap/issues/331">https://github.com/angular-ui/bootstrap/issues/331</a></p> | 16,343,834 | 3 | 0 | null | 2013-05-01 23:05:03.493 UTC | 21 | 2014-02-14 14:21:12.323 UTC | 2014-02-11 07:27:30.503 UTC | null | 79,485 | null | 1,113,921 | null | 1 | 55 | javascript|css|twitter-bootstrap|angularjs|twitter-bootstrap-3 | 64,397 | <p>So, the <a href="http://angular-ui.github.io/bootstrap/" rel="noreferrer">http://angular-ui.github.io/bootstrap/</a> project <strong><em>does not</em></strong> depend on Bootstrap's JavaScript (it is not wrapping it, not requiring etc.). Those are native AngularJS directives written from the ground-up to be lightweight and well integrated into the AngularJS ecosystem.</p>
<p><strong>The only adherence to the Bootstrap project is Bootstrap's markup (HTML) and CSS.</strong></p>
<p>If you ask a question "can I grab all the directives and use them with Bootstrap 3.0" the answer is "it depends". It really depends if and how much Bootstrap 3.0 decide do change its markup and corresponding CSS classes. I would presume that markup of some controls have changed and not for some others.</p>
<p>Now, the very good news with <a href="http://angular-ui.github.io/bootstrap/" rel="noreferrer">http://angular-ui.github.io/bootstrap/</a> is that most of the HTML markup and CSS classes are encapsulated in separate AngularJS templates. In practice it means that you can grab the JavaScript code of the directives and only change markup (templates) to fit into Bootstrap 3.0.</p>
<p>All the templates are located here:
<a href="https://github.com/angular-ui/bootstrap/tree/master/template" rel="noreferrer">https://github.com/angular-ui/bootstrap/tree/master/template</a>
and by browsing them you should get an idea that it is pretty simple to update markup without messing with JavaScript. This is one of the design goals of this project.</p>
<p>I would encourage you to simply give it a try and see how CSS of Bootstrap 3.0 works with the existing directives and templates. If you spot any issues you can always update templates to Bootstrap 3.0 (and contribute them back to the project!)</p> |
16,362,407 | NSAttributedString background color and rounded corners | <p>I have a question regarding rounded corners and text background color for a custom <code>UIView</code>.</p>
<p>Basically, I need to achieve an effect like this (image attached - notice the rounded corners on one side) in a custom UIView:
<img src="https://i.stack.imgur.com/BxJq5.png" alt="Background highlight"></p>
<p>I'm thinking the approach to use is:</p>
<ul>
<li>Use Core Text to get glyph runs.</li>
<li>Check highlight range.</li>
<li>If the current run is within the highlight range, draw a background rectangle with rounded corners and desired fill color before drawing the glyph run.</li>
<li>Draw the glyph run.</li>
</ul>
<p>However, I'm not sure whether this is the only solution (or for that matter, whether this is the most efficient solution).</p>
<p>Using a <code>UIWebView</code> is not an option, so I have to do it in a custom <code>UIView</code>.</p>
<p>My question being, is this the best approach to use, and am I on the right track? Or am I missing out something important or going about it the wrong way?</p> | 16,423,399 | 4 | 3 | null | 2013-05-03 15:23:43.39 UTC | 77 | 2022-06-28 18:19:22.88 UTC | 2017-12-01 08:57:01.823 UTC | null | 3,885,376 | null | 931,031 | null | 1 | 73 | ios|objective-c|uiview|quartz-graphics|nsattributedstring | 29,000 | <p><strong>TL;DR;</strong> Create a custom-view, which renders same old <code>NSAttributedString</code>, but with rounded-corners.</p>
<blockquote>
<p>Unlike Android's <code>SpannableString</code>, iOS does not support "custom-render for custom-string-attributes", at least not without an entire custom-view (at time of writing, 2022).</p>
</blockquote>
<hr />
<p>I managed to achieve the above effect, so thought I'd post an answer for the same.</p>
<p>If anyone has any suggestions about making this more effective, please feel free to contribute. I'll be sure to mark your answer as the correct one. :)</p>
<p>For doing this, you'll need to add a "custom attribute" to <code>NSAttributedString</code>.</p>
<p>Basically, what that means is that you can add any key-value pair, as long as it is something that you can add to an <code>NSDictionary</code> instance. If the system does not recognize that attribute, it does nothing. It is up to you, as the developer, to provide a custom implementation and behavior for that attribute.</p>
<p>For the purposes of this answer, let us assume I've added a custom attribute called: <code>@"MyRoundedBackgroundColor"</code> with a value of <code>[UIColor greenColor]</code>.</p>
<p>For the steps that follow, you'll need to have a basic understanding of how <code>CoreText</code> gets stuff done. Check out <a href="https://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Overview/Overview.html#//apple_ref/doc/uid/TP40005533-CH3-SW13" rel="nofollow noreferrer">Apple's Core Text Programming Guide</a> for understanding what's a frame/line/glyph run/glyph, etc.</p>
<p>So, here are the steps:</p>
<ol>
<li>Create a custom UIView subclass.</li>
<li>Have a property for accepting an <code>NSAttributedString</code>.</li>
<li>Create a <code>CTFramesetter</code> using that <code>NSAttributedString</code> instance.</li>
<li>Override the <code>drawRect:</code> method</li>
<li>Create a <code>CTFrame</code> instance from the <code>CTFramesetter</code>.</li>
<li>You will need to give a <code>CGPathRef</code> to create the <code>CTFrame</code>. Make that <code>CGPath</code> to be the same as the frame in which you wish to draw the text.</li>
<li>Get the current graphics context and flip the text coordinate system.</li>
<li>Using <code>CTFrameGetLines(...)</code>, get all the lines in the <code>CTFrame</code> you just created.</li>
<li>Using <code>CTFrameGetLineOrigins(...)</code>, get all the line origins for the <code>CTFrame</code>.</li>
<li>Start a <code>for loop</code> - for each line in the array of <code>CTLine</code>...</li>
<li>Set the text position to the start of the <code>CTLine</code> using <code>CGContextSetTextPosition(...)</code>.</li>
<li>Using <code>CTLineGetGlyphRuns(...)</code> get all the Glyph Runs (<code>CTRunRef</code>) from the <code>CTLine</code>.</li>
<li>Start another <code>for loop</code> - for each glyphRun in the array of <code>CTRun</code>...</li>
<li>Get the range of the run using <code>CTRunGetStringRange(...)</code>.</li>
<li>Get typographic bounds using <code>CTRunGetTypographicBounds(...)</code>.</li>
<li>Get the x offset for the run using <code>CTLineGetOffsetForStringIndex(...)</code>.</li>
<li>Calculate the bounding rect (let's call it <code>runBounds</code>) using the values returned from the aforementioned functions.</li>
<li>Remember - <code>CTRunGetTypographicBounds(...)</code> requires pointers to variables to store the "ascent" and "descent" of the text. You need to add those to get the run height.</li>
<li>Get the attributes for the run using <code>CTRunGetAttributes(...)</code>.</li>
<li>Check if the attribute dictionary contains your attribute.</li>
<li>If your attribute exists, calculate the bounds of the rectangle that needs to be painted.</li>
<li>Core text has the line origins at the baseline. We need to draw from the lowermost point of the text to the topmost point. Thus, we need to adjust for descent.</li>
<li>So, subtract the descent from the bounding rect that we calculated in step 16 (<code>runBounds</code>).</li>
<li>Now that we have the <code>runBounds</code>, we know what area we want to paint - now we can use any of the <code>CoreGraphis</code>/<code>UIBezierPath</code> methods to draw and fill a rect with specific rounded corners.</li>
<li><code>UIBezierPath</code> has a convenience class method called <code>bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:</code> that let's you round specific corners. You specify the corners using bit masks in the 2nd parameter.</li>
<li>Now that you've filled the rect, simply draw the glyph run using <code>CTRunDraw(...)</code>.</li>
<li>Celebrate victory for having created your custom attribute - drink a beer or something! :D</li>
</ol>
<p>Regarding detecting that the attribute range extends over multiple runs, you can get the entire effective range of your custom attribute when the 1st run encounters the attribute. If you find that the length of the maximum effective range of your attribute is greater than the length of your run, you need to paint sharp corners on the right side (for a left to right script). More math will let you detect the highlight corner style for the next line as well. :)</p>
<p>Attached is a screenshot of the effect. The box on the top is a standard <code>UITextView</code>, for which I've set the attributedText. The box on the bottom is the one that has been implemented using the above steps. The same attributed string has been set for both the textViews.
<img src="https://i.stack.imgur.com/XJY5s.png" alt="custom attribute with rounded corners" /></p>
<p>Again, if there is a better approach than the one that I've used, please do let me know! :D</p>
<p>Hope this helps the community. :)</p>
<p>Cheers!</p> |
41,736,460 | EXCEPTION: This browser is not supported or 3rd party cookies and data may be disabled | <p>This error occurs when our users "Block third-party cookies and site data". </p>
<p>To replicate the error, go to:</p>
<ol>
<li>Check your Chrome browser "Block third-party cookies and site data" <a href="https://medium.com/@jek.bao.choo/deeptent-troubleshoot-faq-9dbfa468ad88#.7k6hib9lm" rel="noreferrer">reference in this guide</a></li>
<li>Go to <a href="http://www.deeptent.com" rel="noreferrer">https://www.deeptent.com</a></li>
<li>Click SIGN IN</li>
<li>Next you will see a blank screen. And if you open up the browser developer console you will see this error:</li>
</ol>
<blockquote>
<p>We always advise our users to Uncheck the blocking of third-party cookies and site data; however, some users still prefer to block it. </p>
</blockquote>
<ol>
<li><p>One can still sign in to their Gmail with this blocked. Interestingly, why can't our users sign in using the Firebase-Google OAuth provided with their third party cookies & site data blocked?</p></li>
<li><p>We are built with Angular2 and Firebase. Is there no way that the users can still authenticate with third-party cookies and site data blocked?</p></li>
</ol> | 48,816,737 | 6 | 9 | null | 2017-01-19 07:50:00.703 UTC | 8 | 2022-07-21 18:59:02.773 UTC | 2017-01-19 08:07:56.883 UTC | null | 4,625,829 | null | 3,073,280 | null | 1 | 24 | firebase|firebase-authentication|angularfire2 | 11,612 | <p>The domain you're using is deeptent.com, but the domain that firebase is authenticating against and setting cookies from is your .firebaseapp.com domain. So, yes, the cookies are considered third-party. The firebase folks really should take a harder look at how they are connecting custom domains in the firebase hosting setup. Also, see here:
<a href="https://stackoverflow.com/questions/48757757/use-google-firebase-authentication-without-3rd-party-cookies">Use Google Firebase Authentication without 3rd Party Cookies</a></p> |
60,510,150 | Flutter: There should be exactly one item with [DropdownButton]'s value | <p>I am trying to create a <strong>dropdown button</strong> in Flutter. I am getting a <strong>List from my database</strong> then I pass the list to my <code>dropdownButton</code> <strong>everything works</strong> the data is shown as intended but <strong>when I choose an element from it</strong> I get this error:</p>
<pre><code>There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
</code></pre>
<p>I tried setting <strong>DropdownButton value to null</strong> it works but then I <strong>can't see the chosen element</strong>.</p>
<p>Here is my code:</p>
<pre><code>FutureBuilder<List<Tag>>(
future: _tagDatabaseHelper.getTagList(),
builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
Container(
margin: EdgeInsets.symmetric(
horizontal: MediaQuery.of(context).size.width * 0.07),
child: Theme(
data: ThemeData(canvasColor: Color(0xFF525A71)),
child: DropdownButton<Tag>(
value: _selectedTag,
isExpanded: true,
icon: Icon(
Icons.arrow_drop_down,
size: 24,
),
hint: Text(
"Select tags",
style: TextStyle(color: Color(0xFF9F9F9F)),
),
onChanged: (value) {
setState(() {
_selectedTag = value;
});
},
items: snapshot.data.map((Tag tag) {
return DropdownMenuItem<Tag>(
value: tag,
child: Text(
tag.tagTitle,
style: TextStyle(color: Colors.white),
),
);
}).toList(),
value: _selectedTag,
),
),
),
</code></pre>
<p>I used <strong>futureBuilder</strong> to <strong>get my List from database</strong>.</p> | 61,425,939 | 19 | 3 | null | 2020-03-03 15:06:59.25 UTC | 7 | 2022-09-13 20:22:05.03 UTC | 2020-10-24 09:35:21.21 UTC | user10563627 | null | null | 12,242,170 | null | 1 | 54 | flutter|dart|drop-down-menu|dropdownbutton|flutter-futurebuilder | 52,564 | <p>Well, since no problem has an exact same solution. I was facing the same issue with my code. Here is How I fixed this.</p>
<p>CODE of my DropdownButton:</p>
<pre><code>DropdownButton(
items: _salutations
.map((String item) =>
DropdownMenuItem<String>(child: Text(item), value: item))
.toList(),
onChanged: (String value) {
setState(() {
print("previous ${this._salutation}");
print("selected $value");
this._salutation = value;
});
},
value: _salutation,
),
</code></pre>
<p><strong>The Error</strong><br></p>
<p>In the code snippet below, I am setting the state for a selection value, which is of type String. Now problem with my code was the default initialization of this selection value.
Initially, I was initializing the variable <code>_salutation</code> as:</p>
<pre><code>String _salutation = ""; //Notice the empty String.
</code></pre>
<p><strong>This was a mistake!</strong></p>
<p><em>Initial selection should not be null or empty as the error message correctly mentioned.</em></p>
<blockquote>
<p>'items == null || items.isEmpty || value == null ||</p>
</blockquote>
<p>And hence the crash:</p>
<p><a href="https://i.stack.imgur.com/8ny32.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8ny32.png" alt="crash_message"></a></p>
<p><strong>Solution</strong><br> Initialize the value object with some default value. <strong>Please note</strong> that the <strong>value should be the one of the values contained by your collection.</strong> If it is not, then expect a crash.</p>
<pre><code> String _salutation = "Mr."; //This is the selection value. It is also present in my array.
final _salutations = ["Mr.", "Mrs.", "Master", "Mistress"];//This is the array for dropdown
</code></pre> |
15,404,535 | How to git reset --hard a subdirectory | <blockquote>
<p><strong>UPDATE²</strong>: With Git 2.23 (August 2019), there's a new command <code>git restore</code> that does this, see the <a href="https://stackoverflow.com/a/15404733/946850">accepted answer</a>.</p>
</blockquote>
<blockquote>
<p><strong>UPDATE</strong>: This will work more intuitively as of Git 1.8.3, see <a href="https://stackoverflow.com/a/16589534/946850">my own answer</a>.</p>
</blockquote>
<p>Imagine the following use case: I want to get rid of all changes in a specific subdirectory of my Git working tree, leaving all other subdirectories intact.</p>
<ul>
<li><p>I can do <code>git checkout .</code> , but <a href="https://stackoverflow.com/questions/15251638/git-checkout-adds-directories-excluded-by-sparse-checkout">git checkout . adds directories excluded by sparse checkout</a></p>
</li>
<li><p>There is <code>git reset --hard</code>, but it won't let me do it for a subdirectory:</p>
<pre><code> > git reset --hard .
fatal: Cannot do hard reset with paths.
</code></pre>
<p>Again: <a href="https://stackoverflow.com/questions/11200839/why-git-cant-do-hard-soft-resets-by-path">Why git can't do hard/soft resets by path?</a></p>
</li>
<li><p>I can reverse-patch the current state using <code>git diff subdir | patch -p1 -R</code>, but this is a rather weird way of doing this.</p>
</li>
</ul>
<p>What is the proper Git command for this operation?</p>
<p>The script below illustrates the problem. Insert the proper command below the <code>How to make files</code> comment -- the current command will restore the file <code>a/c/ac</code> which is supposed to be excluded by the sparse checkout. Note that I <em>do not</em> want to explicitly restore <code>a/a</code> and <code>a/b</code>, I only "know" <code>a</code> and want to restore everything below. <strong>EDIT</strong>: And I also don't "know" <code>b</code>, or which other directories reside on the same level as <code>a</code>.</p>
<pre><code>#!/bin/sh
rm -rf repo; git init repo; cd repo
for f in a b; do
for g in a b c; do
mkdir -p $f/$g
touch $f/$g/$f$g
git add $f/$g
git commit -m "added $f/$g"
done
done
git config core.sparsecheckout true
echo a/a > .git/info/sparse-checkout
echo a/b >> .git/info/sparse-checkout
echo b/a >> .git/info/sparse-checkout
git read-tree -m -u HEAD
echo "After read-tree:"
find * -type f
rm a/a/aa
rm a/b/ab
echo >> b/a/ba
echo "After modifying:"
find * -type f
git status
# How to make files a/* reappear without changing b and without recreating a/c?
git checkout -- a
echo "After checkout:"
git status
find * -type f
</code></pre> | 15,404,733 | 10 | 10 | null | 2013-03-14 08:40:35.827 UTC | 47 | 2022-06-30 10:45:53.677 UTC | 2022-06-05 13:29:43.537 UTC | null | 63,550 | null | 946,850 | null | 1 | 262 | git|reset|git-reset|sparse-checkout | 213,358 | <p>With Git 2.23 (August 2019), you have the <a href="https://stackoverflow.com/a/57066072/6309">new command <code>git restore</code></a> (also <a href="https://stackoverflow.com/a/58003889/6309">presented here</a>)</p>
<pre><code>git restore --source=HEAD --staged --worktree -- aDirectory
# or, shorter
git restore -s@ -SW -- aDirectory
</code></pre>
<p>That would replace both the index and working tree with <code>HEAD</code> content, like an <code>reset --hard</code> would, but for a specific path.</p>
<hr />
<p>Original answer (2013)</p>
<p>Note (as <a href="https://stackoverflow.com/questions/11200839/why-git-cant-do-hard-soft-resets-by-path#comment17212802_11200860">commented</a> by <a href="https://stackoverflow.com/users/54829/dan-fabulich">Dan Fabulich</a>) that:</p>
<ul>
<li><code>git checkout -- <path></code> doesn't do a hard reset: it replaces the working tree contents with the staged contents.</li>
<li><code>git checkout HEAD -- <path></code> does a hard reset for a path, replacing both the index and the working tree with the version from the <code>HEAD</code> commit.</li>
</ul>
<p>As <a href="https://stackoverflow.com/a/27988725/6309">answered</a> by <a href="https://stackoverflow.com/users/1157054/ajedi32">Ajedi32</a>, both checkout forms <strong>don't remove files which were deleted in the target revision</strong>.<br />
If you have extra files in the working tree which don't exist in HEAD, a <code>git checkout HEAD -- <path></code> won't remove them.</p>
<p>Note: With <a href="https://stackoverflow.com/a/55083251/6309"><code>git checkout --overlay HEAD -- <path></code> (Git 2.22, Q1 2019)</a>, files that appear in the index and working tree, but not in <code><tree-ish></code> are removed, to make them match <code><tree-ish></code> exactly.</p>
<p>But that checkout can respect a <code>git update-index --skip-worktree</code> (for those directories you want to ignore), as mentioned in "<a href="https://stackoverflow.com/questions/11148579/why-do-excluded-files-keep-reappearing-in-my-git-sparse-checkout">Why do excluded files keep reappearing in my git sparse checkout?</a>".</p> |
17,584,515 | How to enable a disabled button by clicking on another button? | <p>I have two buttons:</p>
<pre><code><button onclick=initialize() id="1" data-role="button" data-mini="true" data-corners="false" data-theme="b">Show My Position</button>
<button onclick=calcRoute() id="2" data-role="button" data-mini="true" data-corners="false" data-theme="b">Evacuate !</button>
</code></pre>
<p>I want to have the second button disabled by default, and have it enabled if clicking on the first button. How do I accomplish this?</p> | 17,584,555 | 1 | 0 | null | 2013-07-11 03:22:04.737 UTC | 1 | 2013-07-11 04:25:45.67 UTC | 2013-07-11 04:24:33.807 UTC | null | 1,530,814 | null | 2,565,280 | null | 1 | 5 | html|button|ibm-mobilefirst | 55,312 | <p>Please see the following answers to questions: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/5875025/disable-buttons-in-jquery-mobile">Disable Buttons in jQuery Mobile</a></li>
<li><a href="https://stackoverflow.com/questions/3014649/how-to-disable-html-button-using-javascript">How to disable html button using JavaScript?</a></li>
</ul>
<p>The simplest approach would be (just a pure example w/out taking into consideration browsers, etc):</p>
<pre><code><html>
<head>
<script>
function enableButton2() {
document.getElementById("button2").disabled = false;
}
</script>
</head>
<body>
<input type="button" id="button1" value="button 1" onclick="enableButton2()" />
<input type="button" id="button2" value="button 2" disabled />
</body>
</html>
</code></pre> |
17,292,087 | Limiting date range in HTML 5 | <p>I have a input field with type date </p>
<pre><code><input type="date" id="datepick" name="mybirthday" placeholder="Birthdate(MM/DD/YYYY)" />
</code></pre>
<p>Here I want to limit the date range that the user can choose. To be more specific, I dont want the user to choose a birthdate like 22/08/2015. How can I do this?</p> | 17,292,152 | 2 | 2 | null | 2013-06-25 07:59:09.013 UTC | 4 | 2016-06-13 16:36:36.117 UTC | null | null | null | null | 1,960,527 | null | 1 | 16 | javascript|jquery|html | 47,376 | <p>Use the <code>min</code> and <code>max</code> attributes:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Enter a date before 1989-10-30:</label>
<input type="date" name="myDate" max="1989-10-29">
<label>Enter a date after 2001-01-01:</label>
<input type="date" name="myDate" min="2001-01-02"></code></pre>
</div>
</div>
</p> |
24,601,722 | How can I use functools.singledispatch with instance methods? | <p>Python 3.4 <a href="https://docs.python.org/3/library/functools.html#functools.singledispatch">added</a> the ability to define function overloading with static methods. This is essentially the example from the documentation:</p>
<pre><code>from functools import singledispatch
class TestClass(object):
@singledispatch
def test_method(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
@test_method.register(int)
def _(arg):
print("Strength in numbers, eh?", end=" ")
print(arg)
@test_method.register(list)
def _(arg):
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
if __name__ == '__main__':
TestClass.test_method(55555)
TestClass.test_method([33, 22, 11])
</code></pre>
<p>In its purest form, the <code>singledispatch</code> implementation relies on the first argument to identify type, therefore making it tricky to extend this functionality to instance methods. </p>
<p>Does anyone have any advice for how to use (or jerry-rig) this functionality to get it to work with instance methods?</p> | 24,602,374 | 2 | 8 | null | 2014-07-07 00:50:41.383 UTC | 22 | 2019-11-22 19:06:46.92 UTC | 2014-07-07 02:54:47.66 UTC | null | 1,014,938 | null | 706,421 | null | 1 | 53 | python|python-3.x|python-3.4|instance-method|single-dispatch | 22,279 | <blockquote>
<p><strong>Update:</strong> As of Python 3.8, <a href="https://docs.python.org/3/library/functools.html#functools.singledispatchmethod" rel="noreferrer"><code>functools.singledispatchmethod</code></a> allows single dispatch on methods, classmethods, abstractmethods,
and staticmethods. </p>
<p>For older Python versions, see the rest of this answer.</p>
</blockquote>
<p>Looking at the <a href="http://hg.python.org/cpython/file/f6f691ff27b9/Lib/functools.py#l706" rel="noreferrer">source</a> for <code>singledispatch</code>, we can see that the decorator returns a function <code>wrapper()</code>, which selects a function to call from those registered based on the type of <code>args[0]</code> ...</p>
<pre><code> def wrapper(*args, **kw):
return dispatch(args[0].__class__)(*args, **kw)
</code></pre>
<p>... which is fine for a regular function, but not much use for an instance method, whose first argument is always going to be <code>self</code>.</p>
<p>We can, however, write a new decorator <code>methdispatch</code>, which relies on <code>singledispatch</code> to do the heavy lifting, but instead returns a wrapper function that selects which registered function to call based on the type of <code>args[1]</code>:</p>
<pre><code>from functools import singledispatch, update_wrapper
def methdispatch(func):
dispatcher = singledispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
update_wrapper(wrapper, func)
return wrapper
</code></pre>
<p>Here's a simple example of the decorator in use:</p>
<pre><code>class Patchwork(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
@methdispatch
def get(self, arg):
return getattr(self, arg, None)
@get.register(list)
def _(self, arg):
return [self.get(x) for x in arg]
</code></pre>
<p>Notice that both the decorated <code>get()</code> method and the method registered to <code>list</code> have an initial <code>self</code> argument as usual.</p>
<p>Testing the <code>Patchwork</code> class:</p>
<pre><code>>>> pw = Patchwork(a=1, b=2, c=3)
>>> pw.get("b")
2
>>> pw.get(["a", "c"])
[1, 3]
</code></pre> |
22,317,329 | Defining a function that returns a slice of variable size in golang | <p>I would like to build a function that returns a slice of any size. I know I can do</p>
<pre><code>func BuildSlice() [100]int { return [100]int{} }
</code></pre>
<p>but I would like to be able to return slices of different sizes from the same function. Something like:</p>
<pre><code>func BuildSlice(int size) [...]int { return [size]int{} }
</code></pre>
<p>I've tried the above as well as</p>
<pre><code>func BuildSlice(size int) []int { return [size]int{} }
</code></pre>
<p>Please point me in the right direction.</p> | 22,318,864 | 2 | 3 | null | 2014-03-11 05:42:02.587 UTC | 2 | 2022-08-24 19:26:11.987 UTC | 2022-08-24 19:26:11.987 UTC | null | 5,446,749 | null | 441,935 | null | 1 | 24 | arrays|function|go | 74,188 | <p>First of all, slices are already of "variable size": <code>[100]int</code> and <code>[...]int</code> are array type definitions.</p>
<p><code>[]int</code> is the correct syntax for a slice, and you could implement the function as:</p>
<pre><code>func BuildSlice(size int) []int {
return make([]int, size)
}
</code></pre>
<p>This will return a slice of zero values with the desired size, similar to what your array version does.</p> |
37,307,307 | Remove a row from a data table in R | <p>I have a data table with 5778 rows and 28 columns. How do I delete ALL of the 1st row. E.g. let's say the data table had 3 rows and 4 columns and looked like this:</p>
<pre><code>Row number tracking_id 3D71 3D72 3D73
1 xxx 1 1 1
2 yyy 2 2 2
3 zzz 3 3 3
</code></pre>
<p>I want to create a data table that looks like this:</p>
<pre><code> Row number tracking_id 3D71 3D72 3D73
1 yyy 2 2 2
2 zzz 3 3 3
</code></pre>
<p>i.e. I want to delete all of row number 1 and then shift the other rows up. </p>
<p>I have tried <code>datatablename[-c(1)]</code> but this deletes the first column not the first row!</p>
<p>Many thanks for any help!</p> | 37,307,371 | 2 | 4 | null | 2016-05-18 18:18:24.76 UTC | 3 | 2018-04-06 10:51:21.327 UTC | 2016-05-18 18:30:30.173 UTC | null | 2,204,410 | null | 6,352,547 | null | 1 | 5 | r | 63,082 | <p>You can do this via</p>
<pre><code>dataframename = dataframename[-1,]
</code></pre> |
27,158,840 | docker: executable file not found in $PATH | <p>I have a docker image which installs <code>grunt</code>, but when I try to run it, I get an error: </p>
<pre><code>Error response from daemon: Cannot start container foo_1: \
exec: "grunt serve": executable file not found in $PATH
</code></pre>
<p>If I run bash in interactive mode, <code>grunt</code> is available.</p>
<p>What am I doing wrong?</p>
<p>Here is my Dockerfile:</p>
<pre><code># https://registry.hub.docker.com/u/dockerfile/nodejs/ (builds on ubuntu:14.04)
FROM dockerfile/nodejs
MAINTAINER My Name, [email protected]
ENV HOME /home/web
WORKDIR /home/web/site
RUN useradd web -d /home/web -s /bin/bash -m
RUN npm install -g grunt-cli
RUN npm install -g bower
RUN chown -R web:web /home/web
USER web
RUN git clone https://github.com/repo/site /home/web/site
RUN npm install
RUN bower install --config.interactive=false --allow-root
ENV NODE_ENV development
# Port 9000 for server
# Port 35729 for livereload
EXPOSE 9000 35729
CMD ["grunt"]
</code></pre> | 27,615,958 | 13 | 7 | null | 2014-11-26 21:03:44.26 UTC | 51 | 2022-03-17 11:58:07.623 UTC | 2014-11-26 21:18:01.34 UTC | null | 955,273 | null | 955,273 | null | 1 | 321 | docker | 540,171 | <p>When you use the exec format for a command (e.g., <code>CMD ["grunt"]</code>, a JSON array with double quotes), it will be executed <em>without</em> a shell. This means that most environment variables will not be present.</p>
<p>If you specify your command as a regular string (e.g. <code>CMD grunt</code>) then the string after <code>CMD</code> will be executed with <code>/bin/sh -c</code>.</p>
<p>More info on this is available in the CMD section of the <a href="https://docs.docker.com/engine/reference/builder/#/cmd" rel="noreferrer">Dockerfile reference</a>.</p> |
39,489,168 | How to scrape real time streaming data with Python? | <p>I was trying to scrape the number of flights for this webpage <a href="https://www.flightradar24.com/56.16,-49.51" rel="noreferrer">https://www.flightradar24.com/56.16,-49.51</a></p>
<p>The number is highlighted in the picture below:
<a href="https://i.stack.imgur.com/Zvsmf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zvsmf.png" alt="enter image description here"></a></p>
<p>The number is updated every 8 seconds.</p>
<p>This is what I tried with BeautifulSoup:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import time
r=requests.get("https://www.flightradar24.com/56.16,-49.51")
c=r.content
soup=BeautifulSoup(c,"html.parser")
value=soup.find_all("span",{"class":"choiceValue"})
print(value)
</code></pre>
<p>But that always returns 0:</p>
<pre><code>[<span class="choiceValue" id="menuPlanesValue">0</span>]
</code></pre>
<p>View source also shows 0, so I understand why BeautifulSoup returns 0 too.</p>
<p>Anyone know any other method to get the current value?</p> | 39,489,328 | 3 | 9 | null | 2016-09-14 11:22:10.023 UTC | 12 | 2017-06-24 11:49:13.533 UTC | null | null | null | null | 1,585,017 | null | 1 | 6 | python|web-scraping|beautifulsoup | 25,337 | <p>The problem with your approach is that the page first loads a view, then performs regular requests to refresh the page. If you look at the network tab in the developer console in Chrome (for example), you'll see the requests to <a href="https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=59.09,52.64,-58.77,-47.71&faa=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=7200&gliders=1&stats=1" rel="nofollow noreferrer">https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=59.09,52.64,-58.77,-47.71&faa=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=7200&gliders=1&stats=1</a></p>
<p>The response is regular json:</p>
<pre><code>{
"full_count": 11879,
"version": 4,
"afefdca": [
"A86AB5",
56.4288,
-56.0721,
233,
38000,
420,
"0000",
"T-F5M",
"B763",
"N641UA",
1473852497,
"LHR",
"ORD",
"UA929",
0,
0,
"UAL929",
0
],
...
"aff19d9": [
"A12F78",
56.3235,
-49.3597,
251,
36000,
436,
"0000",
"F-EST",
"B752",
"N176AA",
1473852497,
"DUB",
"JFK",
"AA291",
0,
0,
"AAL291",
0
],
"stats": {
"total": {
"ads-b": 8521,
"mlat": 2045,
"faa": 598,
"flarm": 152,
"estimated": 464
},
"visible": {
"ads-b": 0,
"mlat": 0,
"faa": 6,
"flarm": 0,
"estimated": 3
}
}
}
</code></pre>
<p>I'm not sure if this API is protected in any way, but it seems like I can access it without any issues using curl.</p>
<p>More info:</p>
<ul>
<li><a href="https://aviation.stackexchange.com/questions/3052/is-there-an-api-to-get-real-time-faa-flight-data">aviation.stackexchange - Is there an API to get real-time FAA flight data?</a></li>
<li><a href="http://forum.flightradar24.com/threads/24-API-access/page3" rel="nofollow noreferrer">Flightradar24 Forum - API access</a> (meaning your use case is probably discouraged)</li>
</ul> |
17,461,237 | How do I get the directory of the PowerShell script I execute? | <p>I run a PowerShell script. How do I get the directory path of this script I run?</p>
<p>How to do this?</p> | 17,461,595 | 1 | 5 | null | 2013-07-04 03:05:54.187 UTC | 7 | 2017-04-13 20:47:58.49 UTC | 2015-07-11 22:43:19.797 UTC | null | 63,550 | null | 2,131,116 | null | 1 | 62 | powershell | 147,059 | <p>PowerShell 3 has the <code>$PSScriptRoot</code> <a href="http://technet.microsoft.com/en-us/library/hh847768.aspx" rel="noreferrer">automatic variable</a>:</p>
<blockquote>
<p>Contains the directory from which a script is being run. </p>
<p>In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.</p>
</blockquote>
<p>Don't be fooled by the poor wording. <code>PSScriptRoot</code> is the directory of the current file. </p>
<p>In PowerShell 2, you can calculate the value of <code>$PSScriptRoot</code> yourself:</p>
<pre><code># PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
</code></pre> |
17,522,286 | Is there a way to get all values in NSUserDefaults? | <p>I would like to print all values I saved via <code>NSUserDefaults</code> without supplying a specific Key. </p>
<p>Something like printing all values in an array using <code>for</code> loop. Is there a way to do so?</p> | 17,522,419 | 4 | 3 | null | 2013-07-08 08:41:41.62 UTC | 9 | 2017-08-31 22:43:19.157 UTC | 2013-07-08 08:49:38.853 UTC | null | 767,730 | null | 2,352,449 | null | 1 | 86 | iphone|ios|objective-c|ios6|nsuserdefaults | 48,646 | <p><strong>Objective C</strong></p>
<p>all values:</p>
<pre><code>NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);
</code></pre>
<p>all keys: </p>
<pre><code>NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
</code></pre>
<p>all keys and values: </p>
<pre><code>NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
</code></pre>
<p>using for:</p>
<pre><code>NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
for(NSString* key in keys){
// your code here
NSLog(@"value: %@ forKey: %@",[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}
</code></pre>
<p><strong>Swift</strong></p>
<p>all values: </p>
<pre><code>print(UserDefaults.standard.dictionaryRepresentation().values)
</code></pre>
<p>all keys:</p>
<pre><code>print(UserDefaults.standard.dictionaryRepresentation().keys)
</code></pre>
<p>all keys and values:</p>
<pre><code>print(UserDefaults.standard.dictionaryRepresentation())
</code></pre> |
26,024,906 | 'Unable to create description in descriptionForLayoutAttribute_layoutItem_coefficient. Something is nil' | <p>First, I got 3 different UIViews to replace the detail view in Split View Controller on iPad storyboard</p>
<p>It runs on well on iOS8 iPad. But when I load one of the detail views, the app crashes when running in iOS7 and iOS 6 Simulator.</p>
<p>I only assume it is because of Auto layout on my Storyboard.</p>
<p>Does anyone know how to fix it?</p>
<pre><code>2014-09-25 04:15:19.705 PSTappsperance[48327:60b] Pad AppDelegate ########
2014-09-25 04:15:27.869 PSTappsperance[48327:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to create description in descriptionForLayoutAttribute_layoutItem_coefficient. Something is nil'
*** First throw call stack:
(
0 CoreFoundation 0x0000000110a5c495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001107af99e objc_exception_throw + 43
2 CoreFoundation 0x0000000110a5c2ad +[NSException raise:format:] + 205
3 Foundation 0x00000001104ec548 descriptionForLayoutAttribute_layoutItem_coefficient + 145
4 Foundation 0x00000001104ec3bc -[NSLayoutConstraint equationDescription] + 216
5 Foundation 0x00000001104ec831 -[NSLayoutConstraint description] + 297
6 CoreFoundation 0x0000000110a1d1b9 -[NSArray descriptionWithLocale:indent:] + 345
7 Foundation 0x000000011037e14e _NSDescriptionWithLocaleFunc + 64
8 CoreFoundation 0x00000001109e1244 __CFStringAppendFormatCore + 7252
9 CoreFoundation 0x0000000110a1f913 _CFStringCreateWithFormatAndArgumentsAux + 115
10 CoreFoundation 0x0000000110a7fa5b _CFLogvEx + 123
11 Foundation 0x00000001103ae276 NSLogv + 79
12 Foundation 0x00000001103ae20a NSLog + 148
13 UIKit 0x000000010f927097 -[UIView(UIConstraintBasedLayout_EngineDelegate) engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:] + 62
14 Foundation 0x00000001104e32ac -[NSISEngine handleUnsatisfiableRowWithHead:body:usingInfeasibilityHandlingBehavior:mutuallyExclusiveConstraints:] + 521
15 Foundation 0x00000001104e49b1 -[NSISEngine tryUsingArtificialVariableToAddConstraintWithMarker:rowBody:usingInfeasibilityHandlingBehavior:mutuallyExclusiveConstraints:] + 353
16 Foundation 0x000000011039c26b -[NSISEngine tryToAddConstraintWithMarker:expression:integralizationAdjustment:mutuallyExclusiveConstraints:] + 663
17 Foundation 0x00000001104ed180 -[NSLayoutConstraint _addLoweredExpression:toEngine:integralizationAdjustment:lastLoweredConstantWasRounded:mutuallyExclusiveConstraints:] + 275
18 Foundation 0x00000001103981b0 -[NSLayoutConstraint _addToEngine:integralizationAdjustment:mutuallyExclusiveConstraints:] + 204
19 UIKit 0x000000010f923f41 __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke_2 + 413
20 Foundation 0x00000001104e529a -[NSISEngine withBehaviors:performModifications:] + 119
21 UIKit 0x000000010f923d7d __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke + 401
22 UIKit 0x000000010f923bc3 -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 197
23 UIKit 0x000000010f923e57 __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke_2 + 179
24 Foundation 0x00000001104e529a -[NSISEngine withBehaviors:performModifications:] + 119
25 UIKit 0x000000010f923d7d __57-[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:]_block_invoke + 401
26 UIKit 0x000000010f923bc3 -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 197
27 UIKit 0x000000010f3ab975 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 95
28 Foundation 0x00000001104e529a -[NSISEngine withBehaviors:performModifications:] + 119
29 UIKit 0x000000010f3ab889 -[UIView(Hierarchy) _postMovedFromSuperview:] + 321
30 UIKit 0x000000010f3b52ac -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1508
31 UIKit 0x000000010f632778 -[UINavigationTransitionView transition:fromView:toView:] + 454
32 UIKit 0x000000010f6325b0 -[UINavigationTransitionView transition:toView:] + 25
33 UIKit 0x000000010f46f4d7 -[UINavigationController _startTransition:fromViewController:toViewController:] + 2893
34 UIKit 0x000000010f46f787 -[UINavigationController _startDeferredTransitionIfNeeded:] + 547
35 UIKit 0x000000010f470238 -[UINavigationController __viewWillLayoutSubviews] + 43
36 UIKit 0x000000010f58a895 -[UILayoutContainerView layoutSubviews] + 202
37 UIKit 0x000000010f3b7993 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 354
38 QuartzCore 0x000000011427c802 -[CALayer layoutSublayers] + 151
39 QuartzCore 0x0000000114271369 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 363
40 QuartzCore 0x00000001142711ea _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
41 QuartzCore 0x00000001141e4fb8 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 252
42 QuartzCore 0x00000001141e6030 _ZN2CA11Transaction6commitEv + 394
43 QuartzCore 0x00000001141e669d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
44 CoreFoundation 0x0000000110a27dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
45 CoreFoundation 0x0000000110a27d37 __CFRunLoopDoObservers + 391
46 CoreFoundation 0x0000000110a07522 __CFRunLoopRun + 946
47 CoreFoundation 0x0000000110a06d83 CFRunLoopRunSpecific + 467
48 GraphicsServices 0x0000000112dbdf04 GSEventRunModal + 161
49 UIKit 0x000000010f357e33 UIApplicationMain + 1010
50 PSTappsperance 0x000000010f092653 main + 115
51 libdyld.dylib 0x00000001114b05fd start + 1
52 ??? 0x0000000000000001 0x0 + 1
)libc++abi.dylib: terminating with uncaught exception of type NSException
</code></pre> | 26,045,383 | 3 | 2 | null | 2014-09-24 19:26:52.147 UTC | 8 | 2015-09-15 14:58:04.543 UTC | null | null | null | null | 3,732,297 | null | 1 | 31 | ios|objective-c|xcode|autolayout | 13,428 | <p>Solved.
It was because of Auto Layout constraints. </p>
<p>There were Labels that did not know to determine its width.</p>
<p>But why only works on iOS 8?
I pinned two constraints to determine the width in Xcode 6</p>
<pre><code>Trailing Space to: superview
Leading Space to: superview
</code></pre>
<p>when pinning constraints, there is an option 'Constraint to Margin', which is checked by default in Xcode 6. And Older versions does not support that.</p> |
26,421,274 | CSS Circular Cropping of Rectangle Image | <p>I want to make a centered circular image from rectangle photo.
The photo's dimensions is unknown. Usually it's a rectangle form.
I've tried a lot of methods:</p>
<p><strong>Code</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image-cropper {
max-width: 100px;
height: auto;
position: relative;
overflow: hidden;
}
.image-cropper img{
display: block;
margin: 0 auto;
height: auto;
width: 150%;
margin: 0 0 0 -20%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-cropper">
<img src="https://sf1.autojournal.fr/wp-content/uploads/autojournal/2012/07/4503003e3c38bc818d635f5a52330d.jpg" class="rounded" />
</div></code></pre>
</div>
</div>
</p> | 26,421,723 | 11 | 3 | null | 2014-10-17 08:47:29.5 UTC | 25 | 2022-05-04 09:10:15.82 UTC | 2021-02-26 16:42:19.44 UTC | null | 11,044,542 | null | 2,876,433 | null | 1 | 91 | html|css | 167,996 | <p>The approach is wrong, you need to apply the <code>border-radius</code> to the container <code>div</code> instead of the actual image.</p>
<p>This would work:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image-cropper {
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
border-radius: 50%;
}
img {
display: inline;
margin: 0 auto;
height: 100%;
width: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-cropper">
<img src="https://via.placeholder.com/150" class="rounded" />
</div></code></pre>
</div>
</div>
</p> |
9,664,231 | ORA-01855: AM/A.M. or PM/P.M. required | <p>I get the error: <code>ORA-01855: AM/A.M. or PM/P.M. required</code></p>
<p>when I try to execute following query. </p>
<pre><code> INSERT INTO TBL(ID,START_DATE)
values (123, TO_DATE ('3/13/2012 9:22:00 AM', 'MM/DD/YYYY HH:MI AM'))
</code></pre>
<p>Where my <code>START_DATE</code> column is of type "Date".</p>
<p>I have executed following query and it gave no errors, still not success yet in above issue: </p>
<pre><code>ALTER SESSION SET NLS_DATE_FORMAT = "MM/DD/YYYY HH:MI AM";
</code></pre> | 9,664,462 | 2 | 2 | null | 2012-03-12 09:08:54.593 UTC | null | 2018-09-23 09:25:09.837 UTC | 2012-03-12 09:17:40.953 UTC | null | 370,116 | null | 370,116 | null | 1 | 3 | oracle|date|oracle10g|nls-lang | 52,011 | <p>Your format mask must match the format of the string you are converting. So you would either want to add <code>SS</code> to the format mask or remove the seconds from the string</p>
<pre><code>INSERT INTO TBL(ID,START_DATE)
values (123, TO_DATE ('3/13/2012 9:22:00 AM', 'MM/DD/YYYY HH:MI:SS AM'))
</code></pre>
<p>or</p>
<pre><code>INSERT INTO TBL(ID,START_DATE)
values (123, TO_DATE ('3/13/2012 9:22 AM', 'MM/DD/YYYY HH:MI:SS AM'))
</code></pre>
<p>If you want to accept a string that contains seconds but you don't want to store the seconds in the database (in which case Oracle will always store 0 for the seconds), you can use the <code>TRUNC</code> function</p>
<pre><code>INSERT INTO TBL(ID,START_DATE)
values (123, TRUNC( TO_DATE ('3/13/2012 9:22:00 AM', 'MM/DD/YYYY HH:MI:SS AM'), 'MI') )
</code></pre> |
22,972,073 | Toast notifications in ASP.NET MVC | <p>I'm using the Toastr notification plugin in my MVC application to display status messages (successful edit, update, delete, etc), and I'm wondering if there is an easy way to put some logic in a Partial view and have it on my Layout or in each individual view where needed.</p>
<h2>Partial</h2>
<pre><code><script type="text/javascript">
$(document).ready(function () {
@if (ViewBag.Success == true) {
@:toastr.success("@ViewBag.Message");
} else if (ViewBag.Success == false) {
@:toastr.error("@ViewBag.Message");
}
});
</script>
</code></pre>
<h2>View</h2>
<pre><code>//Doesn't work
@Html.Partial("_ToastPartial")
//Tried this directly in the view instead of using the partial, didn't work
@if (ViewBag.Success == true) {
@:toastr.success("@ViewBag.Message");
} else if (ViewBag.Success == false) {
@:toastr.error("@ViewBag.Message");
}
</code></pre>
<h2>Controller</h2>
<pre><code> public ActionResult SomethingAwesome(MyViewModel model)
{
ViewBag.Success = true;
ViewBag.Message = "Employee successfully added";
return RedirectToAction("Index");
}
</code></pre>
<p>This doesn't work. Is it possible to wrap something like this in a partial or does MVC strip out the <code><script></code> tags? Can I render the partial within a script block on the View?</p>
<p>I even tried to move the code within the script tags directly to the View and then setting the values on the Controller and it seems like nothing is happening.</p>
<p>Any help? Is the ViewBag cleared by the time the view is rendered again? Should I use TempData? Can I move a <code>Success</code> and <code>Message</code> property into my ViewModel and just pass that into my View like this?</p>
<pre><code>public ActionResult Index(MyViewModel model)
{
//Do something with model.Success
}
</code></pre>
<h2>My Solution</h2>
<p>I used a couple of answers to come to a final conclusion for this section of my site, and will most likely use the method for the accepted answer in other parts.</p>
<p>I went and added the following to my ViewModel </p>
<pre><code>public bool Success { get; set; }
public string Message { get; set; }
</code></pre>
<p>I have the Action return the Index view with the ViewModel, after properties have all been set </p>
<pre><code>//fetch the updated data and shove into ViewModel here
viewModel.Success = true;
viewModel.Message = "Employee successfully checked in";
return View("Index", viewModel);
</code></pre>
<p>And then just use the Razor syntax in my View</p>
<pre><code>@if (Model.Success) {
@:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
@:toastr.error("@Model.Message");
}
</code></pre>
<p>Also as a bonus (although implementation seems sloppy), render the Partial in my document.Ready block </p>
<pre><code>@Html.Partial("_ToastPartial", Model)
</code></pre>
<p>and move the Toastr notification code to the partial</p>
<pre><code>@if (Model.Success) {
@:toastr.success("@Model.Message");
} else if (!Model.Success && !String.IsNullOrWhiteSpace(Model.Message)) {
@:toastr.error("@Model.Message");
}
</code></pre>
<p>Most likely I would set up an interface with the <code>Message</code> and <code>Success</code> properties and make any ViewModels that will use the partial implement that interface</p> | 22,972,535 | 3 | 8 | null | 2014-04-09 19:21:22.793 UTC | 11 | 2017-02-25 23:00:07.303 UTC | 2014-04-10 12:06:15.353 UTC | null | 1,313,465 | null | 1,313,465 | null | 1 | 8 | c#|javascript|asp.net|asp.net-mvc | 24,711 | <p>Your controller is performing a <code>RedirectToAction</code>. The ViewBag and ViewData only survives the current request. TempData is the thing to use when you use redirects (and only then): </p>
<p><a href="http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications" rel="noreferrer">http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications</a> states this clearly:</p>
<blockquote>
<p>[...] the TempData object works well in one basic scenario:</p>
<ul>
<li>Passing data between the current and next HTTP requests</li>
</ul>
</blockquote> |
5,196,290 | How can I override the @Html.LabelFor template? | <p>I have a simple field form</p>
<pre><code><div class="field fade-label">
@Html.LabelFor(model => model.Register.UserName)
@Html.TextBoxFor(model => model.Register.UserName)
</div>
</code></pre>
<p>and this results in:</p>
<pre><code><div class="field fade-label">
<label for="Register_UserName">Username (used to identify all services, from 4 to 30 chars)</label>
<input type="text" value="" name="Register.UserName" id="Register_UserName">
</div>
</code></pre>
<p>but I want that <code>LabelFor</code> code append a <code><span></code> inside so I can end up having:</p>
<pre><code><label for="Register_UserName">
<span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>
</code></pre>
<p><strong>How can I do this?</strong></p>
<p>All <a href="http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/">examples</a> use <code>EditorTemplates</code> but this is a <code>LabelFor</code>.</p> | 5,196,392 | 3 | 5 | null | 2011-03-04 16:08:47.97 UTC | 20 | 2014-05-10 17:20:24.7 UTC | 2012-02-27 17:56:05.503 UTC | null | 28,004 | null | 28,004 | null | 1 | 70 | asp.net-mvc|templates|asp.net-mvc-3 | 40,352 | <p>You'd do this by creating your own HTML helper.</p>
<p><a href="http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs" rel="noreferrer">http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs</a></p>
<p>You can view the code for LabelFor<> by downloading the source for ASP.Net MVC and modify that as a custom helper.</p>
<hr>
<p><strong>Answer</strong> added by <a href="https://stackoverflow.com/users/28004/balexandre">balexandre</a></p>
<pre><code>public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
TagBuilder span = new TagBuilder("span");
span.SetInnerText(labelText);
// assign <span> to <label> inner html
tag.InnerHtml = span.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
</code></pre> |
5,127,407 | How to implement a confirmation (yes/no) DialogPreference? | <p>How can I implement a Preference that displays a simple yes/no confirmation dialog?</p>
<p>For an example, see <code>Browser->Setting->Clear Cache</code>.</p> | 5,127,506 | 3 | 0 | null | 2011-02-26 14:23:29.42 UTC | 23 | 2015-04-16 19:39:52.857 UTC | 2013-04-11 18:50:42.283 UTC | user1131435 | null | null | 199,556 | null | 1 | 116 | android|android-preferences|confirmation|dialog-preference | 126,174 | <p>That is a simple <a href="http://developer.android.com/guide/topics/ui/dialogs.html">alert dialog</a>, Federico gave you a site where you can look things up.</p>
<p>Here is a short example of how an alert dialog can be built.</p>
<pre><code>new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton(android.R.string.no, null).show();
</code></pre> |
9,038,522 | Regular Expression for any number greater than 0? | <p>I'm looking for a way to check if a number is greater than 0 using regex.</p>
<p>For example:</p>
<ul>
<li><code>12</code> would return true</li>
<li><code>0</code> would return false.</li>
</ul> | 9,038,554 | 14 | 3 | null | 2012-01-27 18:53:48.023 UTC | 19 | 2021-12-10 10:10:03.01 UTC | 2019-12-22 11:01:58.007 UTC | null | 372,239 | null | 537,172 | null | 1 | 88 | regex | 199,248 | <p>I don't know how MVC is relevant, but if your ID is an integer, this BRE should do:</p>
<pre><code> ^[1-9][0-9]*$
</code></pre>
<p>If you want to match real numbers (floats) rather than integers, you need to handle the case above, along with normal decimal numbers (i.e. <code>2.5</code> or <code>3.3̅</code>), cases where your pattern is between 0 and 1 (i.e. <code>0.25</code>), as well as case where your pattern has a decimal part that is 0. (i.e. <code>2.0</code>). And while we're at it, we'll add support for leading zeros on integers (i.e. <code>005</code>):</p>
<pre><code> ^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$
</code></pre>
<p>Note that this second one is an Extended RE. The same thing can be expressed in Basic RE, but almost everything understands ERE these days. Let's break the expression down into parts that are easier to digest.</p>
<pre><code> ^(
</code></pre>
<p>The caret matches the null at the beginning of the line, so preceding your regex with a caret anchors it to the beginning of the line. The opening parenthesis is there because of the or-bar, below. More on that later.</p>
<pre><code> 0*[1-9][0-9]*(\.[0-9]+)?
</code></pre>
<p>This matches any integer <em>or</em> any floating point number above 1. So our <code>2.0</code> would be matched, but <code>0.25</code> would not. The <code>0*</code> at the start handles leading zeros, so <code>005 == 5</code>.</p>
<pre><code> |
</code></pre>
<p>The pipe character is an "<em>or-bar</em>" in this context. For purposes of evaluation of this expression, It has higher precedence than everything else, and effectively joins two regular expressions together. Parentheses are used to group multiple expressions separated by or-bars.</p>
<p>And the second part:</p>
<pre><code> 0+\.[0-9]*[1-9][0-9]*
</code></pre>
<p>This matches any number that starts with one or more <code>0</code> characters (replace <code>+</code> with <code>*</code> to match zero or more zeros, i.e. <code>.25</code>), followed by a period, followed by a string of digits that includes at least one that is not a <code>0</code>. So this matches everything above <code>0</code> and below <code>1</code>.</p>
<pre><code> )$
</code></pre>
<p>And finally, we close the parentheses and anchor the regex to the end of the line with the dollar sign, just as the caret anchors to the beginning of the line.</p>
<p>Of course, if you let your programming language evaluate something numerically rather than try to match it against a regular expression, you'll save headaches <em>and</em> CPU.</p> |
9,246,536 | warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data -- C++ | <p>I made a simple program that allows the user to pick a number of dice then guess the outcome... I posted this code before but with the wrong question so it was deleted... now I cannot have any errors or even warnings on this code but for some reason this warning keeps popping and I have no clue how to fix it...
<strong>"warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data"</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>
using namespace std;
int choice, dice, random;
int main(){
string decision;
srand ( time(NULL) );
while(decision != "no" || decision != "No")
{
std::cout << "how many dice would you like to use? ";
std::cin >> dice;
std::cout << "guess what number was thrown: ";
std::cin >> choice;
for(int i=0; i<dice;i++){
random = rand() % 6 + 1;
}
if( choice == random){
std::cout << "Congratulations, you got it right! \n";
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
} else{
std::cout << "Sorry, the number was " << random << "... better luck next time \n" ;
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
}
}
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
</code></pre>
<p>This is what I am trying to figure out, why am I getting this warning:
warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data</p> | 9,246,559 | 4 | 5 | null | 2012-02-12 04:55:16.423 UTC | 10 | 2014-03-31 14:24:34.36 UTC | null | null | null | null | 1,058,846 | null | 1 | 30 | c++ | 67,971 | <p>That's because on your system, <code>time_t</code> is a larger integer type than <code>unsigned int</code>.</p>
<ul>
<li><code>time()</code> returns a <code>time_t</code> which is probably a 64-bit integer.</li>
<li><code>srand()</code> wants an <code>unsigned int</code> which is probably a 32-bit integer.</li>
</ul>
<p>Hence you get the warning. You can silence it with a cast:</p>
<pre><code>srand ( (unsigned int)time(NULL) );
</code></pre>
<p>In this case, the downcast (and potential data loss) doesn't matter since you're only using it to seed the RNG.</p> |
9,150,370 | select the TOP N rows from a table | <p>I am making some paging, and I need to make some query and get the result form defined slicing .
for example: I need to get all "top" rows in range 20n < x < 40n etc.</p>
<pre><code>SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
</code></pre>
<p>and now I need to make my sliding by column called ID .</p>
<p>Any suggestions how to so ? I need to run my query on mysql, mssql, and oracle.</p> | 9,150,494 | 5 | 5 | null | 2012-02-05 15:17:45.367 UTC | 12 | 2020-07-06 14:11:50.417 UTC | 2012-02-05 15:43:39.273 UTC | null | 135,152 | null | 140,100 | null | 1 | 40 | mysql|sql|sql-server|oracle | 159,091 | <p>Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:</p>
<p>SQL Server, Oracle:</p>
<pre><code>SELECT * -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, *
FROM Reflow
WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40
</code></pre>
<p>MySQL:</p>
<pre><code>SELECT *
FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20
</code></pre> |
9,316,023 | Python 2.7: Print to File | <p>Why does trying to print directly to a file instead of <code>sys.stdout</code> produce the following syntax error:</p>
<pre><code>Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
File "<stdin>", line 1
print('This is a test', file=f1)
^
SyntaxError: invalid syntax
</code></pre>
<p>From help(__builtins__) I have the following info:</p>
<pre><code>print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
</code></pre>
<p>So what would be the right syntax to change the standard stream print writes to?</p>
<p>I know that there are different maybe better ways to write to file but I really don't get why this should be a syntax error...</p>
<p>A nice explanation would be appreciated!</p> | 9,316,160 | 6 | 5 | null | 2012-02-16 17:28:37.54 UTC | 20 | 2018-10-03 22:10:42.963 UTC | 2015-07-06 17:49:20.953 UTC | null | 733,092 | null | 1,214,396 | null | 1 | 100 | python|file|python-2.7 | 324,334 | <p>If you want to use the <code>print</code> function in Python 2, you have to import from <code>__future__</code>:</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>But you can have the same effect without using the function, too:</p>
<pre><code>print >>f1, 'This is a test'
</code></pre> |
18,572,092 | How specify a list value as variable in ansible inventory file? | <p>I need something like (ansible inventory file):</p>
<pre><code>[example]
127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL"
</code></pre>
<p>However, ansible does not recognize 'locales' as a list. </p> | 29,174,946 | 7 | 0 | null | 2013-09-02 11:24:48.253 UTC | 12 | 2022-09-21 13:24:15.2 UTC | 2014-09-16 09:45:52.79 UTC | null | 926,639 | null | 868,941 | null | 1 | 56 | list|variables|ansible|inventory | 93,089 | <p>You can pass a list or object like this: </p>
<pre><code>[example]
127.0.0.1 timezone="Europe/Amsterdam" locales='["en_US", "nl_NL"]'
</code></pre> |
18,755,967 | How to make a program that finds id's of xinput devices and sets xinput some settings | <p>I have a G700 mouse connected to my computer. The problem with this mouse in Linux (Ubuntu) is that the sensitivity is very high. I also don't like mouse acceleration, so I've made a script that turns this off. The script looks like this</p>
<pre><code>#!/bin/bash
# This script removes mouse acceleration, and lowers pointer speed
# Suitable for gaming mice, I use the Logitech G700.
# More info: http://www.x.org/wiki/Development/Documentation/PointerAcceleration/
xinput set-prop 11 'Device Accel Profile' -1
xinput set-prop 11 'Device Accel Constant Deceleration' 2.5
xinput set-prop 11 'Device Accel Velocity Scaling' 1.0
xinput set-prop 12 'Device Accel Profile' -1
xinput set-prop 12 'Device Accel Constant Deceleration' 2.5
xinput set-prop 12 'Device Accel Velocity Scaling' 1.0
</code></pre>
<p>Another problem with the G700 mouse is that it shows up as two different devices in xinput. This is most likely because the mouse has a wireless adapter, and is usually also connected via a usb cable (for charging). This is my output from <code>xinput --list</code> (see id 11 and 12):</p>
<pre><code>$ xinput --list
⎡ Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
⎜ ↳ Logitech USB Receiver id=8 [slave pointer (2)]
⎜ ↳ Logitech USB Receiver id=9 [slave pointer (2)]
⎜ ↳ Logitech Unifying Device. Wireless PID:4003 id=10 [slave pointer (2)]
⎜ ↳ Logitech G700 Laser Mouse id=11 [slave pointer (2)]
⎜ ↳ Logitech G700 Laser Mouse id=12 [slave pointer (2)]
⎣ Virtual core keyboard id=3 [master keyboard (2)]
↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)]
↳ Power Button id=6 [slave keyboard (3)]
↳ Power Button id=7 [slave keyboard (3)]
</code></pre>
<p>This isn't usually a problem, since the id's are usually the same. But sometimes the id's of the mouse change, and that's where my question comes in.</p>
<p>What's the simplest way of writing a script/program that finds the id that belongs to the two listings named <code>Logitech G700 Laser Mouse</code> in the output from <code>xinput --list</code>, and then running the commands in the top script using those two ids?</p> | 18,756,948 | 7 | 3 | null | 2013-09-12 05:25:44.107 UTC | 11 | 2021-07-20 15:36:30.703 UTC | null | null | null | null | 1,850,917 | null | 1 | 27 | shell|xinput | 27,299 | <p>You can do something like the following.</p>
<pre><code>if [ "$SEARCH" = "" ]; then
exit 1
fi
ids=$(xinput --list | awk -v search="$SEARCH" \
'$0 ~ search {match($0, /id=[0-9]+/);\
if (RSTART) \
print substr($0, RSTART+3, RLENGTH-3)\
}'\
)
for i in $ids
do
xinput set-prop $i 'Device Accel Profile' -1
xinput set-prop $i 'Device Accel Constant Deceleration' 2.5
xinput set-prop $i 'Device Accel Velocity Scaling' 1.0
done
</code></pre>
<p>So with this you first find all the IDs which match the search pattern <code>$SEARCH</code> and store them in <code>$ids</code>.
Then you loop over the IDs and execute the three <code>xinput</code> commands.</p>
<p>You should make sure that <code>$SEARCH</code> does not match to much, since this could result in undesired behavior.</p> |
18,593,746 | How to bulk change MySQL Triggers DEFINER | <p>I've been working on our internal development server and creating MySQL Triggers on our MySQL 5.6.13 server. The problem I now have is the Triggers (around 200 in total) were created with as DEFINER=<code>root</code>@<code>%</code> on the internal server.</p>
<p>Now I want to move to the live production server. However on our live server we don't allow this access for user root. Therefore how can I bulk change all my Triggers, so that it reads DEFINER=<code>root</code>@<code>localhost</code></p> | 18,596,425 | 8 | 0 | null | 2013-09-03 13:35:09.127 UTC | 11 | 2020-03-17 02:20:16.12 UTC | null | null | null | null | 1,979,729 | null | 1 | 24 | mysql|triggers | 37,965 | <p>One way to do it:</p>
<p>1) Dump trigger definitions into a file</p>
<pre class="lang-none prettyprint-override"><code># mysqldump -uroot -p --triggers --add-drop-trigger --no-create-info \
--no-data --no-create-db --skip-opt test > /tmp/triggers.sql
</code></pre>
<p>2) Open <code>triggers.sql</code> file in your favorite editor and use <code>Find and Replace</code> feature to change <code>DEFINER</code>s. Save updated file.</p>
<p>3) Recreate triggers from the file</p>
<pre class="lang-none prettyprint-override"><code># mysql < triggers.sql
</code></pre> |
18,718,996 | Format DateTime in Kendo UI Grid using asp.net MVC Wrapper | <p>I want to build a Kendo UI Grid with format date dd//MM/yyyy. However, all questions that I found about this, it were resolved with code <strong>Format("{0:d}");</strong>. So, I have tried like a code below:</p>
<pre><code>GridBoundColumnBuilder<TModel> builder = par.Bound(field.Name);
switch (field.Type.Type)
{
case CType.Boolean:
builder = builder.ClientTemplate(string.Format("<input type='checkbox' #= {0} ? checked='checked' : '' # disabled='disabled' ></input>", field.Name));
break;
case CType.Datetime:
builder = builder.Format("{0:d}");
break;
case CType.Decimal:
case CType.Double:
builder = builder.Format("{0:0.00}");
break;
}
</code></pre>
<p>Another formats is works fine, just DateTime do not works. </p>
<p>I had this result for Datetime = /Date(1377020142000)/</p> | 18,719,324 | 8 | 2 | null | 2013-09-10 12:28:34.927 UTC | 8 | 2019-06-03 08:47:22.04 UTC | null | null | null | null | 2,764,847 | null | 1 | 38 | c#|asp.net-mvc-4|datetime|kendo-grid|kendo-asp.net-mvc | 71,887 | <p>If you want to display datetime format in kendo grid then do this,</p>
<pre><code>.Format("{0:dd/MM/yyyy}")
</code></pre>
<p>Or </p>
<pre><code>builder.ToString("dd/MM/yyyy");
</code></pre> |
20,041,051 | How to judge a string is UUID type? | <p>In my project, I use <code>UUID.fromString()</code> to convert string to <code>UUID</code>, but if the string is not <code>UUID</code> type, it will throw <code>exception</code>, so how can I validate this string?</p> | 20,044,013 | 2 | 3 | null | 2013-11-18 05:56:00.64 UTC | 7 | 2022-02-14 17:44:43.94 UTC | null | null | null | null | 2,284,670 | null | 1 | 58 | java | 119,895 | <p>You should use regex to verify it e.g.:</p>
<pre><code>^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$
</code></pre>
<p>test it with e.g.g <code>01234567-9ABC-DEF0-1234-56789ABCDEF0</code></p>
<p>or with brackets</p>
<pre><code>^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?$
</code></pre> |
15,253,548 | Filtering a list of objects with a certain attribute | <pre><code>class Object
{
public int ID {get; set;}
public string description {get; set;}
}
</code></pre>
<p>If I have a <code>List<Object> Objects</code> populated with various objects, and I want to find objects whose description is something particular, how would I do that?</p>
<pre><code>find every Object in Objects whose description == "test"
</code></pre> | 15,253,570 | 3 | 0 | null | 2013-03-06 17:04:14.517 UTC | null | 2013-03-06 17:16:36.993 UTC | null | null | null | null | 1,413,866 | null | 1 | 18 | c# | 45,269 | <p>You can use LINQ:</p>
<pre><code>var results = Objects.Where(o => o.Description == "test");
</code></pre>
<hr>
<p>On a side note, realize that <code>Object</code> is a very poor choice of names for a class, and won't even compile as-is... I'd recommend choosing more appropriate names, and following standard capitalization conventions for C#. </p> |
15,090,752 | How to include 10" and 7" layouts properly | <p>Nexus 7: 7" 1280x800</p>
<p>Galaxy tab 10.1 10" 1280x800</p>
<p>I want my app to run on 7 and 10 inch tablets. As far as I know, I have to include these layout folders in my app:</p>
<p>for 7 inch tablets</p>
<ul>
<li>layout-sw600dp </li>
<li>layout-sw600dp-port</li>
</ul>
<p>for 10 inch tablets</p>
<ul>
<li>layout-sw720dp </li>
<li>layout-sw720dp-port</li>
</ul>
<p>It runs fine on the nexus 7, but loads the sw600dp layouts on the 10" tablet.</p>
<p>If I include these default folders:</p>
<ul>
<li>layout</li>
<li>layout-port</li>
</ul>
<p>10" galaxy tab loads layouts from these.</p>
<p>If I only include the default layout folders and the sw600dp one, it crashes on the nexus7.</p>
<p>How am I supposed to support phones, 7" tablets and 10" tablets, if the 10" galaxy tab won't load the sw720p layouts?</p>
<p>edit:formatting</p> | 15,113,877 | 4 | 2 | null | 2013-02-26 13:47:22.69 UTC | 28 | 2015-07-06 09:43:46.913 UTC | 2013-02-26 14:01:04.603 UTC | null | 2,025,224 | null | 2,025,224 | null | 1 | 42 | android|layout|tablet|dpi | 39,135 | <p>The problem was, that I had no default layout folder. </p>
<p>I tried getting by, using only the sw600dp and sw720dp folders. I still have no idea why they don't work, but I don't care. I can't use swxxxdp <3.2 anyway, so screw that.</p>
<p>So if you want to write an app, that has to support phones(2.2+), 7inch tablets and 10 inch tablets, use the following oldschool stuff:</p>
<p><strong>layout</strong> this is the default, it is needed even if you don't plan to support phones!</p>
<p><strong>layout-large</strong> for 7" tablet (works on emulator and nexus7)</p>
<p><strong>layout-xlarge</strong> for 10" tablet (works on emulator and galaxytab10.1)</p>
<p><a href="https://stackoverflow.com/questions/12541442/galaxy-tab-10-layout-qualifiers">Other people</a> have came to the same conclusion too.</p> |
43,885,365 | Using map() on an iterator | <p>Say we have a Map: <code>let m = new Map();</code>, using <code>m.values()</code> returns a map iterator.</p>
<p>But I can't use <code>forEach()</code> or <code>map()</code> on that iterator and implementing a while loop on that iterator seems like an anti-pattern since ES6 offer functions like <code>map()</code>. </p>
<p>So is there a way to use <code>map()</code> on an iterator?</p> | 43,885,505 | 10 | 6 | null | 2017-05-10 06:50:14.197 UTC | 11 | 2022-08-31 09:49:06.75 UTC | null | null | null | null | 4,279,201 | null | 1 | 149 | javascript|dictionary|syntax|ecmascript-6|iterator | 81,548 | <p>The <strong>simplest</strong> and <strong>least performant</strong> way to do this is:</p>
<pre class="lang-js prettyprint-override"><code>Array.from(m).map(([key,value]) => /* whatever */)
</code></pre>
<p>Better yet</p>
<pre class="lang-js prettyprint-override"><code>Array.from(m, ([key, value]) => /* whatever */))
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" rel="noreferrer"><code>Array.from</code></a> takes any iterable or array-like thing and converts it into an array! As Daniel points out in the comments, we can add a mapping function to the conversion to remove an iteration and subsequently an intermediate array.</p>
<p>Using <code>Array.from</code> will move your performance from <em><code>O(1)</code></em> to <em><code>O(n)</code></em> as @hraban points out in the comments. Since <code>m</code> is a <code>Map</code>, and they can't be infinite, we don't have to worry about an infinite sequence. For most instances, this will suffice.</p>
<p>There are a couple of other ways to loop through a map.</p>
<h2>Using <code>forEach</code></h2>
<pre class="lang-js prettyprint-override"><code>m.forEach((value,key) => /* stuff */ )
</code></pre>
<h2>Using <code>for..of</code></h2>
<pre class="lang-js prettyprint-override"><code>var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (var [key, value] of myMap) {
console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one
</code></pre> |
5,103,121 | How to find the JVM version from a program? | <p>I want to write a sample Java file in which I want to know the JVM version in which the class is running. Is there a way?</p> | 5,103,183 | 10 | 4 | null | 2011-02-24 10:06:18.43 UTC | 18 | 2021-12-06 21:10:36.683 UTC | 2014-06-13 10:57:02.563 UTC | null | 418,556 | null | 268,850 | null | 1 | 137 | java|jvm|version | 121,307 | <p><code>System.getProperty("java.version")</code> returns what you need. </p>
<p>You can also use JMX if you want:</p>
<p><code>ManagementFactory.getRuntimeMXBean().getVmVersion()</code></p> |
5,172,421 | Generate a random float between 0 and 1 | <p>I'm trying to generate a random number that's between 0 and 1. I keep reading about <code>arc4random()</code>, but there isn't any information about getting a float from it. How do I do this?</p> | 5,172,449 | 12 | 1 | null | 2011-03-02 19:32:20.747 UTC | 21 | 2019-06-13 11:49:21.097 UTC | 2013-04-22 05:03:32.763 UTC | null | 603,977 | null | 323,698 | null | 1 | 84 | ios|c|random|floating-point|arc4random | 62,306 | <p>Random value in <strong>[0, 1[</strong> (including 0, excluding 1):</p>
<pre><code>double val = ((double)arc4random() / UINT32_MAX);
</code></pre>
<p>A bit more details <a href="https://web.archive.org/web/20141010223916/http://iphonedevelopment.blogspot.com:80/2008/10/random-thoughts-rand-vs-arc4random.html" rel="noreferrer">here</a>.</p>
<p>Actual range is <strong>[0, 0.999999999767169356]</strong>, as upper bound is (double)0xFFFFFFFF / 0x100000000.</p> |
29,643,714 | improve speed of mysql import | <p>I have large database of <code>22GB</code>. I used to take backup with <code>mysqldump</code> command in a gzip format. </p>
<p>When i extract the gz file it produces the <code>.sql</code> file of <code>16.2GB</code></p>
<p>When I try to import the database in my local server, it takes approximately 48hrs to import.Is there a way to increase the speed of the import process? </p>
<p>Also i would like to know if any hardware changes need to be done to improve the performance.</p>
<p>Current System Config</p>
<pre><code> Processor: 4th Gen i5
RAM: 8GB
</code></pre>
<p><strong>#update</strong></p>
<p>my.cnf is as follows</p>
<pre><code>#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer = 16M
max_allowed_packet = 512M
thread_stack = 192K
thread_cache_size = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover = BACKUP
#max_connections = 100
#table_cache = 64
#thread_concurrency = 10
#
# * Query Cache Configuration
#
query_cache_limit = 4M
query_cache_size = 512M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file = /var/log/mysql/mysql.log
#general_log = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 100M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
[mysqldump]
quick
quote-names
max_allowed_packet = 512M
[mysql]
#no-auto-rehash # faster start of mysql but no tab completition
[isamchk]
key_buffer = 512M
#
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
</code></pre>
<p>It is being uploading for 3 days and right now 9.9 GB has been imported. The Database has both <code>MyISAM</code> and <code>InnoDB</code> tables. What can i do to improve the import performance?</p>
<p>I have tried exporting each table separately in gz format with <code>mysqldump</code> and importing each table through PHP script executing the following code</p>
<pre><code>$dir="./";
$files = scandir($dir, 1);
array_pop($files);
array_pop($files);
$tablecount=0;
foreach($files as $file){
$tablecount++;
echo $tablecount." ";
echo $file."\n";
$command="gunzip < ".$file." | mysql -u root -pubuntu cms";
echo exec($command);
}
</code></pre> | 29,879,444 | 10 | 7 | null | 2015-04-15 07:07:33.56 UTC | 11 | 2022-01-26 16:34:49.517 UTC | 2015-04-22 05:12:02.327 UTC | null | 3,398,816 | null | 3,398,816 | null | 1 | 48 | mysql|linux|database-administration | 59,301 | <p>There are a lot of parameters that are missing, to fully understand the reason for the problem. such as:</p>
<ol>
<li>MySQL version</li>
<li>Disk type and speed</li>
<li>Free memory on the server before you start MySQL server</li>
<li>iostat output before and at the time of the mysqldump. </li>
<li>What are the parameters that you use to create the dump file in the first place.</li>
</ol>
<p>and many more.</p>
<p>So I'll try to guess that your problem is in the disks because I have 150 instances of MySQL that I manage with 3TB of data on one of them, and usually the disk is the problem</p>
<p>Now to the solution:</p>
<p>First of all - your MySQL is not configured for best performance.</p>
<p>You can read about the most important settings to configure at Percona blog post:
<a href="http://www.percona.com/blog/2014/01/28/10-mysql-settings-to-tune-after-installation/">http://www.percona.com/blog/2014/01/28/10-mysql-settings-to-tune-after-installation/</a></p>
<p>Especially check the parameters:</p>
<pre><code>innodb_buffer_pool_size
innodb_flush_log_at_trx_commit
innodb_flush_method
</code></pre>
<p>If your problem is the disk - reading the file from the same drive - is making the problem worse. </p>
<p>And if your MySQL server starting to swap because it does not have enough RAM available - your problem becomes even bigger.</p>
<p>You need to run diagnostics on your machine before and at the time of the restore procedure to figure that out.</p>
<p>Furthermore, I can suggest you to use another technic to perform the rebuild task, which works faster than mysqldump.</p>
<p>It is Percona Xtrabackup - <a href="http://www.percona.com/doc/percona-xtrabackup/2.2/">http://www.percona.com/doc/percona-xtrabackup/2.2/</a> </p>
<p>You will need to create the backup with it, and restore from it, or rebuild from running server directly with streaming option.</p>
<p>Also, MySQL version starting from 5.5 - InnoDB performs faster than MyISAM. Consider changing all your tables to it.</p> |
12,298,667 | Finding webelement with xpath starting with | <p>I'm trying to locate a link using Selenium Webdriver. I don't wanna locate it by link text, only the actual link which is typed in . This can be done by using Selenium's find element by xpath - method, but what is the syntax when I only know the starting of that href text, not the whole text?</p>
<p>I guess I'm seaching for xpath link locator with some sort of starts with-method. I have no code ready on this.</p> | 12,300,989 | 3 | 0 | null | 2012-09-06 11:03:46.16 UTC | 7 | 2016-07-26 11:00:15.39 UTC | null | null | null | null | 562,286 | null | 1 | 18 | selenium | 41,829 | <p>You can use the <code>start-with</code> in xpath to locate an attribute value that starts with a certain text.</p>
<p>For example, assume you have the following link on the page:</p>
<pre><code><a href="mylink_somerandomstuff">link text</a>
</code></pre>
<p>Then you can use the following xpath to find links that have an href that starts with 'mylink':</p>
<pre><code>//a[starts-with(@href, "mylink")]
</code></pre> |
12,478,772 | How do I use Instagram's API to display a gallery of my own photos? | <p>I'd like to use Instagram's API to display a gallery of just my own photos on a webpage. Is this possible?</p> | 12,481,401 | 3 | 1 | null | 2012-09-18 14:13:51.837 UTC | 8 | 2020-02-05 11:00:38.78 UTC | null | null | null | null | 255,196 | null | 1 | 18 | api|instagram | 96,226 | <p>Take a look here: <a href="http://instagram.com/developer/endpoints/users/">http://instagram.com/developer/endpoints/users/</a></p>
<p>Most of the endpoints require users to be authenticated. You can retrieve tagged pictures and popular pictures without authentication. In order to display your own, you would need a user to be logged in with Instagram.</p>
<p><strong>EDIT:</strong> Check this out: <a href="http://www.blueprintinteractive.com/blog/how-instagram-api-fancybox-simplified">http://www.blueprintinteractive.com/blog/how-instagram-api-fancybox-simplified</a></p> |
12,356,260 | Magento How To Show Full Error Message Instead of Truncated One | <p>Anyone know how do you make Magento show the full error message and not truncate it with ...</p>
<p>example:</p>
<pre><code>Warning: include() [function.include]: Filename cannot be empty in /home/kevinmag/public_html/app/code/core/Mage/Core/Block/Template.php on line 241
0 /home/kevinmag/public_html/app/code/core/Mage/Core/Block/Template.php(241): mageCoreErrorHandler(2, 'include() [fetchView('frontend/base/d...')
</code></pre>
<p>I want to know what the [fetchView('frontend/base/d...') it cutting off with the ...</p> | 12,358,464 | 3 | 1 | null | 2012-09-10 16:59:33.107 UTC | 19 | 2014-11-07 04:28:43.587 UTC | 2012-09-10 17:01:05.167 UTC | null | 1,533,148 | null | 1,533,148 | null | 1 | 22 | magento | 13,022 | <p>Don't blame Magento, it's all PHP's fault :) The <a href="http://php.net/manual/en/exception.gettraceasstring.php" rel="noreferrer">Exception::getTraceAsString</a> native method cuts the backtrace output, and it seems there's no normal way to handle it.</p>
<p>The only solution I've got to work is next:</p>
<ol>
<li><p>I've added a function, which I got from kind sir <strong><a href="https://stackoverflow.com/users/418819/steve">Steve</a></strong> (<a href="https://stackoverflow.com/questions/1949345/how-can-i-get-the-full-string-of-phps-gettraceasstring">How can I get the full string of PHP’s getTraceAsString()</a>) to app\code\core\Mage\Core\functions.php:</p>
<pre><code>function getExceptionTraceAsString($exception) {
$rtn = "";
$count = 0;
foreach ($exception->getTrace() as $frame) {
$args = "";
if (isset($frame['args'])) {
$args = array();
foreach ($frame['args'] as $arg) {
if (is_string($arg)) {
$args[] = "'" . $arg . "'";
} elseif (is_array($arg)) {
$args[] = "Array";
} elseif (is_null($arg)) {
$args[] = 'NULL';
} elseif (is_bool($arg)) {
$args[] = ($arg) ? "true" : "false";
} elseif (is_object($arg)) {
$args[] = get_class($arg);
} elseif (is_resource($arg)) {
$args[] = get_resource_type($arg);
} else {
$args[] = $arg;
}
}
$args = join(", ", $args);
}
$rtn .= sprintf( "#%s %s(%s): %s%s(%s)\n",
$count,
$frame['file'],
$frame['line'],
isset($frame['class']) ? $frame['class'] . '->' : '',
$frame['function'],
$args );
$count++;
}
return $rtn;
}
</code></pre></li>
<li><p>I've modified Mage.php file (<em>printException</em> method) - instead of <code>$e->getTraceAsString()</code> I've inserted <code>getExceptionTraceAsString($e)</code> - notice that there's two appearances: for Debug mode on, and off.</p></li>
</ol>
<p>To demonstrate the results, here is an example of two backtraces - without the fix, and with the fix accordingly.</p>
<p>Old:</p>
<pre><code>0 C:\apache\htdocs\checkout\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
1 C:\apache\htdocs\checkout\lib\Zend\Db\Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
2 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(479): Zend_Db_Statement->execute(Array)
3 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT COUNT(DI...', Array)
4 C:\apache\htdocs\checkout\lib\Varien\Db\Adapter\Pdo\Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('SELECT COUNT(DI...', Array)
5 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(825): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array)
6 C:\apache\htdocs\checkout\lib\Varien\Data\Collection\Db.php(217): Zend_Db_Adapter_Abstract->fetchOne(Object(Varien_Db_Select), Array)
7 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(225): Varien_Data_Collection_Db->getSize()
8 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(211): Varien_Data_Collection->getLastPageNumber()
9 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(996): Varien_Data_Collection->getCurPage()
10 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(831): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
11 C:\apache\htdocs\checkout\app\code\core\Mage\Review\Model\Observer.php(78): Mage_Eav_Model_Entity_Collection_Abstract->load()
12 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1299): Mage_Review_Model_Observer->catalogBlockProductCollectionBeforeToHtml(Object(Varien_Event_Observer))
13 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1274): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Review_Model_Observer), 'catalogBlockPro...', Object(Varien_Event_Observer))
14 C:\apache\htdocs\checkout\app\Mage.php(416): Mage_Core_Model_App->dispatchEvent('catalog_block_p...', Array)
</code></pre>
<p>New:</p>
<pre><code>0 C:\apache\htdocs\checkout\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
1 C:\apache\htdocs\checkout\lib\Zend\Db\Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
2 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(479): Zend_Db_Statement->execute(Array)
3 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT COUNT(DISTINCT e.entity_id) FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.visibility IN(2, 4) AND cat_index.category_id='3' AND cat_index.is_parent=1
INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 WHERE (d=1) AND (d=1)', Array)
4 C:\apache\htdocs\checkout\lib\Varien\Db\Adapter\Pdo\Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('SELECT COUNT(DISTINCT e.entity_id) FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.visibility IN(2, 4) AND cat_index.category_id='3' AND cat_index.is_parent=1
INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 WHERE (d=1) AND (d=1)', Array)
5 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(825): Varien_Db_Adapter_Pdo_Mysql->query(Varien_Db_Select, Array)
6 C:\apache\htdocs\checkout\lib\Varien\Data\Collection\Db.php(217): Zend_Db_Adapter_Abstract->fetchOne(Varien_Db_Select, Array)
7 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(225): Varien_Data_Collection_Db->getSize()
8 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(211): Varien_Data_Collection->getLastPageNumber()
9 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(996): Varien_Data_Collection->getCurPage()
10 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(831): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
11 C:\apache\htdocs\checkout\app\code\core\Mage\Review\Model\Observer.php(78): Mage_Eav_Model_Entity_Collection_Abstract->load()
12 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1299): Mage_Review_Model_Observer->catalogBlockProductCollectionBeforeToHtml(Varien_Event_Observer)
13 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1274): Mage_Core_Model_App->_callObserverMethod(Mage_Review_Model_Observer, 'catalogBlockProductCollectionBeforeToHtml', Varien_Event_Observer)
14 C:\apache\htdocs\checkout\app\Mage.php(416): Mage_Core_Model_App->dispatchEvent('catalog_block_product_list_collection', Array)
</code></pre>
<p><strong>Update</strong>: the above logic only modified Error/report output; to add this logic to Exception log as well you'll want to modify the Mage::logException method - change</p>
<pre><code>self::log("\n" . $e->__toString(), Zend_Log::ERR, $file);
</code></pre>
<p>with</p>
<pre><code>self::log("\n" . $e->getMessage() . getExceptionTraceAsString($e), Zend_Log::ERR, $file);
</code></pre>
<p>Hope it helps!</p> |
12,640,152 | xmlstarlet select value | <p>This is the xml-data: </p>
<pre><code><DATA VERSION="1.0">
<TABLES>
<ITEM>
<identifyer V="1234"></identifyer>
<property1 V="abcde"></property1>
<Property2 V="qwerty"></property2>
</ITEM>
<ITEM>
<identifyer V="5678"></identifyer>
<Property1 V="zyxwv"></property1>
<Property2 V="dvorak"></property2>
</ITEM>
</TABLES>
</DATA>
</code></pre>
<p>I am trying to find <code>property2</code> of the item where <code>identifyer</code> has value <code>1234</code>. I can select the data: </p>
<pre><code>$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM/identifyer [@V=1234]" test.xml
<identifyer V="1234"/>
</code></pre>
<p>Two types of output would be desirable: </p>
<pre><code>$ xmlstarlet <some magic>
<identifyer V="1234"></identifyer>
<property1 V="abcde"></property1>
<Property2 V="qwerty"></property2>
</code></pre>
<p>And: </p>
<pre><code>$ xmlstarlet <some magic>
qwerty
</code></pre> | 12,644,980 | 1 | 0 | null | 2012-09-28 12:36:11.81 UTC | 9 | 2017-10-17 10:41:15.787 UTC | 2016-12-10 10:24:08.747 UTC | null | 1,609,844 | null | 1,609,844 | null | 1 | 23 | xml|xmlstarlet | 37,124 | <p>The key is to start from the ITEM node, not the identifyer:</p>
<pre><code>$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]" test.xml
<ITEM>
<identifyer V="1234"/>
<property1 V="abcde"/>
<Property2 V="qwerty"/>
</ITEM>
</code></pre>
<p>Then you can pick out the bits you want:</p>
<pre><code>$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]/*" test.xml
<identifyer V="1234"/><property1 V="abcde"/><Property2 V="qwerty"/>
$ xmlstarlet sel -t -v "/DATA/TABLES/ITEM[identifyer/@V=1234]/Property2/@V" test.xml
qwerty
</code></pre> |
44,206,521 | How can I get the penultimate element in a list? | <p>I have a <code>std::list<double> foo;</code></p>
<p>I'm using </p>
<pre><code>if (foo.size() >= 2){
double penultimate = *(--foo.rbegin());
}
</code></pre>
<p>but this always gives me an arbitrary value of <code>penultimate</code>.</p>
<p>What am I doing wrong?</p> | 44,206,535 | 3 | 4 | null | 2017-05-26 16:47:26.323 UTC | 6 | 2017-06-01 17:34:56.953 UTC | 2017-05-26 19:37:05.307 UTC | null | 125,389 | null | 8,071,511 | null | 1 | 69 | c++|stl|stdlist | 3,477 | <p>Rather than <em>decrementing</em> <code>rbegin</code>, you should increment it, as shown here:<sup>1</sup></p>
<pre><code>double penultimate = *++foo.rbegin();
</code></pre>
<p>as <code>rbegin()</code> returns a <em>reverse iterator</em>, so <code>++</code> is the operator to move backwards in the container. Note that I've also dropped the superfluous parentheses: that's not to everyone's taste.</p>
<p>Currently the behaviour of your program is <em>undefined</em> since you are actually moving to <code>end()</code>, and you are not allowed to dereference that. The arbitrary nature of the output is a manifestation of that undefined behaviour.</p>
<hr>
<p><sup>1</sup>Do retain the minimum size check that you currently have.</p> |
18,916,432 | Malloc a string array - C | <p>I have been trying to understand malloc and strings, can someone help me with this please - I get a bad pointer error </p>
<pre><code>char password[100];
char *key[2];
int textlen, keylen, i, j, k, t, s = 0;
printf("password:\n") ;
scanf("%s",password);
keylen = strlen(password) + 1;
for(i=0; i < keylen; i++)
{
key[i] = (char*)malloc(keylen * sizeof(char));
strcpy(key[i], password);
}
printf("The key is:\n\t %s", key);
</code></pre> | 18,916,799 | 2 | 6 | null | 2013-09-20 12:08:00.77 UTC | 3 | 2017-01-02 07:06:36.537 UTC | 2016-11-10 13:23:02.05 UTC | null | 4,565,943 | null | 2,146,106 | null | 1 | 6 | c|arrays|string | 70,123 | <p>I think you need to try and understand yourself what you are trying to achieve. You don't need the key[2] array and I think you are confusing yourself there as you don't yet understand how pointers work. The following should work (untested)</p>
<pre><code>// Allow a password up to 99 characters long + room for null char
char password[100];
// pointer to malloc storage for password
char *key;
int textlen, keylen, i, j, k, t, s = 0;
// Prompt user for password
printf("password:\n") ;
scanf("%s",password);
// Determine the length of the users password, including null character room
keylen = strlen(password) + 1;
// Copy password into dynamically allocated storage
key = (char*)malloc(keylen * sizeof(char));
strcpy(key, password);
// Print the password
printf("The key is:\n\t %s", key);
</code></pre> |
24,221,449 | want to run redis-server in background nonstop | <p>I have downloaded redis-2.6.16.tar.gz file and i installed sucessfully. After installed i run src/redis-server it worked fine.</p>
<p>But i don't want manually run src/redis-server everytime, rather i want redis-server running as background process continuously.</p>
<p>So far after installed i did following tasks:</p>
<p>1. vim redis.conf and i changed to</p>
<pre><code># By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes
</code></pre>
<p>But same result i found. What mistake i did?</p>
<p>After redis run in background. I will run juggernaut also as background process with following command.</p>
<pre><code>nohup node server.js
</code></pre>
<p>But i am not able to make redis run in background. Please provide some solution.</p> | 33,316,249 | 5 | 5 | null | 2014-06-14 15:27:16.63 UTC | 25 | 2022-08-14 08:58:20.12 UTC | 2014-06-14 15:32:48.253 UTC | null | 2,606,967 | null | 2,606,967 | null | 1 | 72 | redis|juggernaut | 76,173 | <p>Since Redis 2.6 it is possible to pass Redis configuration parameters using the command line directly. This is very useful for testing purposes. </p>
<pre><code>redis-server --daemonize yes
</code></pre>
<p>Check if the process started or not:</p>
<pre><code>ps aux | grep redis-server
</code></pre> |
3,959,236 | how to change class name of an element by jquery | <pre><code><div class="bestAnswerControl">
<div id="ct100_contentplaceholder_lvanswer_control_divbestanswer"
class="IsBestAnswer"></div>
</div>
</code></pre>
<p>I want to add: </p>
<pre><code>.bestanswer
{
// some attribute
}
</code></pre>
<p>I want to replace <code>class="IsBestAnswer"</code> of div to <code>class="bestanswer"</code> by jquery.
How do I do this?</p>
<p>I am using this approach:</p>
<pre><code>$('.IsBestAnswer').addclass('bestanswer');
</code></pre>
<p>but it's not working.</p> | 3,959,249 | 3 | 1 | null | 2010-10-18 12:43:21.353 UTC | 11 | 2015-12-19 22:14:47.297 UTC | 2013-06-27 18:53:03.797 UTC | null | 1,541,083 | null | 430,803 | null | 1 | 64 | jquery | 145,307 | <pre><code>$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
</code></pre>
<p>Case in method names is important, so no <code>addclass</code>.</p>
<p><a href="http://api.jquery.com/addClass" rel="noreferrer">jQuery <code>addClass()</code></a><br>
<a href="http://api.jquery.com/removeClass" rel="noreferrer">jQuery <code>removeClass()</code></a></p> |
20,783,823 | Action Bar Tabs using ViewPager with Navigation Drawer | <p>Requirement:- Action Bar Tabs using ViewPager with Navigation Drawer .</p>
<p>I can create a Navigation Drawer example</p>
<p><img src="https://i.stack.imgur.com/x3hjA.jpg" alt="http://www.omgubuntu.co.uk/wp-content/uploads/2013/07/sidebar.jpg"></p>
<p>Action Bar Tabs using ViewPager separately. </p>
<p><img src="https://i.stack.imgur.com/j3abl.png" alt="http://developer.android.com/design/media/action_bar_pattern_considerations.png"></p>
<p>But when I try to use both at once I am having issue.</p>
<p>I can create Navigation Drawer using fragments and Action Bar Tabs using Fragment. But the initial Activity of the both examples is Fragment Activity. </p>
<p>How to implement the action bar tabs on a fragment which is part of the navigation drawer?</p> | 20,784,117 | 3 | 5 | null | 2013-12-26 11:13:29.853 UTC | 11 | 2016-02-08 10:24:35.323 UTC | 2014-07-31 11:26:05.11 UTC | null | 3,535,925 | user1586758 | null | null | 1 | 10 | android|android-fragments|android-actionbar|navigation-drawer | 22,944 | <p>Use the following layout for your main activity.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="@+id/viewpager_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffe6e1d4"
android:focusable="true"
android:focusableInTouchMode="true" />
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:listSelector="@drawable/drawer_list_selector"
android:background="@color/drawer_bg" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>Write your FragmentPagerAdapter as show in <a href="https://stackoverflow.com/q/11249836/1237297">APPTabsAdapter</a>.</p>
<p>This is how I had built it in one of my projects.</p>
<p>You can try and ask for help, if needed.</p>
<p>OR</p>
<p>You can take help from this <a href="https://github.com/Balaji-K13/Navigation-drawer-page-sliding-tab-strip" rel="nofollow noreferrer">GitHub Repo</a>.</p>
<p>Thanks.</p> |
11,333,369 | Hibernate DTO and value object mapping | <p>Is it good practice to take hibernate entities till presentation layer? or Do we need to map all properties of entities to a value object and value object will be used for UI?</p>
<p>Please let me know advantages and disadvantages of both the appoaches.</p>
<p>When should we use what?</p> | 11,334,175 | 2 | 1 | null | 2012-07-04 17:31:47.653 UTC | 10 | 2015-01-08 19:10:32.747 UTC | 2012-07-04 19:17:21.51 UTC | null | 1,493,432 | null | 1,493,432 | null | 1 | 9 | hibernate | 10,542 | <p>what you call DTO are entities in ORMs. They are normally part of a domain model which contains business logic and contain most of the time more data than is needed to render individual views. My personal rule of thumb</p>
<p><strong>Use entities in Views when there is no transfer layer between the DAL and the view and there is little business logic:</strong></p>
<ul>
<li>Advantages:
<ul>
<li>one model</li>
<li>no need to map between models</li>
<li>easier use of lazy loading</li>
</ul></li>
<li>Disadvantages:
<ul>
<li>each change in the model means change of the views</li>
<li>many disadvatages with transfer layer see below</li>
</ul></li>
</ul>
<p><strong>Map entities to DTOs when there is a transfer layer and/or the viewdata differs from entities or aggregate many different entities</strong></p>
<ul>
<li>Advantages:
<ul>
<li>DTOs/ views dont have to change when there are changes to the models</li>
<li>avoid sending entities over the wire which has loads of problems (lazy loading exceptions, much unneeded data sent, expose sensible information, ...)</li>
<li>Model has fewer responsibilities (serialisation) which make them easier to reuse (eg. backend processing)</li>
</ul></li>
<li>Disadvantages:
<ul>
<li>more classes to write</li>
<li>code to translate entities to DTOs</li>
</ul></li>
</ul> |
10,879,137 | How can I memoize a class instantiation in Python? | <p>Ok, here is the real world scenario: I'm writing an application, and I have a class that represents a certain type of files (in my case this is photographs but that detail is irrelevant to the problem). Each instance of the Photograph class should be unique to the photo's filename.</p>
<p>The problem is, when a user tells my application to load a file, I need to be able to identify when files are already loaded, and use the existing instance for that filename, rather than create duplicate instances on the same filename.</p>
<p>To me this seems like a good situation to use memoization, and there's a lot of examples of that out there, but in this case I'm not just memoizing an ordinary function, I need to be memoizing <code>__init__()</code>. This poses a problem, because by the time <code>__init__()</code> gets called it's already too late as there's a new instance created already.</p>
<p>In my research I found Python's <code>__new__()</code> method, and I was actually able to write a working trivial example, but it fell apart when I tried to use it on my real-world objects, and I'm not sure why (the only thing I can think of is that my real world objects were subclasses of other objects that I can't really control, and so there were some incompatibilities with this approach). This is what I had:</p>
<pre><code>class Flub(object):
instances = {}
def __new__(cls, flubid):
try:
self = Flub.instances[flubid]
except KeyError:
self = Flub.instances[flubid] = super(Flub, cls).__new__(cls)
print 'making a new one!'
self.flubid = flubid
print id(self)
return self
@staticmethod
def destroy_all():
for flub in Flub.instances.values():
print 'killing', flub
a = Flub('foo')
b = Flub('foo')
c = Flub('bar')
print a
print b
print c
print a is b, b is c
Flub.destroy_all()
</code></pre>
<p>Which output this:</p>
<pre><code>making a new one!
139958663753808
139958663753808
making a new one!
139958663753872
<__main__.Flub object at 0x7f4aaa6fb050>
<__main__.Flub object at 0x7f4aaa6fb050>
<__main__.Flub object at 0x7f4aaa6fb090>
True False
killing <__main__.Flub object at 0x7f4aaa6fb050>
killing <__main__.Flub object at 0x7f4aaa6fb090>
</code></pre>
<p>It's perfect! Only two instances were made for the two unique id's given, and Flub.instances clearly only has two listed.</p>
<p>But when I tried to take this approach with the objects I was using, I got all kinds of nonsensical errors about how <code>__init__()</code> took only 0 arguments, not 2. So I'd change some things around and then it would tell me that <code>__init__()</code> needed an argument. Totally bizarre.</p>
<p>After a while of fighting with it, I basically just gave up and moved all the <code>__new__()</code> black magic into a staticmethod called <code>get</code>, such that I could call <code>Photograph.get(filename)</code> and it would only call <code>Photograph(filename)</code> if filename wasn't already in <code>Photograph.instances</code>.</p>
<p>Does anybody know where I went wrong here? Is there some better way to do this?</p>
<p>Another way of thinking about it is that it's similar to a singleton, except it's not globally singleton, just singleton-per-filename.</p>
<p><a href="https://github.com/robru/gottengeography/blob/908a1842116dc26ca57e3e4db6802fa563bc2008/gg/photos.py#L74">Here's my real-world code using the staticmethod get</a> if you want to see it all together.</p> | 10,882,094 | 4 | 1 | null | 2012-06-04 09:32:08.483 UTC | 10 | 2022-05-20 10:49:32.18 UTC | 2012-06-06 07:43:45.57 UTC | null | 1,423,157 | null | 1,423,157 | null | 1 | 27 | python|caching|singleton|unique|memoization | 12,089 | <p>Let us see two points about your question.</p>
<h1>Using memoize</h1>
<p>You can use memoization, but you should decorate the <em>class</em>, not the <code>__init__</code> method. Suppose we have this memoizator:</p>
<pre><code>def get_id_tuple(f, args, kwargs, mark=object()):
"""
Some quick'n'dirty way to generate a unique key for an specific call.
"""
l = [id(f)]
for arg in args:
l.append(id(arg))
l.append(id(mark))
for k, v in kwargs:
l.append(k)
l.append(id(v))
return tuple(l)
_memoized = {}
def memoize(f):
"""
Some basic memoizer
"""
def memoized(*args, **kwargs):
key = get_id_tuple(f, args, kwargs)
if key not in _memoized:
_memoized[key] = f(*args, **kwargs)
return _memoized[key]
return memoized
</code></pre>
<p>Now you just need to decorate the class:</p>
<pre><code>@memoize
class Test(object):
def __init__(self, somevalue):
self.somevalue = somevalue
</code></pre>
<p>Let us see a test?</p>
<pre><code>tests = [Test(1), Test(2), Test(3), Test(2), Test(4)]
for test in tests:
print test.somevalue, id(test)
</code></pre>
<p>The output is below. Note that the same parameters yield the same id of the returned object:</p>
<pre><code>1 3072319660
2 3072319692
3 3072319724
2 3072319692
4 3072319756
</code></pre>
<p>Anyway, I would prefer to create a function to generate the objects and memoize it. Seems cleaner to me, but it may be some irrelevant pet peeve:</p>
<pre><code>class Test(object):
def __init__(self, somevalue):
self.somevalue = somevalue
@memoize
def get_test_from_value(somevalue):
return Test(somevalue)
</code></pre>
<h1>Using <code>__new__</code>:</h1>
<p>Or, of course, you can override <code>__new__</code>. Some days ago I posted <a href="https://stackoverflow.com/a/10789315/287976">an answer about the ins, outs and best practices of overriding <code>__new__</code></a> that can be helpful. Basically, it says to always pass <code>*args, **kwargs</code> to your <code>__new__</code> method.</p>
<p>I, for one, would prefer to memoize a function which creates the objects, or even write a specific function which would take care of never recreating a object to the same parameter. Of course, however, this is mostly a opinion of mine, not a rule.</p> |
11,120,279 | Difference between JAVA_HOME and JRE_HOME | <p>I have a script that starts Tomcat and it looks like this:</p>
<pre><code>rem set JRE_HOME=C:\Program Files\Java\jdk1.7.0_03
set JRE_HOME=C:\Program Files\Java\jre7\
set CATALINA_HOME=D:\test\Server\apache-tomcat-6.0.18
"%CATALINA_HOME%\bin\catalina.bat" jpda start
</code></pre>
<p>I can set JRE_HOME to either my jre folder or my JDK folder and Tomcat will work, but if I remove JRE_HOME and use JAVA_HOME instead, Tomcat will only work if I give it the path to the JDK folder.</p>
<p>So what is the difference between JRE and JAVA home, why does Tomcat behave in this manner?</p> | 11,147,860 | 1 | 0 | null | 2012-06-20 13:07:19.64 UTC | 7 | 2016-01-15 08:49:21.517 UTC | 2016-01-15 08:49:21.517 UTC | null | 3,885,376 | null | 473,259 | null | 1 | 32 | tomcat|java|java-home | 58,263 | <p>Tomcat enables some additional debugging options at start up if you are running with a full JDK. These options require the JDK so you Tomcat checks you are actually using one if you claim that you are to ensure these options don't fail if used.</p>
<p>I rarely see these options being used. I think I have used them once in getting on for 10 years working with Tomcat.</p>
<p>When you use JRE_HOME Tomcat doesn't enable JDK specific options so it doesn't check if you are running with the full JDK rather than the JRE.</p> |
11,258,628 | How to collapse If, Else, For, Foreach, etc clauses? | <p>I get stuck sometimes with very long clauses and I am looking for a way that allows me to collapse them, same way as I can collapse classes, methods and namespaces by default.</p>
<p>Is there a Visual Studio extension that does that? neither ReSharper nor JustCode does allow it.</p>
<p>Thank you!</p> | 11,300,947 | 5 | 3 | null | 2012-06-29 08:43:36.93 UTC | 19 | 2020-11-13 12:37:43.577 UTC | 2020-07-31 00:15:45.183 UTC | null | 3,773,011 | null | 837,623 | null | 1 | 69 | c#|visual-studio|visual-studio-extensions|clause | 67,834 | <p>Try this plugin (C# Outline Extension):</p>
<ul>
<li><a href="http://visualstudiogallery.msdn.microsoft.com/4d7e74d7-3d71-4ee5-9ac8-04b76e411ea8" rel="nofollow noreferrer">VS2010</a></li>
<li><a href="http://visualstudiogallery.msdn.microsoft.com/bc07ec7e-abfa-425f-bb65-2411a260b926" rel="nofollow noreferrer">VS2012</a></li>
<li><a href="https://visualstudiogallery.msdn.microsoft.com/6c3c5dec-1534-4c42-81b1-cfd4615fd0e9" rel="nofollow noreferrer">VS2013</a></li>
<li><a href="https://visualstudiogallery.msdn.microsoft.com/9390e08c-d0aa-42f1-b3d2-5134aabf3b9a" rel="nofollow noreferrer">VS2015</a></li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=xyz0835.CSharpOutline2017" rel="nofollow noreferrer">VS2017</a></li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=Coutline2019.xyz0835-coutline2019" rel="nofollow noreferrer">VS2019</a></li>
</ul> |
11,005,788 | ASP.NET Web Api: The requested resource does not support http method 'GET' | <p>I've got the following action on an ApiController:</p>
<pre><code>public string Something()
{
return "value";
}
</code></pre>
<p>And I've configured my routes as follows:</p>
<pre><code>routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
</code></pre>
<p>In the beta, this worked just fine, but I just updated to the latest Release Candidate and now I'm seeing errors on calls like this:</p>
<blockquote>
<p>The requested resource does not support http method 'GET'.</p>
</blockquote>
<p>Why doesn't this work anymore?</p>
<p>(I suppose I could get rid of {action} and just make a ton of controllers, but that feels messy.)</p> | 11,006,454 | 11 | 0 | null | 2012-06-12 22:29:54.707 UTC | 13 | 2020-11-18 13:06:32.36 UTC | 2012-08-22 17:38:13.76 UTC | null | 50,843 | null | 50,843 | null | 1 | 99 | asp.net|asp.net-web-api | 191,513 | <p>If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")]. </p> |
37,596,333 | tensorflow store training data on GPU memory | <p>I am pretty new to tensorflow. I used to use theano for deep learning development. I notice a difference between these two, that is where input data can be stored.</p>
<p>In Theano, it supports shared variable to store input data on GPU memory to reduce the data transfer between CPU and GPU.</p>
<p>In tensorflow, we need to feed data into placeholder, and the data can come from CPU memory or files.</p>
<p>My question is: is it possible to store input data on GPU memory for tensorflow? or does it already do it in some magic way?</p>
<p>Thanks.</p> | 37,596,846 | 2 | 10 | null | 2016-06-02 15:37:35.65 UTC | 10 | 2017-10-19 21:41:42.787 UTC | null | null | null | null | 2,945,737 | null | 1 | 13 | neural-network|tensorflow|theano|deep-learning | 7,884 | <p>If your data fits on the GPU, you can load it into a constant on GPU from e.g. a numpy array:</p>
<pre><code>with tf.device('/gpu:0'):
tensorflow_dataset = tf.constant(numpy_dataset)
</code></pre>
<p>One way to extract minibatches would be to slice that array at each step instead of feeding it using <a href="https://www.tensorflow.org/api_docs/python/tf/slice" rel="noreferrer"><code>tf.slice</code></a>:</p>
<pre><code> batch = tf.slice(tensorflow_dataset, [index, 0], [batch_size, -1])
</code></pre>
<p>There are many possible variations around that theme, including using queues to prefetch the data to GPU dynamically.</p> |
16,589,600 | Remove ns2 as default namespace prefix | <p>I have a file that is printed with a default namespace. The elements are printed with a prefix of ns2, I need this to be removed, how it is with my code:</p>
<pre><code><ns2:foo xmlns:ns2="http://namespace" />
</code></pre>
<p>how I want it to be:</p>
<pre><code><foo xmlns="http://namespace" />
</code></pre>
<p>this is how I have coded it, something which as I see it should be enough for the ns2 to go away:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:bar="http://namespace" targetNamespace="http://namespace"
elementFormDefault="qualified">
...
</code></pre>
<p>the generated package-info turns out like this:</p>
<pre><code>@javax.xml.bind.annotation.XmlSchema(namespace = "http://namespace",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.foo.bar;
</code></pre>
<p>I create the file like this:</p>
<pre><code>JAXBContext jaxbContext = JAXBContext.newInstance(generatedClassesPackage);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<Foo>(new QName("http://namespace", "Foo"),
Foo.class, rootFoo), outputStream);
</code></pre>
<p>generatedClassesPackage is the package where package-info.java and the elements are.</p>
<p>The Foo object is defined and has elements like this::</p>
<pre><code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"group"
})
@XmlRootElement(name = "Foo")
public class Foo {
@XmlElement(name = "Group", required = true)
protected List<Group> group;
</code></pre>
<p>Is it something I have missed? or have I misunderstood how this works?</p> | 16,590,616 | 7 | 8 | null | 2013-05-16 14:03:31.603 UTC | 4 | 2021-02-05 17:56:39.31 UTC | 2013-05-17 08:33:38.487 UTC | null | 2,227,064 | null | 2,227,064 | null | 1 | 37 | java|xml|jaxb | 77,280 | <p>Most likely you have multiple namespaces in the response. This will use the default convention of creating ns# namespace prefixes and one of them becomes the xmlns without a prefix. If you want to control this you can do the following:</p>
<pre><code>NamespacePrefixMapper mapper = new NamespacePrefixMapper() {
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
if ("http://namespace".equals(namespaceUri) && !requirePrefix)
return "";
return "ns";
}
};
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
marshaller.mashal....
</code></pre>
<p>This will set the <code>http://namespace</code> as the default xmlns always and use ns# for all other namespaces when marshalling. You can also give them more descriptive prefixes if you want.</p> |
16,641,033 | select2 force focus on page load | <p>I am trying to make a select2 box appear in its <em>focused</em> state on page load. I have tried the following:</p>
<pre><code>$('#id').select2('focus');
$('#id').trigger('click');
$('#id').trigger('focus');
</code></pre>
<p>Only the first line seems to have any effect, and it does focus the select2 field, however it requires an additional keypress to display the search field, and to allow typing in search string.</p>
<p>Therefore, if you load the page and start typing: "Search", the "S" will open the search box and then the remainder of the keys will be entered into it, so you'll be searching "earch"</p> | 16,641,154 | 13 | 0 | null | 2013-05-20 00:39:54.47 UTC | 7 | 2021-11-14 05:51:08.877 UTC | 2013-10-30 05:21:53.667 UTC | null | 31,671 | null | 984,976 | null | 1 | 72 | jquery|jquery-select2 | 69,653 | <p>According to the Select2 documentation: </p>
<pre><code>$('#id').select2('open');
</code></pre>
<p>Should be all you need.</p>
<p>Found under the <strong>Programmatic Access</strong> section in the <a href="https://select2.org/programmatic-control/methods#opening-the-dropdown" rel="noreferrer">documentation</a>.</p> |
25,798,674 | Python Duplicate words | <p>I have a question where I have to count the duplicate words in Python (v3.4.1) and put them in a sentence. I used counter but I don't know how to get the output in this following order. The input is:</p>
<pre><code>mysentence = As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality
</code></pre>
<p>I made this into a list and sorted it </p>
<p>The output is suppose to be this</p>
<pre><code>"As" is repeated 1 time.
"are" is repeated 2 times.
"as" is repeated 3 times.
"certain" is repeated 2 times.
"do" is repeated 1 time.
"far" is repeated 2 times.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 times.
"of" is repeated 1 time.
"reality" is repeated 2 times.
"refer" is repeated 2 times.
"the" is repeated 1 time.
"they" is repeated 3 times.
"to" is repeated 2 times.
</code></pre>
<p>I have come to this point so far</p>
<pre><code>x=input ('Enter your sentence :')
y=x.split()
y.sort()
for y in sorted(y):
print (y)
</code></pre> | 25,798,827 | 5 | 5 | null | 2014-09-11 23:52:30.26 UTC | 3 | 2022-08-11 04:57:05.92 UTC | 2014-09-12 00:04:40.653 UTC | null | 815,724 | null | 4,032,728 | null | 1 | 6 | python|python-3.x|count|duplicates | 46,244 | <p>I can see where you are going with sort, as you can reliably know when you have hit a new word and keep track of counts for each unique word. However, what you really want to do is use a hash (dictionary) to keep track of the counts as dictionary keys are unique. For example:</p>
<pre><code>words = sentence.split()
counts = {}
for word in words:
if word not in counts:
counts[word] = 0
counts[word] += 1
</code></pre>
<p>Now that will give you a dictionary where the key is the word and the value is the number of times it appears. There are things you can do like using <code>collections.defaultdict(int)</code> so you can just add the value:</p>
<pre><code>counts = collections.defaultdict(int)
for word in words:
counts[word] += 1
</code></pre>
<p>But there is even something better than that... <code>collections.Counter</code> which will take your list of words and turn it into a dictionary (an extension of dictionary actually) containing the counts.</p>
<pre><code>counts = collections.Counter(words)
</code></pre>
<p>From there you want the list of words in sorted order with their counts so you can print them. <code>items()</code> will give you a list of tuples, and <code>sorted</code> will sort (by default) by the first item of each tuple (the word in this case)... which is exactly what you want.</p>
<pre><code>import collections
sentence = """As far as the laws of mathematics refer to reality they are not certain as far as they are certain they do not refer to reality"""
words = sentence.split()
word_counts = collections.Counter(words)
for word, count in sorted(word_counts.items()):
print('"%s" is repeated %d time%s.' % (word, count, "s" if count > 1 else ""))
</code></pre>
<p><strong>OUTPUT</strong> </p>
<pre><code>"As" is repeated 1 time.
"are" is repeated 2 times.
"as" is repeated 3 times.
"certain" is repeated 2 times.
"do" is repeated 1 time.
"far" is repeated 2 times.
"laws" is repeated 1 time.
"mathematics" is repeated 1 time.
"not" is repeated 2 times.
"of" is repeated 1 time.
"reality" is repeated 2 times.
"refer" is repeated 2 times.
"the" is repeated 1 time.
"they" is repeated 3 times.
"to" is repeated 2 times.
</code></pre> |
25,606,481 | Remove-Item doesn't work, Delete does | <p>Does anyone have any idea why <code>Remove-Item</code> would fail while <code>Delete</code> works? </p>
<hr>
<p>In below script, I get a list of files I'd like to delete.<br>
Using <code>Remove-Item</code> I get following error message:</p>
<blockquote>
<p>VERBOSE: Performing the operation "Remove File" on target
"\\UncPath\Folder\test.rtf". Remove-Item : Cannot remove item
\\UncPath\Folder\test.rtf: Access to the path is denied.</p>
</blockquote>
<p>but using <code>Delete</code> is deleting those files as we speak.</p>
<p><strong>Script</strong></p>
<pre><code>$files = gci \\UncPath\Folder| ?{ $_.LastWriteTime -le (Get-Date).addDays(-28) }
# This doesn't work
$files | Remove-Item -force -verbose
# But this does
$files | % { $_.Delete() }
</code></pre> | 25,626,901 | 2 | 8 | null | 2014-09-01 13:01:31.37 UTC | null | 2014-09-02 15:33:01.03 UTC | 2014-09-01 13:14:45.31 UTC | null | 381,149 | null | 52,598 | null | 1 | 7 | windows|powershell | 38,372 | <p>I can finally repro this and IMO it appears to be a bug. The repro is to have an open share like C$ but to set Deny Modify perms for the user on the file. When I do that, I observe this:</p>
<pre><code>PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
ri : Cannot remove item \\Keith-PC\C$\Users\Keith\foo.txt: Access to the path is denied.
At line:1 char:43
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (\\Keith-PC\C$\Users\Keith\foo.txt:FileInfo) [Remove-Item], ArgumentExc
eption
+ FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Delete()} # <== this works!
</code></pre>
<p>I also observe that removing the <code>-Force</code> parameter deletes the file without error as well. The deny perms still allow me to delete the file from Windows Explorer so that leads me to believe that the file should delete. So what is up with using the <code>-Force</code> parameter? When I delve into the ErrorRecord I see this:</p>
<pre><code>Message : Access to the path is denied.
ParamName :
Data : {}
InnerException :
TargetSite : Void set_Attributes(System.IO.FileAttributes)
StackTrace : at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at Microsoft.PowerShell.Commands.FileSystemProvider.RemoveFileSystemItem(FileSystemInfo
fileSystemInfo, Boolean force)
</code></pre>
<p>It seems that the <code>-Force</code> parameter is trying to set (more likely <em>reset</em>) attributes and the permissions on the file don't allow it e.g.:</p>
<pre><code>PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
Exception setting "Attributes": "Access to the path is denied."
At line:1 char:45
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
</code></pre>
<p>So it seems to me that PowerShell should first try as if the <code>-Force</code> weren't present and if that fails, then try resetting attributes.</p> |
63,058,021 | React-hook-form's 'reset' is working properly, input fields are still not emptying after submit | <p>I've tried using the "reset" function form react-hook-form but after submitting the input fields are not emptying.
I don't know why exactly, I"m sure I"m missing something but cannot find what.</p>
<p>Here's my code:</p>
<pre><code>const Form = () => {
const [values, setValues] = useState({
email: "",
name: "",
subject: "",
description: "",
});
const { register, handleSubmit, reset, errors } = useForm();
toastr.options = {"positionClass": "toast-top-right","progressBar": true,}
const onSubmit = (values, e) => {
const { email, name, subject, description } = values;
axios.post("http://localhost:8080/sendme", {
email,
name,
subject,
text: description,
});
e.target.reset();
toastr.success('Message was sent successfully!');
};
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<div className="inputField">
<input
className={`${errors.email && "inputError"}`}
name="email"
type="email"
ref={register({ required: true, pattern: /^\S+@\S+$/i })}
placeholder="Your email *"
value={values.email}
onChange={handleChange}
/>
<ErrorMessage error={errors.email} />
</div>
<div className="inputField">
<input
className={`${errors.name && "inputError"}`}
name="name"
type="text"
placeholder="Your name *"
ref={register({ required: true })}
value={values.name}
onChange={handleChange}
/>
<ErrorMessage error={errors.name} />
</div>
<div className="inputField">
<input
className={`${errors.subject && "inputError"}`}
name="subject"
type="text"
placeholder="Subject *"
ref={register({ required: true })}
value={values.subject}
onChange={handleChange}
/>
<ErrorMessage error={errors.subject} />
</div>
<div className="inputField">
<p className="reqTxt"> * = Required</p>
<textarea
className={`${errors.description && "inputError"}`}
name="description"
placeholder="Type your message here *"
ref={register({ required: true, minLength: 15 })}
value={values.description}
onChange={handleChange}
rows="15"
cols="80"
></textarea>
<ErrorMessage error={errors.description} />
</div>
<button className="btn" onClick={reset} type="submit">
Send message
</button>
</form>
</div>
);
};
</code></pre>
<p>I've imported the reset and used it with onClick but it doesn't seem to work.
How should I fix this?</p> | 63,100,557 | 7 | 6 | null | 2020-07-23 15:39:16.027 UTC | 4 | 2022-08-14 12:00:09.99 UTC | null | null | null | null | 13,859,352 | null | 1 | 11 | reactjs|react-hooks|react-hook-form | 41,882 | <p>When you using react-hook-form, you are most likely can skip using useState:</p>
<p><a href="https://react-hook-form.com/get-started" rel="noreferrer">https://react-hook-form.com/get-started</a></p>
<p>Here is a quick example at the get started page:</p>
<pre><code>import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = data => console.log(data);
console.log(watch("example")); // watch input value by passing the name of it
return (
{/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input name="example" defaultValue="test" ref={register} />
{/* include validation with required or other standard HTML validation rules */}
<input name="exampleRequired" ref={register({ required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
</code></pre> |
62,733,064 | "ERROR in getInternalNameOfClass() called on a non-ES5 class: expected AngularFireModule to have an inner class declaration" | <pre><code>Terminal -
"WARNING in Invalid constructor parameter decorator in D:/New folder/SilverLife/node_modules/@angular/fire/fesm2015/angular-fire.js:
() => [
{ type: Object, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] }
]
ERROR in getInternalNameOfClass() called on a non-ES5 class: expected
AngularFireModule to have an inner class declaration"
</code></pre>
<p>I am facing this issue while integrating Angular firebase in my Angular 9 project.
<a href="https://i.stack.imgur.com/d9Qwf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d9Qwf.png" alt="My application's package.json" /></a></p> | 62,912,078 | 3 | 2 | null | 2020-07-04 18:43:05.517 UTC | 4 | 2022-02-22 09:54:01.147 UTC | 2020-07-04 18:50:06.86 UTC | null | 9,476,541 | null | 9,476,541 | null | 1 | 44 | angular|firebase|angularfire|angular9 | 37,284 | <p>Try changing target in the <code>compilerOptions</code> of your <code>tsconfig.json</code> from <code>es5</code> to <code>es2015</code></p> |
4,752,389 | PHP readfile() of external URL | <p>Can I use external URLs in readfile()?</p>
<pre><code> header('Content-type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename="'.$file.'" ');
//header('Content-Length: ' . filesize("http:...z/pub/".$file.'.pdf'));
@readfile("http://...z/pub/".$file.'.pdf');
</code></pre> | 4,752,423 | 2 | 2 | null | 2011-01-20 20:46:51.46 UTC | 1 | 2011-01-20 20:56:06.56 UTC | null | null | null | null | 583,311 | null | 1 | 13 | php|readfile | 42,898 | <p>The PHP manual on <a href="http://us.php.net/readfile"><code>readfile</code></a> states:</p>
<blockquote>
<p>A URL can be used as a filename with this function if the <a href="http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen">fopen wrappers</a> have been enabled. See <a href="http://us.php.net/fopen">fopen()</a> for more details on how to specify the filename. See the <a href="http://www.php.net/manual/en/wrappers.php">Supported Protocols and Wrappers</a> for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.</p>
</blockquote>
<p>As an alternative you can also use <code>file_get_contents</code>:</p>
<pre><code>echo file_get_contents("http://...z/pub/".$file.'.pdf');
</code></pre> |
4,554,749 | Replace a question mark (?) with (\\?) | <p>I am trying to define a pattern to match text with a question mark (?) inside it. In the regex the question mark is considered a 'once or not at all'. <strong>So can i replace the (?) sign in my text with (\\?) to fix the pattern problem ?</strong></p>
<pre><code>String text = "aaa aspx?pubid=222 zzz";
Pattern p = Pattern.compile( "aspx?pubid=222" );
Matcher m = p.matcher( text );
if ( m.find() )
System.out.print( "Found it." );
else
System.out.print( "Didn't find it." ); // Always prints.
</code></pre> | 4,554,779 | 2 | 0 | null | 2010-12-29 14:03:13.253 UTC | 2 | 2010-12-30 03:41:14.343 UTC | 2010-12-30 03:41:14.343 UTC | null | 227,665 | null | 147,381 | null | 1 | 28 | java|regex|replace|escaping | 65,637 | <p>You need to escape <code>?</code> as <code>\\?</code> in the <strong><em>regular expression and not in the text</em></strong>.</p>
<pre><code>Pattern p = Pattern.compile( "aspx\\?pubid=222" );
</code></pre>
<p><a href="http://www.ideone.com/ZIwvs" rel="noreferrer"><strong>See it</strong></a></p>
<p>You can also make use of <code>quote</code> method of the <code>Pattern</code> class to quote the regex meta-characters, this way <strong><em>you</em></strong> need not have to worry about quoting them:</p>
<pre><code>Pattern p = Pattern.compile(Pattern.quote("aspx?pubid=222"));
</code></pre>
<p><a href="http://www.ideone.com/aBI8Q" rel="noreferrer"><strong>See it</strong></a></p> |
4,119,672 | Do I need to include jQuery core alongside jQuery mobile? | <p>Is it necessary to include the core of jQuery, or is the mobile framework sufficient alone?
From what I`ve tried, I concluded that both files are necessary, but I would like to be sure on this issue.</p> | 4,119,729 | 2 | 0 | null | 2010-11-07 21:01:38.117 UTC | 0 | 2016-02-28 23:50:38.047 UTC | 2010-11-07 21:07:26.45 UTC | null | 94,197 | null | 500,105 | null | 1 | 30 | jquery|jquery-mobile | 9,136 | <p><a href="http://demos.jquerymobile.com/1.4.5/pages/" rel="noreferrer">The docs</a> give you all the information you need to know:</p>
<blockquote>
<p>A jQuery Mobile site must start with an HTML5 'doctype' to take full advantage of all of the framework's features. (Older devices with browsers that don't understand HTML5 will safely ignore the 'doctype' and various custom attributes.) In the 'head', <strong>references to jQuery, jQuery Mobile and the mobile theme CSS</strong> are all required to start things off.</p>
</blockquote>
<p>In short, yes, jQuery core <em>is</em> required.</p> |
4,601,852 | Find the distance between HTML element and browser (or window) sides | <p>How to find the distance in pixels between html element and one of the browser (or window) sides (left or top) using jQuery?</p> | 4,601,868 | 2 | 1 | null | 2011-01-05 07:50:44.51 UTC | 12 | 2017-05-04 06:36:47.387 UTC | 2017-05-04 06:36:47.387 UTC | null | 87,015 | null | 434,967 | null | 1 | 51 | javascript|jquery|html|position|distance | 52,209 | <p>You can use the <a href="http://api.jquery.com/offset/"><code>offset</code></a> function for that. It gives you the element's position relative to the (left,top) of the <em>document</em>:</p>
<pre><code>var offset = $("#target").offset();
display("span is at " + offset.left + "," + offset.top +
" of document");
</code></pre>
<p><a href="http://jsbin.com/oveju4">Live example</a> On my browser, that example says that the span we've targeted is at 157,47 (left,top) of the document. This is because I've applied a big padding value to the <code>body</code> element, and used a span with a spacer above it and some text in front of it.</p>
<p><a href="http://jsbin.com/oveju4/2">Here's a second example</a> showing a paragraph at the absolute left,top of the document, showing 0,0 as its position (and also showing a span later on that's offset from both the left and top, 129,19 on my browser).</p> |
26,889,142 | Using Eigen in a C Project | <p>I am working on a C project I got from the Internet, and I'm trying to add some functions to the project that involve linear algebra. In my previous works in C++, I usually rely on Eigen for linear algebra.</p>
<p>Is there a way to use Eigen for a C project? If yes, what should I do to make that work? (Simply adding Eigen header files is not enough since for example the standard C++ files do not get included automatically)</p> | 26,890,738 | 1 | 12 | null | 2014-11-12 14:17:26.777 UTC | 8 | 2014-11-12 17:12:30.687 UTC | null | null | null | null | 4,240,332 | null | 1 | 6 | c++|c|include|eigen | 5,453 | <p>Eigen is a library which heavily uses C++ features which are not present in C. As such, it cannot be directly used from a C translation unit.</p>
<p>However, you can wrap the parts using Eigen in a separate shared library and expose a C interface. Here is a small example how one could write such a library.</p>
<h2>Library interface</h2>
<pre><code>/* foo.h */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void foo(int arg);
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
</code></pre>
<p>By default, C++ uses different mangling rules than C for names of exported functions. We use <code>extern "C"</code> to instruct the C++ compiler to use the C rules. Because the interface file will be seen by both the C++ and the C compiler, we wrap the <code>extern</code> declaration in <code>#ifdef</code>s which will only trigger for the C++ compiler.</p>
<h2>Library implementation</h2>
<pre><code>/* foo.cpp */
#include "foo.h"
#include <iostream>
extern "C" {
void foo(int arg) {
std::cout << arg << std::endl;
}
} /* extern "C" */
</code></pre>
<p>We also need to define C linkage in the definition of the interface. Other than that, you can use any C++ features you like in the implementation (including Eigen).</p>
<h2>C project</h2>
<pre><code>/* main.c */
#include "foo.h"
int main() {
foo(42);
return 0;
}
</code></pre>
<p>Include the interface header and use it like any other C library.</p>
<h2>Building</h2>
<pre><code>$ g++ foo.cpp -shared -fPIC -o libfoo.so
$ gcc main.c -L. -lfoo -o main
</code></pre>
<p>Use a C++ compiler to build the shared library <code>libfoo.so</code>. Use a C compiler to build the main program, linking to the shared library. The exact build steps may vary for your compiler/platform.</p> |
9,884,091 | Dynamic Text size change according to tablet | <p>With all effort,I finally reached to the end of my first app in android. And thanks to all. But after coming to end, I realized one thing that my app text size is common in all tablet sizes. So I will re frame my question.</p>
<p><strong>Problem:</strong> I used my own custom text size in entire app. and some what satisfied with 7 inch tablet. But when I am looking the same thing in 8.9 inches and 10.1 inch tablet its containing lots of white spaces and text size are also relatively small. So is there some way that I can change the text size according to my tablet size??? It may look novice question but I am struggling with this because the same app which look wonderful in 7 inches, is loosing its essence in 8.9 and 10.1 inches. Or there is something else which I could do with my app for the same.
<strong>Probable Solution:-</strong> As my topic indicates is there some way to change the text size as tablet size changes. Either dynamically or any other way.</p>
<p><em><strong>EDITED::</em></strong> As per Cheeta answer, approach is correct but I can't do it for each layout buttons and textfields and other field. There are hundreds of field like this in single app. Can I do it in some one place and call it required attribute. Is custom tag is approach which I am looking for.Is it possible????</p>
<p>Any help will be appreciated.
Thanks in advance.</p>
<p><em><strong>NOTE</em></strong> I have not reached to a answer but cheetah answer is somewhat leading to correct way. I am marking his answer as correct although there are few alignment issue with his answer. Any other answer is always welcome. <strong>Thanks</strong></p> | 9,884,323 | 4 | 0 | null | 2012-03-27 05:58:55.537 UTC | 8 | 2018-12-07 12:52:59.143 UTC | 2012-04-02 12:25:53.1 UTC | null | 1,230,131 | null | 1,230,131 | null | 1 | 13 | android|text-size | 37,747 | <p>I was Having Same Problem but what i realized <code>sp/db</code> are not efficient for dealing with this kind of problem, I handled my alignment and font size related stuff programtically.</p>
<p>here are the steps, how i handled this problem.</p>
<ul>
<li>Calculate Screen Width and Height of Your device </li>
<li>Use Set <code>TextView.setTextSize(unit, size)</code>, where the unit parameter is <code>TypedValue.COMPLEX_UNIT_PX</code> and the size parameter is percent of the total width of your screen. Normally, for me, .5% of total width for font is suitable. You can experiment by trying other total width percentages, such as 0.4% or 0.3%.</li>
</ul>
<p>This way your font <code>size</code> will be always suitable for each and every text/screen size.</p> |
10,143,905 | Python: two-curve gaussian fitting with non-linear least-squares | <p>My knowledge of maths is limited which is why I am probably stuck. I have a spectra to which I am trying to fit two Gaussian peaks. I can fit to the largest peak, but I cannot fit to the smallest peak. I understand that I need to sum the Gaussian function for the two peaks but I do not know where I have gone wrong. An image of my current output is shown:</p>
<p><img src="https://i.stack.imgur.com/7JYwH.png" alt="Current Output"></p>
<p>The blue line is my data and the green line is my current fit. There is a shoulder to the left of the main peak in my data which I am currently trying to fit, using the following code:</p>
<pre><code>import matplotlib.pyplot as pt
import numpy as np
from scipy.optimize import leastsq
from pylab import *
time = []
counts = []
for i in open('/some/folder/to/file.txt', 'r'):
segs = i.split()
time.append(float(segs[0]))
counts.append(segs[1])
time_array = arange(len(time), dtype=float)
counts_array = arange(len(counts))
time_array[0:] = time
counts_array[0:] = counts
def model(time_array0, coeffs0):
a = coeffs0[0] + coeffs0[1] * np.exp( - ((time_array0-coeffs0[2])/coeffs0[3])**2 )
b = coeffs0[4] + coeffs0[5] * np.exp( - ((time_array0-coeffs0[6])/coeffs0[7])**2 )
c = a+b
return c
def residuals(coeffs, counts_array, time_array):
return counts_array - model(time_array, coeffs)
# 0 = baseline, 1 = amplitude, 2 = centre, 3 = width
peak1 = np.array([0,6337,16.2,4.47,0,2300,13.5,2], dtype=float)
#peak2 = np.array([0,2300,13.5,2], dtype=float)
x, flag = leastsq(residuals, peak1, args=(counts_array, time_array))
#z, flag = leastsq(residuals, peak2, args=(counts_array, time_array))
plt.plot(time_array, counts_array)
plt.plot(time_array, model(time_array, x), color = 'g')
#plt.plot(time_array, model(time_array, z), color = 'r')
plt.show()
</code></pre> | 10,149,641 | 3 | 1 | null | 2012-04-13 15:36:50.88 UTC | 12 | 2014-05-28 07:47:53.217 UTC | 2012-08-31 20:10:52.6 UTC | null | 313,087 | null | 490,332 | null | 1 | 19 | python|scipy|gaussian|least-squares | 24,306 | <p>This code worked for me providing that you are only fitting a function that is a combination of two Gaussian distributions.</p>
<p>I just made a residuals function that adds two Gaussian functions and then subtracts them from the real data. </p>
<p>The parameters (p) that I passed to Numpy's least squares function include: the mean of the first Gaussian function (m), the difference in the mean from the first and second Gaussian functions (dm, i.e. the horizontal shift), the standard deviation of the first (sd1), and the standard deviation of the second (sd2).</p>
<pre><code>import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
######################################
# Setting up test data
def norm(x, mean, sd):
norm = []
for i in range(x.size):
norm += [1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x[i] - mean)**2/(2*sd**2))]
return np.array(norm)
mean1, mean2 = 0, -2
std1, std2 = 0.5, 1
x = np.linspace(-20, 20, 500)
y_real = norm(x, mean1, std1) + norm(x, mean2, std2)
######################################
# Solving
m, dm, sd1, sd2 = [5, 10, 1, 1]
p = [m, dm, sd1, sd2] # Initial guesses for leastsq
y_init = norm(x, m, sd1) + norm(x, m + dm, sd2) # For final comparison plot
def res(p, y, x):
m, dm, sd1, sd2 = p
m1 = m
m2 = m1 + dm
y_fit = norm(x, m1, sd1) + norm(x, m2, sd2)
err = y - y_fit
return err
plsq = leastsq(res, p, args = (y_real, x))
y_est = norm(x, plsq[0][0], plsq[0][2]) + norm(x, plsq[0][0] + plsq[0][1], plsq[0][3])
plt.plot(x, y_real, label='Real Data')
plt.plot(x, y_init, 'r.', label='Starting Guess')
plt.plot(x, y_est, 'g.', label='Fitted')
plt.legend()
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/pDnAE.png" alt="Results of the code."></p> |
9,887,505 | How to change Tor identity in Python? | <p>I have the following script:</p>
<pre><code>import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
</code></pre>
<p>which uses tor and <a href="http://sourceforge.net/projects/socksipy/" rel="noreferrer">SocksiPy</a></p>
<p>Now I want to change tor identity with each request, for example:</p>
<pre><code>for i in range(0, 10):
#somehow change tor identity
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
</code></pre>
<p>How can I do this?</p> | 9,928,803 | 7 | 1 | null | 2012-03-27 10:13:07.55 UTC | 40 | 2021-07-11 10:11:32.823 UTC | 2016-01-15 15:33:20.143 UTC | null | 276,158 | null | 873,286 | null | 1 | 28 | python|tor | 44,195 | <p>Today, I have searched a lot about this question, and finally managed to answer myself. But before I need to say that pirvoxy and tor should be configured correctly. First script, then a little bit about configuration:</p>
<pre><code>import urllib2
from TorCtl import TorCtl
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support)
def newId():
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="your_password")
conn.send_signal("NEWNYM")
for i in range(0, 10):
print "case "+str(i+1)
newId()
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
urllib2.install_opener(opener)
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
</code></pre>
<p>Above script gets new IP and checks it from ifconfig.me web site. About configuration:
We need <a href="http://www.privoxy.org/">Privoxy</a>. to use TOR with HTTP connections, privoxy should work with tor. We can do it by adding thi to /etc/privoxy/config file:</p>
<pre><code>forward-socks5 / localhost:9050 . #dot is important at the end
</code></pre>
<p>then we configure ControlPort in /etc/tor/torrc file. We need just uncomment this line:</p>
<pre><code>ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C
</code></pre>
<p>then we just restart tor:</p>
<pre><code>/etc/init.d/tor restart
</code></pre> |
9,892,137 | How do I effectively design my application where most classes depend on ILogger? | <p>How can I pull objects from the container that are transient in nature? Do I have to register them with the container and inject in the constructor of the needing class? Injecting everything into the constructor doesn't feel good. Also just for one class I don't want to create a <code>TypedFactory</code> and inject the factory into the needing class.</p>
<p>Another thought that came to me was "new" them up on need basis. But I am also injecting a <code>Logger</code> component (through property) into all my classes. So if I new them up, I will have to manually instantiate the <code>Logger</code> in those classes. How can I continue to use the container for ALL of my classes?</p>
<p><em><strong>Logger injection:</em></strong> Most of my classes have the <code>Logger</code> property defined, except where there is inheritance chain (in that case only the base class has this property, and all the deriving classes use that). When these are instantiated through Windsor container, they would get my implementation of <code>ILogger</code> injected into them.</p>
<pre><code>//Install QueueMonitor as Singleton
Container.Register(Component.For<QueueMonitor>().LifestyleSingleton());
//Install DataProcessor as Trnsient
Container.Register(Component.For<DataProcessor>().LifestyleTransient());
Container.Register(Component.For<Data>().LifestyleScoped());
public class QueueMonitor
{
private dataProcessor;
public ILogger Logger { get; set; }
public void OnDataReceived(Data data)
{
//pull the dataProcessor from factory
dataProcessor.ProcessData(data);
}
}
public class DataProcessor
{
public ILogger Logger { get; set; }
public Record[] ProcessData(Data data)
{
//Data can have multiple Records
//Loop through the data and create new set of Records
//Is this the correct way to create new records?
//How do I use container here and avoid "new"
Record record = new Record(/*using the data */);
...
//return a list of Records
}
}
public class Record
{
public ILogger Logger { get; set; }
private _recordNumber;
private _recordOwner;
public string GetDescription()
{
Logger.LogDebug("log something");
// return the custom description
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li><p>How do I create new <code>Record</code> object without using "new"?</p></li>
<li><p><code>QueueMonitor</code> is <code>Singleton</code>, whereas <code>Data</code> is "Scoped". How can I inject <code>Data</code> into <code>OnDataReceived()</code> method?</p></li>
</ol> | 9,915,056 | 1 | 3 | null | 2012-03-27 14:59:42.757 UTC | 110 | 2022-07-31 10:17:31.773 UTC | 2022-07-31 10:17:31.773 UTC | null | 264,697 | null | 1,178,376 | null | 1 | 68 | .net|dependency-injection|castle-windsor|ioc-container | 19,545 | <p>From the samples you give it is hard to be very specific, but in general, when you inject <code>ILogger</code> instances into most services, you should ask yourself two things:</p>
<ol>
<li>Do I log too much?</li>
<li>Do I violate the SOLID principles?</li>
</ol>
<p><strong>1. Do I log too much</strong></p>
<p>You are logging too much, when you have a lot of code like this:</p>
<pre class="lang-cs prettyprint-override"><code>try
{
// some operations here.
}
catch (Exception ex)
{
this.logger.Log(ex);
throw;
}
</code></pre>
<p>Writing code like this comes from the concern of losing error information. Duplicating these kinds of try-catch blocks all over the place, however, doesn't help. Even worse, I often see developers log and continue by removing the last <code>throw</code> statement:</p>
<pre class="lang-cs prettyprint-override"><code>try
{
// some operations here.
}
catch (Exception ex)
{
this.logger.Log(ex); // <!-- No more throw. Execution will continue.
}
</code></pre>
<p>This is most of the cases a bad idea (and smells like the old VB <code>ON ERROR RESUME NEXT</code> behavior), because in most situations you simply have not enough information to determine whether it is safe continue. Often there is a bug in the code or a hiccup in an external resource like a database that caused the operation to fail. To continue means that the user often gets the idea that the operation succeeded, while it hasn't. Ask yourself: what is worse, showing users a generic error message saying that there something gone wrong and ask them to try again, or silently skipping the error and letting users <em>think</em> their request was successfully processed?</p>
<p>Think about how users will feel if they found out two weeks later that their order was never shipped. You’d probably lose a customer. Or worse, a patient’s <a href="https://www.mayoclinic.org/diseases-conditions/mrsa/symptoms-causes/syc-20375336" rel="noreferrer">MRSA</a> registration silently fails, causing the patient not to be quarantined by nursing and resulting in the contamination of other patients, causing high costs or perhaps even death.</p>
<p>Most of these kinds of try-catch-log lines should be removed and you should simply let the exception bubble up the call stack.</p>
<p>Shouldn't you log? You absolutely should! But if you can, define one try-catch block at the top of the application. With ASP.NET, you can implement the <code>Application_Error</code> event, register an <code>HttpModule</code> or define a custom error page that does the logging. With Win Forms the solution is different, but the concept stays the same: Define one single top most catch-all.</p>
<p>Sometimes, however, you still want to catch and log a certain type of exception. A system I worked on in the past let the business layer throw <code>ValidationExceptions</code>, which would be caught by the presentation layer. Those exceptions contained validation information for display to the user. Since those exceptions would get caught and processed in the presentation layer, they would not bubble up to the top most part of the application and didn't end up in the application's catch-all code. Still I wanted to log this information, just to find out how often the user entered invalid information and to find out whether the validations were triggered for the right reason. So this was no error logging; just logging. I wrote the following code to do this:</p>
<pre class="lang-cs prettyprint-override"><code>try
{
// some operations here.
}
catch (ValidationException ex)
{
this.logger.Log(ex);
throw;
}
</code></pre>
<p>Looks familiar? Yes, looks exactly the same as the previous code snippet, with the difference that I only caught <code>ValidationException</code> exceptions. However, there was another difference that can't be seen by just looking at this snippet. There was only <em>one place</em> in the application that contained that code! It was a decorator, which brings me to the next question you should ask yourself:</p>
<p><strong>2. Do I violate the SOLID principles?</strong></p>
<p>Things like logging, auditing, and security, are called <a href="https://en.wikipedia.org/wiki/Cross-cutting_concern" rel="noreferrer">cross-cutting concerns</a> (or aspects). They are called <em>cross cutting</em>, because they can cut across many parts of your application and must often be applied to many classes in the system. However, when you find you're writing code for their use in many classes in the system, you are most likely violating the SOLID principles. Take for instance the following example:</p>
<pre class="lang-cs prettyprint-override"><code>public void MoveCustomer(int customerId, Address newAddress)
{
var watch = Stopwatch.StartNew();
// Real operation
this.logger.Log("MoveCustomer executed in " +
watch.ElapsedMiliseconds + " ms.");
}
</code></pre>
<p>Here you measure the time it takes to execute the <code>MoveCustomer</code> operation and you log that information. It is very likely that other operations in the system need this same cross-cutting concern. You start adding code like this for your <code>ShipOrder</code>, <code>CancelOrder</code>, <code>CancelShipping</code>, and other use cases, and this leads to a lot of code duplication and eventually a maintenance nightmare (I've been there.)</p>
<p>The problem with this code can be traced back to a violation of the <a href="https://en.wikipedia.org/wiki/SOLID" rel="noreferrer">SOLID</a> principles. The SOLID principles are a set of object-oriented design principles that help you in defining flexible and maintainable (object-oriented) software. The <code>MoveCustomer</code> example violated at least two of those rules:</p>
<ol>
<li>The <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">Single Responsibility Principle</a> (SRP)—classes should have a single responsibility. The class holding the <code>MoveCustomer</code> method, however, does not only contain the core business logic, but also measures the time it takes to do the operation. In other words, it has multiple <em>responsibilities</em>.</li>
<li>The <a href="https://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">Open-Closed principle</a> (OCP)—it prescribes an application design that prevents you from having to make sweeping changes throughout the code base; or, in the vocabulary of the OCP, a class should be open for extension, but closed for modification. In case you need to add exception handling (a third responsibility) to the <code>MoveCustomer</code> use case, you (again) have to alter the <code>MoveCustomer</code> method. But not only do you have to alter the <code>MoveCustomer</code> method, but many other methods as well, as they will typically require that same exception handling, making this a sweeping change.</li>
</ol>
<p>The solution to this problem is to extract the logging into its own class and allow that class to wrap the original class:</p>
<pre class="lang-cs prettyprint-override"><code>// The real thing
public class MoveCustomerService : IMoveCustomerService
{
public virtual void MoveCustomer(int customerId, Address newAddress)
{
// Real operation
}
}
// The decorator
public class MeasuringMoveCustomerDecorator : IMoveCustomerService
{
private readonly IMoveCustomerService decorated;
private readonly ILogger logger;
public MeasuringMoveCustomerDecorator(
IMoveCustomerService decorated, ILogger logger)
{
this.decorated = decorated;
this.logger = logger;
}
public void MoveCustomer(int customerId, Address newAddress)
{
var watch = Stopwatch.StartNew();
this.decorated.MoveCustomer(customerId, newAddress);
this.logger.Log("MoveCustomer executed in " +
watch.ElapsedMiliseconds + " ms.");
}
}
</code></pre>
<p>By wrapping the <a href="https://en.wikipedia.org/wiki/Decorator_pattern" rel="noreferrer">decorator</a> around the real instance, you can now add this measuring behavior to the class, without any other part of the system to change:</p>
<pre><code>IMoveCustomerService service =
new MeasuringMoveCustomerDecorator(
new MoveCustomerService(),
new DatabaseLogger());
</code></pre>
<p>The previous example did, however, just solve part of the problem (only the SRP part). When writing the code as shown above, you will have to define separate decorators for all operations in the system, and you'll end up with decorators like <code>MeasuringShipOrderDecorator</code>, <code>MeasuringCancelOrderDecorator</code>, and <code>MeasuringCancelShippingDecorator</code>. This lead again to a lot of duplicate code (a violation of the OCP principle), and still needing to write code for every operation in the system. What's missing here is a common abstraction over use cases in the system.</p>
<p>What's missing is an <code>ICommandHandler<TCommand></code> interface.</p>
<p>Let's define this interface:</p>
<pre class="lang-cs prettyprint-override"><code>public interface ICommandHandler<TCommand>
{
void Execute(TCommand command);
}
</code></pre>
<p>And let's store the method arguments of the <code>MoveCustomer</code> method into its own (<a href="http://c2.com/cgi/wiki?ParameterObject" rel="noreferrer">Parameter Object</a>) class called <code>MoveCustomerCommand</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public class MoveCustomerCommand
{
public int CustomerId { get; set; }
public Address NewAddress { get; set; }
}
</code></pre>
<p>And let's put the behavior of the <code>MoveCustomer</code> method in a class that implements <code>ICommandHandler<MoveCustomerCommand></code>:</p>
<pre class="lang-cs prettyprint-override"><code>public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Execute(MoveCustomerCommand command)
{
int customerId = command.CustomerId;
Address newAddress = command.NewAddress;
// Real operation
}
}
</code></pre>
<p>This might look weird at first, but because you now have a general abstraction for use cases, you can rewrite your decorator to the following:</p>
<pre class="lang-cs prettyprint-override"><code>public class MeasuringCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand>
{
private ILogger logger;
private ICommandHandler<TCommand> decorated;
public MeasuringCommandHandlerDecorator(
ILogger logger,
ICommandHandler<TCommand> decorated)
{
this.decorated = decorated;
this.logger = logger;
}
public void Execute(TCommand command)
{
var watch = Stopwatch.StartNew();
this.decorated.Execute(command);
this.logger.Log(typeof(TCommand).Name + " executed in " +
watch.ElapsedMiliseconds + " ms.");
}
}
</code></pre>
<p>This new <code>MeasuringCommandHandlerDecorator<T></code> looks much like the <code>MeasuringMoveCustomerDecorator</code>, but this class can be reused for <strong>all</strong> command handlers in the system:</p>
<pre class="lang-cs prettyprint-override"><code>ICommandHandler<MoveCustomerCommand> handler1 =
new MeasuringCommandHandlerDecorator<MoveCustomerCommand>(
new MoveCustomerCommandHandler(),
new DatabaseLogger());
ICommandHandler<ShipOrderCommand> handler2 =
new MeasuringCommandHandlerDecorator<ShipOrderCommand>(
new ShipOrderCommandHandler(),
new DatabaseLogger());
</code></pre>
<p>This way it will be much, much easier to add cross-cutting concerns to your system. It's quite easy to create a convenient method in your <a href="https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/" rel="noreferrer">Composition Root</a> that can wrap any created command handler with the applicable command handlers in the system. For instance:</p>
<pre class="lang-cs prettyprint-override"><code>private static ICommandHandler<T> Decorate<T>(ICommandHandler<T> decoratee)
{
return
new MeasuringCommandHandlerDecorator<T>(
new DatabaseLogger(),
new ValidationCommandHandlerDecorator<T>(
new ValidationProvider(),
new AuthorizationCommandHandlerDecorator<T>(
new AuthorizationChecker(
new AspNetUserProvider()),
new TransactionCommandHandlerDecorator<T>(
decoratee))));
}
</code></pre>
<p>This method can be used as follows:</p>
<pre class="lang-cs prettyprint-override"><code>ICommandHandler<MoveCustomerCommand> handler1 =
Decorate(new MoveCustomerCommandHandler());
ICommandHandler<ShipOrderCommand> handler2 =
Decorate(new ShipOrderCommandHandler());
</code></pre>
<p>If your application starts to grow, however, it can get useful to bootstrap this with a DI Container, because a DI Container can support Auto-Registration. This prevents you from having to make changes to your Composition Root for every new command/handler pair you add to the system.</p>
<p>Most modern, mature DI Containers for .NET have fairly decent support for decorators, and especially Autofac (<a href="https://autofac.readthedocs.io/en/latest/advanced/adapters-decorators.html" rel="noreferrer">example</a>) and Simple Injector (<a href="https://simpleinjector.org/decorators" rel="noreferrer">example</a>) make it easy to register open-generic decorators.</p>
<p>Unity and Castle, on the other hand, have Dynamic Interception facilities (as Autofac does to btw). Dynamic Interception has a lot in common with decoration, but it uses dynamic-proxy generation under the covers. This can be more flexible than working with generic decorators, but you pay the price when it comes to maintainability, because you often loose type safety and interceptors always force you to take a dependency on the interception library, while decorators are type-safe and can be written without taking a dependency on an external library.</p>
<p>I've been using these types of designs for over a decade now and can't think of designing my applications without it. I've <a href="https://blogs.cuttingedge.it/steven/p/commands/" rel="noreferrer">written extensively</a> about these designs, and more recently, I coauthored a book called <a href="https://cuttingedge.it/book/" rel="noreferrer">Dependency Injection Principles, Practices, and Patterns</a>, which goes into much more detail on this SOLID programming style and the design described above (see chapter 10).</p> |
10,143,093 | Origin is not allowed by Access-Control-Allow-Origin | <p>I'm making an <code>Ajax.request</code> to a remote PHP server in a <a href="https://en.wikipedia.org/wiki/Sencha_Touch" rel="noreferrer">Sencha Touch</a> 2 application (wrapped in <a href="http://en.wikipedia.org/wiki/PhoneGap" rel="noreferrer">PhoneGap</a>).</p>
<p>The response from the server is the following:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://nqatalog.negroesquisso.pt/login.php" rel="noreferrer">http://nqatalog.negroesquisso.pt/login.php</a>. Origin <code>http://localhost:8888</code> is not allowed by Access-Control-Allow-Origin.</p>
</blockquote>
<p>How can I fix this problem?</p> | 10,143,166 | 18 | 5 | null | 2012-04-13 14:50:19.807 UTC | 131 | 2021-12-29 05:06:44.193 UTC | 2019-02-02 04:23:01.69 UTC | null | 441,757 | null | 240,365 | null | 1 | 359 | javascript|ajax|cors|xmlhttprequest|cross-domain | 760,018 | <p>I wrote an article on this issue a while back, <a href="http://www.cypressnorth.com/blog/programming/cross-domain-ajax-request-with-json-response-for-iefirefoxchrome-safari-jquery/" rel="noreferrer">Cross Domain AJAX</a>.</p>
<p>The easiest way to handle this if you have control of the responding server is to add a response header for:</p>
<pre><code>Access-Control-Allow-Origin: *
</code></pre>
<p>This will allow cross-domain <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a>. In PHP, you'll want to modify the response like so:</p>
<pre><code><?php header('Access-Control-Allow-Origin: *'); ?>
</code></pre>
<p>You can just put the <code>Header set Access-Control-Allow-Origin *</code> setting in the <a href="http://en.wikipedia.org/wiki/Apache_HTTP_Server" rel="noreferrer">Apache</a> configuration or htaccess file.</p>
<p>It should be noted that this effectively disables CORS protection, which <strong>very likely exposes your users to attack</strong>. If you don't know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:</p>
<pre><code><?php header('Access-Control-Allow-Origin: http://example.com') ?>
</code></pre> |
7,920,128 | Difference between Django Form 'initial' and 'bound data'? | <p>Given an example like this:</p>
<pre><code>class MyForm(forms.Form):
name = forms.CharField()
</code></pre>
<p>I'm trying to grasp what the difference between the following two snippets is:</p>
<p>"Bound Data" style:</p>
<pre><code>my_form = MyForm({'name': request.user.first_name})
</code></pre>
<p>"Initial data" style:</p>
<pre><code>my_form = MyForm(initial={'name': request.user.first_name})
</code></pre>
<p>The documentation seems to suggest than "initial is for dynamic initial values", and yet being able to pass "bound data" to the constructor accomplishes exactly the same thing. I've used initial data in the past for dynamic values, but I'm tempted to use the more straightforward "bound data" style, but would like some insights about what the real difference between these two styles is.</p> | 7,920,343 | 3 | 0 | null | 2011-10-27 17:49:06.673 UTC | 10 | 2015-12-06 09:20:11.497 UTC | null | null | null | null | 66,289 | null | 1 | 25 | python|django|django-forms | 17,582 | <p>Here's the key part from the django docs on <a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#bound-and-unbound-forms" rel="noreferrer">bound and unbound forms</a>.</p>
<blockquote>
<p>A Form instance is either <strong>bound</strong> to a set of data, or <strong>unbound</strong>:</p>
<ul>
<li>If it’s <strong>bound</strong> to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.</li>
<li>If it’s <strong>unbound</strong>, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.</li>
</ul>
</blockquote>
<p>You can't really see the difference for the example form you gave, because the form is valid in the "bound data" style. Let's extend the form by adding an <code>age</code> field, then the difference will be more obvious.</p>
<pre><code>class MyForm(forms.Form):
name = forms.CharField()
age = forms.IntegerField()
</code></pre>
<h2>Bound form</h2>
<pre><code>my_form = MyForm({'name': request.user.first_name})
</code></pre>
<p>This form is invalid, because <code>age</code> is not specified. When you render the form in the template, you will see validation errors for the <code>age</code> field.</p>
<h2>Unbound form with dynamic initial data</h2>
<pre><code>my_form = MyForm(initial={'name':request.user.first_name})
</code></pre>
<p>This form is unbound. Validation is not triggered, so there will not be any errors displayed when you render the template.</p> |
8,162,257 | Passing a lambda as a block | <p>I'm trying to define a block that I'll use to pass the the each method of multiple ranges. Rather than redefining the block on each range, I'd like to create a lamba, and pass the lambda as such:</p>
<pre><code>count = 0
procedure = lambda {|v| map[count+=1]=v}
("A".."K").each procedure
("M".."N").each procedure
("P".."Z").each procedure
</code></pre>
<p>However, I get the following error:</p>
<pre>
ArgumentError: wrong number of arguments(1 for 0)
from code.rb:23:in `each'
</pre>
<p>Any ideas what's going on here?</p> | 8,162,291 | 3 | 0 | null | 2011-11-17 04:48:02.517 UTC | 15 | 2019-03-01 21:57:46.317 UTC | 2011-11-17 06:05:57.413 UTC | null | 38,765 | null | 879,034 | null | 1 | 70 | ruby|lambda | 30,040 | <p>Tack an ampersand (<code>&</code>) onto the argument, for example:</p>
<pre><code>("A".."K").each &procedure
</code></pre>
<p>This signifies that you're passing it as the special block parameter of the method. Otherwise it's interpreted as a normal argument.</p>
<p>It also mirrors they way you'd capture and access the block parameter inside the method itself:</p>
<pre><code># the & here signifies that the special block parameter should be captured
# into the variable `procedure`
def some_func(foo, bar, &procedure)
procedure.call(foo, bar)
end
some_func(2, 3) {|a, b| a * b }
=> 6
</code></pre> |
11,610,023 | Click is not working on the Listitem Listview android | <p>I implemented the android <code>listview</code> with the <code>ListActivity</code>. Here I have the problem that when i click on the list item no action is performed when the flash color is also not coming that is the orange color. So do you have any idea about this kindly answer to my question. </p>
<pre><code>@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT)
.show();
}
</code></pre>
<p>I put this code also into the Main ListActivity.</p> | 11,624,769 | 10 | 2 | null | 2012-07-23 09:42:33.177 UTC | 8 | 2019-03-09 07:34:38.66 UTC | 2012-07-23 09:49:17.737 UTC | null | 903,469 | null | 914,427 | null | 1 | 34 | java|android|android-listview|listactivity | 37,655 | <p>The first thing what you have to note here is, whenever there are Clickable elements like Buttons or <code>ImageButtons</code> present in your <code>ListView</code> element, they take the control of click events. And so your <code>ListView</code> won't get the chance to accept the click event. </p>
<p>What you simply have to do is, set the <code>focusable</code> attribute to false for the <code>Button</code> or <code>ImageButton</code> you have in your ListView. But still they will work without any problem and also your ListView's <code>onListItemClick</code> will also work. </p>
<p>Try this, </p>
<pre><code> <Button android:id="@+id/textsize_increaser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/back_button"
android:focusable="false"
android:text=" A + "/>
</code></pre>
<p>Here I have added this <code>android:focusable="false"</code> and it works fine. try it.</p> |
11,651,254 | How to change the display name for LabelFor in razor in mvc3? | <p>In razor engine I have used <code>LabelFor</code> helper method to display the name</p>
<p>But the display name is seems to be not good to display.
so i need to change my display name how to do it....</p>
<pre><code>@Html.LabelFor(model => model.SomekingStatus, new { @class = "control-label"})
</code></pre> | 11,651,330 | 5 | 1 | null | 2012-07-25 13:49:39.67 UTC | 15 | 2021-05-17 07:03:05.84 UTC | 2015-01-23 17:12:50.463 UTC | null | 1,535,629 | null | 1,543,609 | null | 1 | 90 | asp.net-mvc-3|html-helper | 136,313 | <p>You could decorate your view model property with the <code>[DisplayName]</code> attribute and specify the text to be used:</p>
<pre><code>[DisplayName("foo bar")]
public string SomekingStatus { get; set; }
</code></pre>
<p>Or use another overload of the LabelFor helper which allows you to specify the text:</p>
<pre><code>@Html.LabelFor(model => model.SomekingStatus, "foo bar")
</code></pre>
<p>And, no, you cannot specify a class name in MVC3 as you tried to do, as the <code>LabelFor</code> helper doesn't support that. However, this would work in MVC4 or 5.</p> |
3,474,933 | How to set SelectedValue of DropDownList in GridView EditTemplate | <p>I am trying to do <a href="https://stackoverflow.com/questions/2402288/using-dropdownlist-in-edittemplates-of-a-gridview"><strong>this</strong></a> as asked earlier. The only difference that I found is additional List item that was included in above code.</p>
<p>I tried to use <code>AppendDataBoundItems=true</code> but it is still not working. I also want to set the its default value to the value that was being displayed in label of itemtemplate i.e. DropDownList's <code>SelectedValue='<%# Eval("DepartmentName") %>'</code> but thie property is not available to me in dropdownlist.
What could be the reason. ??</p>
<pre><code><EditItemTemplate>
<asp:DropDownList ID="ddlDepartment_Edit" runat="server"
DataSourceID="dsDepartment_Edit" DataTextField="DepartmentName"
DataValueField="PK_DepartmentId">
</asp:DropDownList>
<asp:SqlDataSource ID="dsDepartment_Edit" runat="server"
ConnectionString="<%$ ConnectionStrings:BlackHillsConnect %>"
ProviderName="System.Data.SqlClient" SelectCommand="sp_GetDepartmentDropDown"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDepartmentName" runat="server" Text='<%# Eval("DepartmentName") %>' >
</asp:Label>
</ItemTemplate>
</code></pre>
<p>I am using <code>GridView</code></p> | 3,475,278 | 5 | 0 | null | 2010-08-13 07:54:32.063 UTC | 2 | 2017-09-13 05:13:05.583 UTC | 2017-05-23 11:54:25.343 UTC | null | -1 | null | 203,262 | null | 1 | 10 | c#|asp.net|data-binding|sqldatasource | 65,567 | <p><code>DataValueField</code> seems to be wrong - shouldn't it be <code>DepartmentId</code>? Similarly, you need to have <code>SelectedValue='<%# Eval("**DepartmentId**") %>'</code> - <code>DepartmentName</code> would be the <code>SeletectText</code>.</p> |
3,255,773 | PHP crop image to fix width and height without losing dimension ratio | <p>im looking to create thumbnails that has 100px by 100px dimension. i've seen many articles explaining the methods but most end up having the width!=height if the dimension ratio is to be kept.</p>
<p>for example, i have a 450px by 350px image. i would like to crop to 100px by 100px. if i were to keep the ratio, i would end up having 100px by 77px. this makes it ugly when im listing these images in a row and column. however, a image without dimension ratio will look terrible as well.</p>
<p>i've seen images from flickr and they look fantastic. for example:<br>
thumbnail: <a href="http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg" rel="noreferrer">http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg</a><br>
medium size: <a href="http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg" rel="noreferrer">http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg</a><br>
large size: <a href="http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg" rel="noreferrer">http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg</a></p>
<p>tks</p> | 3,256,004 | 5 | 1 | null | 2010-07-15 13:07:45.02 UTC | 8 | 2019-05-07 12:10:27.957 UTC | 2010-07-15 13:19:52.697 UTC | null | 340,355 | null | 291,779 | null | 1 | 13 | php|image|thumbnails|crop | 58,233 | <p>This is done by only using a part of the image as the thumbnail which has a 1:1 aspect ratio (mostly the center of the image). If you look closely you can see it in the flickr thumbnail. </p>
<p>Because you have "crop" in your question, I'm not sure if you didn't already know this, but what do you want to know then?</p>
<p>To use cropping, here is an example:</p>
<pre><code>//Your Image
$imgSrc = "image.jpg";
//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);
//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);
// calculating the part of the image to use for thumbnail
if ($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
}
// copying the part into thumbnail
$thumbSize = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
</code></pre> |
3,521,209 | Making C code plot a graph automatically | <p>I have written a program which writes a list of data to a '.dat' file with the intention of then plotting it separately using gnuplot. Is there a way of making my code plot it automatically? My output is of the form:</p>
<pre><code>x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
....
</code></pre>
<p>Ideally, when I run the code the graph would also be printed with an x-label, y-label and title (which could be changed from my C code). Many thanks.</p> | 6,934,363 | 5 | 1 | null | 2010-08-19 11:18:55.677 UTC | 16 | 2020-10-08 06:07:35.327 UTC | 2010-08-19 11:33:30.353 UTC | null | 31,615 | null | 406,912 | null | 1 | 17 | c|gnuplot|numerical-methods|piping | 98,437 | <p>I came across this while searching for something else regarding gnuplot. Even though it's an old question, I thought I'd contribute some sample code. I use this for a program of mine, and I think it does a pretty tidy job. AFAIK, this PIPEing only works on Unix systems (see the edit below for Windows users). My gnuplot installation is the default install from the Ubuntu repository. </p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#define NUM_POINTS 5
#define NUM_COMMANDS 2
int main()
{
char * commandsForGnuplot[] = {"set title \"TITLEEEEE\"", "plot 'data.temp'"};
double xvals[NUM_POINTS] = {1.0, 2.0, 3.0, 4.0, 5.0};
double yvals[NUM_POINTS] = {5.0 ,3.0, 1.0, 3.0, 5.0};
FILE * temp = fopen("data.temp", "w");
/*Opens an interface that one can use to send commands as if they were typing into the
* gnuplot command line. "The -persistent" keeps the plot open even after your
* C program terminates.
*/
FILE * gnuplotPipe = popen ("gnuplot -persistent", "w");
int i;
for (i=0; i < NUM_POINTS; i++)
{
fprintf(temp, "%lf %lf \n", xvals[i], yvals[i]); //Write the data to a temporary file
}
for (i=0; i < NUM_COMMANDS; i++)
{
fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); //Send commands to gnuplot one by one.
}
return 0;
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>In my application, I also ran into the problem that the plot doesn't appear until the calling program is closed. To get around this, add a <code>fflush(gnuplotPipe)</code> after you've used <code>fprintf</code> to send it your final command. </p>
<p>I've also seen that Windows users may use <code>_popen</code> in place of <code>popen</code> -- however I can't confirm this as I don't have Windows installed.</p>
<p><strong>EDIT 2</strong></p>
<p>One can avoid having to write to a file by sending gnuplot the <code>plot '-'</code> command followed by data points followed by the letter "e". </p>
<p>e.g.</p>
<pre><code>fprintf(gnuplotPipe, "plot '-' \n");
int i;
for (int i = 0; i < NUM_POINTS; i++)
{
fprintf(gnuplotPipe, "%lf %lf\n", xvals[i], yvals[i]);
}
fprintf(gnuplotPipe, "e");
</code></pre> |
3,994,860 | How to execute jobs just after spring loads application context? | <p>I want to run some jobs just after loading the Spring context but I do not know how to do this.<br>
Do you have any idea how to do that?</p> | 4,022,069 | 5 | 0 | null | 2010-10-22 07:51:46.217 UTC | 9 | 2014-10-23 04:42:12.353 UTC | 2014-10-23 04:42:12.353 UTC | null | 1,521,627 | null | 405,458 | null | 1 | 30 | java|spring | 37,815 | <p>thank you all for your reply.
In fact I missed a little detail in my question, I wanted to run Quartz Job just after loading the application context..
I tried the solution stakfeman, but I had some problems running the Quartz Jobs.
Finally I found that solution: Use Quartz within Spring ,here is the code:</p>
<pre><code><!--
===========================Quartz configuration====================
-->
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="processLauncher" />
<property name="targetMethod" value="execute" />
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<!-- see the example of method invoking job above -->
<property name="jobDetail" ref="jobDetail" />
<!-- 10 seconds -->
<property name="startDelay" value="10000" />
<!-- repeat every 50 seconds -->
<property name="repeatInterval" value="50000" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>
</bean>
</code></pre>
<p>thank you again for the help and I apologize if the question was not very clear ':(</p> |
3,407,620 | Only show tables with certain patterns in mysql "show tables" | <p>There are too many tables in a db. how can I only show tables with certain patterns? Or is there a way I can do paging like "| more" in shell command?</p> | 3,407,663 | 5 | 1 | null | 2010-08-04 16:27:10.46 UTC | 5 | 2021-04-10 10:17:29.287 UTC | 2016-10-27 11:31:56.07 UTC | null | 4,370,109 | null | 398,384 | null | 1 | 47 | mysql|pagination|show | 25,913 | <pre><code>show tables like 'pattern';
</code></pre> |
3,828,823 | How to generate ssh keys (for github) | <p><strong>Question:</strong> How do I generate ssh private and public keys (to be used in GitHub/GitLab) using command line.</p>
<p>The command below generates the error</p>
<pre><code>sh.exe": syntax error near unexpected token '('
</code></pre>
<p>I am using Windows XP.</p>
<pre><code>$ ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/xxxx/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/xxxx/.ssh/id_rsa.
Your public key has been saved in /c/Users/xxxx/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db [email protected]
</code></pre> | 3,828,849 | 6 | 1 | null | 2010-09-30 08:01:19.163 UTC | 22 | 2022-06-10 22:18:46.86 UTC | 2021-07-13 02:47:44.867 UTC | null | 2,671,470 | null | 335,460 | null | 1 | 38 | git|ssh|github|ssh-keys | 61,778 | <p>The command to run is only </p>
<pre><code>ssh-keygen -t rsa -C "[email protected]"
</code></pre>
<p>All the rest beginning with line 2 of your script is the output of ssh-keygen.</p>
<p>And replace [email protected] with your email address.</p>
<p>Have a look at the <a href="http://linux.die.net/man/1/ssh-keygen" rel="noreferrer">manual for <code>ssh-keygen</code></a> to look for additional options. You should probably use a longer key by adding <code>-b 4096</code> to the option list.</p> |
3,602,323 | Trying to get a full URL without filename in PHP | <p>I thought this would be simple but I can't seem to find a variable of <code>$_SERVER</code> array that has what I'm looking for.</p>
<p>Let's say my url is <code>http://example.com/subdirectory/index.php</code> I want to get all but the filename - <code>http://example.com/subdirectory/</code>.</p>
<p>I know I could quite easily do this with some string manipulation, but I want to know if there's a var of the <code>_server</code> array that I'm just missing. I've tried all of them to see what they give and I can get anything BUT what I'm looking for.</p> | 3,602,369 | 7 | 2 | null | 2010-08-30 16:33:48.537 UTC | 4 | 2020-12-20 12:33:39.223 UTC | 2013-03-15 10:57:35.823 UTC | null | 1,455,317 | null | 21,880 | null | 1 | 23 | php | 50,902 | <p>There won't be one because it's not a useful attribute to track. If the current script is something other than <code>index.*</code> then it will not return the correct URL for the current script.</p>
<p>However, this might get you what you want:</p>
<pre><code>echo '//'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
</code></pre>
<p><strong>Edit:</strong><br/>
Also, aside from installing the php.net online manual search tool for Firefox and setting it up with a search keyword (which will let you pull up the documentation on the <code>$_SERVER</code> global by typing something like "<code>php $_server</code>" into your URL bar), you should also know that <code>var_dump()</code> and <code>print_r()</code> lets you output the full contents of any variable, including arrays and objects. This is very useful for debugging.</p> |
3,549,750 | Why are assignment operators (=) invalid in a foreach loop? | <p>Why are assignment operators (=) invalid in a <code>foreach</code> loop? I'm using C#, but I would assume that the argument is the same for other languages that support <code>foreach</code> (e.g. PHP). For example, if I do something like this:</p>
<pre><code>string[] sArray = new string[5];
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
</code></pre>
<p>I get an error, "Cannot assign to 'item' because it is a 'foreach iteration variable'."</p> | 3,549,789 | 10 | 2 | null | 2010-08-23 16:47:06.52 UTC | 8 | 2010-08-23 17:32:34.47 UTC | 2010-08-23 16:55:33.253 UTC | null | 82,118 | null | 214,296 | null | 1 | 29 | c#|foreach|variable-assignment | 22,131 | <p>Here's your code:</p>
<pre><code>foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
</code></pre>
<p>Here's <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx" rel="noreferrer">a rough approximation</a> of what the compiler does with this:</p>
<pre><code>using (var enumerator = sArray.GetEnumerator())
{
string item;
while (enumerator.MoveNext())
{
item = enumerator.Current;
// Your code gets put here
}
}
</code></pre>
<p>The <code>IEnumerator<T>.Current</code> property is read-only, but that's not actually relevant here, as you are attempting to assign the local <code>item</code> variable to a new value. The compile-time check preventing you from doing so is in place basically to protect you from doing something that isn't going to work like you expect (i.e., changing a local variable and having no effect on the underlying collection/sequence).</p>
<p>If you want to modify the internals of an indexed collection such as a <code>string[]</code> while enumerating, the traditional way is to use a <code>for</code> loop instead of a <code>foreach</code>:</p>
<pre><code>for (int i = 0; i < sArray.Length; ++i)
{
sArray[i] = "Some assignment.\r\n";
}
</code></pre> |
3,790,918 | Format date without year | <p>How can create text representation of some date, that <strong>takes locale into account</strong> and contains only day and month (no year)?</p>
<p>Following code gives me something like <strong>23/09/2010</strong></p>
<pre><code>DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(date);
</code></pre>
<p>I want to get <strong>23/09</strong></p> | 3,794,059 | 10 | 3 | null | 2010-09-24 20:56:14.793 UTC | 8 | 2020-08-17 13:54:53.31 UTC | 2010-09-24 22:44:22.553 UTC | null | 243,225 | null | 243,225 | null | 1 | 36 | java|date | 22,509 | <p>You could use regex to trim off all <code>y</code>'s and any non-alphabetic characters before and after, if any. Here's a kickoff example:</p>
<pre><code>public static void main(String[] args) throws Exception {
for (Locale locale : Locale.getAvailableLocales()) {
DateFormat df = getShortDateInstanceWithoutYears(locale);
System.out.println(locale + ": " + df.format(new Date()));
}
}
public static DateFormat getShortDateInstanceWithoutYears(Locale locale) {
SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
sdf.applyPattern(sdf.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", ""));
return sdf;
}
</code></pre>
<p>You see that this snippet tests it for all locales as well. It looks to work fine for all locales here.</p> |
3,989,016 | How to find all positions of the maximum value in a list? | <p>I have a list:</p>
<pre><code>a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
</code></pre>
<p>max element is 55 (two elements on position 9 and 12)</p>
<p>I need to find on which position(s) the maximum value is situated. Please, help.</p> | 3,989,032 | 18 | 0 | null | 2010-10-21 15:15:25.477 UTC | 42 | 2021-09-22 16:51:31.82 UTC | 2021-09-22 16:51:31.82 UTC | null | 967,621 | null | 465,137 | null | 1 | 210 | python|list|indexing|max | 431,049 | <pre><code>>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
</code></pre> |
7,999,259 | How to perform the TFS-equivalent of 'Undo pending changes' | <p>How do I perform the equivalent of the TFS 'Undo pending changes' in Git, on one or multiple files?</p>
<p>That basically means to do these steps:</p>
<ul>
<li>Undo changes on disk</li>
<li>Resetting any changes Git has discovered</li>
<li>Getting the latest changes on the file from Git</li>
</ul>
<p>It would be good to know the differences (if there are any) in commands for doing this if you've <strong>(1) just changed it on disk, without adding it</strong>, but also when you've <strong>(2) done the add-command</strong> and for a bonus, <strong>(3) even when you have commit the change</strong>.</p> | 7,999,306 | 4 | 0 | null | 2011-11-03 17:27:29.31 UTC | 12 | 2017-04-12 20:27:56.193 UTC | 2017-04-12 20:27:56.193 UTC | null | 41,956 | null | 2,429 | null | 1 | 35 | git|version-control|undo | 25,319 | <p>For 1 and 2, all you need to do is:</p>
<pre><code> git stash -u #same effect as git reset --hard, but can be undone
</code></pre>
<p>this will throw away any changes. Be careful if you use <code>reset</code>. Read up on manipulating the index and the permutations of the hard, soft and mixed options with the reset and checkout. The progit book explains this in detail: <a href="http://progit.org/2011/07/11/reset.html" rel="noreferrer">http://progit.org/2011/07/11/reset.html</a></p>
<p>For 3,</p>
<pre><code> git reset --hard HEAD^
</code></pre>
<p>but would be better to issue a <code>git stash -u</code> before this - just in case you have pending changes.</p>
<p>This will reset the current branch to the parent of the current commit. Look up "tree-ish" online. ^ and ~N after a reference will allow you to point to any reachable points in the history of that reference. To understand how history is tracked in git, "Git for computer scientists" explains the Directed Acyclic Graph well: <a href="http://eagain.net/articles/git-for-computer-scientists/" rel="noreferrer">http://eagain.net/articles/git-for-computer-scientists/</a></p>
<p>To get individual files from the state of the current commit (ie, throw away changes), you can use checkout</p>
<pre><code>git checkout HEAD -- <a list of files>
</code></pre>
<p>If you issued the last reset command above in error, you're not in trouble. Git keeps track of where the branches used to point in the reflog.</p>
<pre><code>git reflog
</code></pre>
<p>will list you the history. You can see in that output how to reference each, so:</p>
<pre><code>git reset --hard HEAD@{1}
</code></pre>
<p>will reset the branch to where it used to be 1 change before.</p>
<p>To add, if you want to wipe ignored files and untracked files, you can wipe with this:</p>
<pre><code>git clean -xdf
</code></pre> |
7,903,073 | AJAX form validate and submit | <p>I created a form in Drupal 7 and want to use AJAX. I added this to the submit button array:</p>
<pre><code>"#ajax" => array(
"callback" => "my_callback",
"wrapper" => "details-container",
"effect" => "fade"
)
</code></pre>
<p>This works but the whole validation function is ignored. How can I validate the form before <code>my_callback()</code> is called? And how can I display the status or error messages on a AJAX form?</p> | 7,913,188 | 6 | 4 | null | 2011-10-26 13:11:42.413 UTC | 11 | 2015-10-06 15:05:24.697 UTC | 2014-08-12 14:25:03.007 UTC | null | 1,551,356 | null | 840,330 | null | 1 | 13 | jquery|ajax|drupal-7|drupal-forms | 38,339 | <p>Ok, I figure it out. Apparently you should return an array on your ajax callback function, not just a text message...</p>
<p>Something like this:</p>
<pre><code>return array("#markup" => "<div id='wrapper'></div>");
</code></pre> |
4,758,525 | Carriage return and new line with Java and readLine() | <p>I am using the following code to establish a HTTP connection and read data:</p>
<pre><code>con = (HttpURLConnection) new URL("http://stream.twitter.com/1/statuses/sample.json").openConnection();
...
con.connect();
while (line = rd.readLine()) {
if (line.contains("\r\n")) {
System.out.println("Carriage return + new line");
}
}
</code></pre>
<p>However, it seems like "\r\n" is not part of the string (<code>line</code>), although the server does return them. How can I read the data and detect "\r\n"?</p>
<p>Thanks,</p>
<p>Joel</p> | 4,758,563 | 3 | 2 | null | 2011-01-21 11:58:47.397 UTC | 6 | 2020-05-23 01:48:45.343 UTC | null | null | null | null | 508,056 | null | 1 | 26 | java | 66,099 | <p>If <code>rd</code> is of type <code>BufferedReader</code> there is no way to figure out if <code>readLine()</code> returned something that ended with <code>\n</code>, <code>\r</code> or <code>\r\n</code>... the end-of-line characters are discarded and not part of the returned string.</p>
<p>If you really care about these characters, you can't go through <code>readLine()</code>. You'll have to for instance read the characters one by one through <a href="http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#read%28%29" rel="noreferrer"><code>read()</code></a>.</p> |
4,283,141 | Jquery change background color | <p>I was trying out jquery with this example:</p>
<pre><code> $(document).ready(function(){
$("button").mouseover(function(){
$("p#44.test").css("background-color","yellow");
$("p#44.test").hide(1500);
$("p#44.test").show(1500);
$("p#44.test").css("background-color","red");
});
});
</code></pre>
<p>I expected the following to happen:</p>
<pre><code>1. Color of <p> to turn yellow
2. <p> to slowly fade
3. <p> to slowly show
4. Color of <p> to turn red
</code></pre>
<p>But this is what actually happened:</p>
<pre><code>1. <p> turned red
2. <p> slowly hid away
3. <p> slowly showed
</code></pre>
<p>Why is that?</p> | 4,283,188 | 3 | 0 | null | 2010-11-26 07:03:12.13 UTC | 27 | 2014-01-06 20:02:32.073 UTC | 2014-01-06 20:02:32.073 UTC | null | 47,550 | null | 406,659 | null | 1 | 146 | jquery | 605,611 | <p>The <code>.css()</code> function doesn't queue behind running animations, it's instantaneous.</p>
<p>To match the behaviour that you're after, you'd need to do the following:</p>
<pre><code>$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
</code></pre>
<p>The <code>.queue()</code> function waits for running animations to run out and then fires whatever's in the supplied function.</p> |
4,220,478 | Get all DOM block elements for selected texts | <p>When selecting texts in HTML documents, one can start from within one DOM element to another element, possibly passing over several other elements on the way. Using DOM API, it is possible to get the range of the selection, the selected texts, and even the parent element of all those selected DOM elements (using commonAncestorContainer or parentElement() based on the used browser). However, there is no way I am aware of that can list all those containing elements of the selected texts other than getting the single parent element that contains them all. Using the parent and traversing the children nodes won't do it, as there might be other siblings which are not selected inside this parent.</p>
<p>So, is there is a way that I can get all these elements that contains the selected texts. I am mainly interested in getting the block elements (p, h1, h2, h3, ...etc) but I believe if there is a way to get all the elements, then I can go through them and filter them to get what I want. I welcome any ideas and suggestions.</p>
<p>Thank you.</p> | 4,220,888 | 4 | 0 | null | 2010-11-18 22:54:05.49 UTC | 9 | 2019-06-13 03:55:05.813 UTC | null | null | null | null | 512,856 | null | 1 | 11 | javascript|html|dom|selection|range | 8,482 | <p>Key is <code>window.getSelection().getRangeAt(0)</code> <a href="https://developer.mozilla.org/en/DOM/range" rel="noreferrer">https://developer.mozilla.org/en/DOM/range</a></p>
<p>Here's some sample code that you can play with to do what you want. Mentioning what you really want this for in question will help people provide better answers.</p>
<pre><code>var selection = window.getSelection();
var range = selection.getRangeAt(0);
var allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");
var allSelected = [];
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
// The second parameter says to include the element
// even if it's not fully selected
if (selection.containsNode(el, true) ) {
allSelected.push(el);
}
}
console.log('All selected =', allSelected);
</code></pre>
<p>This is not the most efficient way, you could traverse the DOM yourself using the Range's startContainer/endContainer, along with nextSibling/previousSibling and childNodes.</p> |
4,304,217 | Database schema which can support specialized properties | <p>I need to store a set of entities, of which there are several specialized versions. They have some common properties, but the specialized ones contain properties specific for that entity.</p>
<h1>Solutions</h1>
<p>The data store is a relational DBMS, and this is not for discussion :-) Specifically, it is the Microsoft SQL Server 2005.</p>
<p>I could easily create a table for the common properties and then a table for each of the specialized versions. However, it is likely that new entities will have to be added to the solution later and I don't want to maintain both an object model <em>and</em> a database schema.</p>
<p><strong>Another</strong> idea is to create a table</p>
<pre><code>reading(<common properties>, extended_properties)
</code></pre>
<p>and have the <code>extended_properties</code>field be some kind of serialization of the extended properties. I was thinking either JSON or XML. I will most likely be using an ORM framework, but I haven't decided yet. Either way, the object representation of a specialized entity from the <code>reading</code> could expose a dictionary <code>{extended_property_name, value}</code> containing the parsed key/value pairs from the <code>extended_properties</code> field.</p>
<p>From this <a href="http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx</a> I gather that XML fields, combined with schemas for these, give the notion of typed XML inside the DBMS. Also, queries involving the XML contents in the <code>extended_properties</code>field can take these into account, too.</p>
<h1>What I want</h1>
<p>Feedback on my solution suggestions, primarily the one with the <code>reading</code> table and serialization of the extended properties.</p>
<p>Also, I realize this is one of the limitations of relational DBMS' compared to key/value based stores. However, there surely must be some modelling techniques to accommodate this.</p>
<p>Any feedback is greatly appreciated!</p> | 4,359,193 | 5 | 1 | null | 2010-11-29 13:31:03.85 UTC | 17 | 2013-07-10 04:56:47.657 UTC | 2012-05-09 14:39:53.42 UTC | null | 1,011,995 | null | 299,731 | null | 1 | 11 | database-design|properties|relational-database | 5,395 | <p>Anders, do not give up any integrity or hardness, eg type safety.</p>
<p>(Response coming).</p>
<p>@Anders. No, not at all, subtyping is fine (the question is which form you use and what are the dis/advantages). Do not give up any strength or Integrity or type safety or checks or DRI. The form you choose will demand additional Checks and maybe a bit of code (depends on your platform). </p>
<p>This subject is coming up frequently, but the seeker always has a narrow perspective; I keep making the same statements (a subset) from an unchanging set. The idea is to evaluate all the options. So I am writing a doc. Unfortunately it is taking longer. Maybe 4 pages. Not ready to post. But the diagrams are finished, I think you are on the ball, and you can use it right away. </p>
<p><strong>Warning: Experienced Project Construction Engineers Only</strong><br>
<em>Road not suitable for caravans or readers with a high Eek factor</em> </p>
<p>Link to <a href="http://www.softwaregems.com.au/Documents/Article/Sixth%20Normal%20Form/5NF%206NF%20Discussion.pdf" rel="noreferrer"><strong>▶Four Alternative Data Models◀</strong></a> in Document Under Construction. Apologies for the mess on the floor; I will clean up soon.</p>
<p><a href="http://www.softwaregems.com.au/Documents/Documentary%20Examples/IDEF1X%20Notation.pdf" rel="noreferrer"><strong>▶Link to IDEF1X Notation◀</strong></a> for anyone who is unfamiliar with the Standard for modelling Relational databases.</p>
<ol>
<li><p>They are all Relational, with full integrity.</p></li>
<li><p>The 6NF options. Relational today (SQL) does not provide support for 6NF; it does not disallow it, it just does not provide the 5NF➔6NF structures. Therefore you need to build a small catalogue, what some people call "metadata". Really, it is just an extension of the standard SQL catalogue (sys tables). The level of control required is modelled in each option.</p></li>
<li><p>Essentially EAV done properly, with full control and integrity (type safety, Declarative Referential Integrity, etc) rather than the mess it usually is.</p></li>
</ol>
<p>You may be interested in these related question/answers (in particular, look at the Data Models):</p>
<p><a href="https://stackoverflow.com/questions/4011956/multiple-fixed-tables-vs-flexible-abstract-tables/4013207#4013207"><strong>Multiple Fixed vs Abstract Flexible</strong></a></p>
<p><a href="https://stackoverflow.com/questions/4283842/database-schema-related-problem/4283979#4283979"><strong>Database Schema-Related Problem</strong></a></p>
<p><a href="https://stackoverflow.com/questions/4289164/need-a-tip-on-simple-mysql-db-design/4296039#4296039"><strong>"Simple" Database Design Problem</strong></a></p>
<h2>Response to Comments</h2>
<blockquote>
<p><em>... That way, we can easily grab "Comment" rows associated with a given specialized type instance. Is this the way to do that, or will I regret that decision later? Is there any other pattern we're missing?</em></p>
</blockquote>
<p>Not sure what you mean. Comments, Notes, Addresses, end up being used (columns resident in) in many tables, so the correct method is to Normalise them; provide One Table for Comment; that is referenced from any table that requires it. Here is a generic Comment table. It is used in Product (the supertype) because you stated <em>any</em> Product. It can just as easily be used in some of the Product subtypes, and not others; in which case the FK will be in said Product Subtypes.</p>
<p><a href="http://www.softwaregems.com.au/Documents/Student%20Resolutions/Anders%20DM.pdf" rel="noreferrer"><strong>Your Data Model</strong></a></p>
<blockquote>
<p><em>What is the purpose of the ProductType table in your Product 5NF/subtype example? Does it contain a row corresponding to each specialized Product, e.g., ProductCPU? I assume it indicates which specialization the base product is.</em></p>
</blockquote>
<p>(Small critical mistake in the diagram, corrected.)</p>
<p>Yes, exactly.</p>
<p>In Standard Relational terms (not the uncontrolled messes passing off as databases), the ProductType is the <strong>Discriminator</strong>; it identifies which of the Product Subtypes apply to this Product. Tells you which Product Subtype table you need to join with. The pair together make a logical Product. Do not forget to produce the Views, one for each ProductType.</p>
<ul>
<li><p>(Do evaluate how ProductType changes, exactly what role it plays, for each of the four Data Models.)</p></li>
<li><p>"Generalisation-specialisation" is all mumbo jumbo, OO terminology; without crossing the line and learning what Relational has been capable of for 30 years. If you learn a little about Relational, you will have the full power; otherwise you are limited to the very limited OO approach to everything (Ambler and Fowler have a lot to answer for). Please read <a href="https://stackoverflow.com/questions/4132044/name-database-design-notation-you-prefer-and-why/4140309#4140309"><strong>this post</strong></a>, from <strong>11 Dec 10</strong> onwards. Relational databases model Entities, not objects; not classes.</p></li>
</ul>
<blockquote>
<p><em>For example, when adding a new product you'll want to provide, say, a dropdown selection of which product types it is possible to add. Based on this selection, it can be deduced which tables to put the data in. Correct? I'm sorry for talking about application code, but I just need to put it into perspective</em></p>
</blockquote>
<p>Yes. And what page (with fields) to provide next, for the user to enter data.</p>
<p>No problem talking about the app code that will use the Rdb, they go together like husband and wife (not husband and slave).</p>
<ul>
<li><p>For your OO classes, map the Class tree to the Rdb, once you have finished modelling the Rdb, independent of any app that will use it. Not the other way around. And not dependent on one app.</p></li>
<li><p>Forget about "persisting", it has many problems (Lost Updates; damaged data integrity; problematic debugging; massive contention; etc). All updates to the Rdb should be in Transactions, with ACID compliance, available for 30 years, but Fowler and Ambler have not read about it yet. Usually that means one stored proc pre xact.</p></li>
</ul>
<blockquote>
<p><em>The discriminant is a FK to a Type-table as we established earlier. It denotes which <strike>spec.</strike> sub type the base type adheres to. But what does the discriminant table contain in detail?</em></p>
</blockquote>
<p>Is that not clear from the data model ? <code>ProducType CHAR(1)</code> or <code>(2). Name Char(30)</code>.</p>
<blockquote>
<p><em>Could be a display-friendly text stating the type for UI-purposes,</em></p>
</blockquote>
<p>Yes, among other things, such as the control, contraint, etc, elimination of ambiguity when coding or reporting.</p>
<blockquote>
<p><em>but does it also contain the exact table name which contains the specialized type?</em></p>
</blockquote>
<p>No. That would be a little too physical to be placed in data. Disallowed on principle. </p>
<p>But it is not necessary.</p>
<blockquote>
<p><em>Say I'm interested in the Product with ID = 1. It has a discriminant indicating that it is a ProductCPU. How would you go about retrieving this ProductCPU from your app code?</em></p>
</blockquote>
<p>That will be easy if you take the provided model, and implement it (all the tables) as classes, correctly, etc. The example you request will not use Views (which are for lists, and more generic use). The pseudo-code would be:</p>
<ul>
<li>given the <code>ProductId</code> (Subtype unknown, therefore your should not be sitting a a Subtype-specific window), load the <code>Product</code> supertype only</li>
<li><p>based on the Discriminator <code>Product.ProductType</code>, set indicators, etc, and load the applicable subtype, one of <code>ProductCPU; ProductMemory; ProductDisk; ProductTape</code>; etc.</p></li>
<li><p>I have seen (and do not agree with) OO methods that load all subtypes for the given <code>ProductId</code> at once: one subtype is valid; and the rest are invalid. The code still has to constrain itself to the valid class for the <code>Product</code> based on <code>Product.ProductType</code>.</p></li>
</ul>
<p>Alternately, eg. where the context is, the user is sitting in a Subtype-specific window, eg. <code>ProductCPU</code>, with that class set up, and requests <code>ProductId</code> xxx. Then use the <code>ProductCPU</code> View. If it returns zero rows, it does not exist.</p>
<ul>
<li>There may be a <code>ProductDisk</code> xxx, but not a <code>ProductCPU</code> xxx. How you handle that, whether you indicate there is a Product`xxx but it isn't a CPU, or not, that depends on the app requirements.</li>
</ul>
<p>For lists, where the app fills in a grid, without regard to the <code>ProductId</code>, use the views (one each) to load each grid. That SQL is based on the join, and does not need to refer to <code>ProductType</code>.</p> |
4,549,489 | Can I change the name of `nohup.out`? | <p>When I run <code>nohup some_command &</code>, the output goes to <code>nohup.out</code>; <code>man nohup</code> says to look at <code>info nohup</code> which in turn says:</p>
<blockquote>
<p>If standard output is a terminal, the
command's standard output is appended
to the file 'nohup.out'; if that
cannot be written to, it is appended
to the file '$HOME/nohup.out'; and if
that cannot be written to, the command
is not run.</p>
</blockquote>
<p>But if I already have one command using <code>nohup</code> with output going to <code>/nohup.out</code> and I want to run another, <code>nohup</code> command, can I redirect the output to <code>nohup2.out</code>? </p> | 4,549,515 | 5 | 2 | null | 2010-12-28 21:03:31.917 UTC | 81 | 2020-10-14 07:30:07.463 UTC | 2012-07-25 20:05:30.52 UTC | null | 199,217 | null | 199,217 | null | 1 | 293 | bash|logging|nohup | 252,790 | <pre><code>nohup some_command &> nohup2.out &
</code></pre>
<p>and voila.</p>
<hr>
<p>Older syntax for Bash version < 4:</p>
<pre><code>nohup some_command > nohup2.out 2>&1 &
</code></pre> |
4,097,694 | float/int implicit conversion | <p>I'm doing multiplication and division of <code>float</code>s and <code>int</code>s and I forget the implicit conversion rules (and the words in the question seem too vague to google more quickly than asking here).</p>
<p>If I have two <code>int</code>s, but I want to do floating-point division, do I need only to cast one or both of the operands? How about for multiplication — if I multiply a <code>float</code> and an <code>int</code>, is the answer a <code>float</code>?</p> | 4,097,829 | 6 | 3 | null | 2010-11-04 14:32:49.28 UTC | 7 | 2014-08-07 21:23:12.01 UTC | 2013-05-24 21:10:19.027 UTC | null | 707,111 | null | 53,501 | null | 1 | 23 | java|floating-point|math | 50,380 | <p>You can’t assign to an <code>int</code> result from division of a <code>float</code> by an <code>int</code> or vice-versa. </p>
<p>So the answers are:</p>
<blockquote>
<p>If I have two <code>int</code>s, but I want to do floating point division…?</p>
</blockquote>
<p>One cast is enough.</p>
<blockquote>
<p>If I multiply a <code>float</code> and an <code>int</code>, is the answer a <code>float</code>? </p>
</blockquote>
<p>Yes it is. </p>
<hr>
<pre><code>float f = 1000f;
int i = 3;
f = i; // Ok
i = f; // Error
f = i/f; //Ok 0.003
f = f/i; //Ok 333.3333(3)
i = i/f; //Error
i = f/i; //Error
</code></pre> |
4,493,291 | How to add multi line comments in makefiles | <p>Is there a way to comment out multiple lines in makefiles like as in C syntax <code>/* */</code> ?</p> | 4,493,447 | 6 | 1 | null | 2010-12-20 19:48:08.203 UTC | 21 | 2017-04-14 18:47:36.13 UTC | 2014-06-26 07:47:44.237 UTC | null | 225,037 | null | 494,074 | null | 1 | 134 | makefile | 85,138 | <p>No, there is nothing like C-style <code>/* */</code> comments in makefiles. As somebody else suggested, you can make a multi-line comment by using line continuations. For example:</p>
<pre><code># This is the first line of a comment \
and this is still part of the comment \
as is this, since I keep ending each line \
with a backslash character
</code></pre>
<p>However, I imagine that you are probably looking to temporarily comment out a chunk of your makefile for debugging reasons, and adding a backslash on every line is not really practical. If you are using GNU make, I suggest you use the <code>ifeq</code> directive with a deliberately false expression. For example:</p>
<pre><code>ifeq ("x","y")
# here's all your 'commented' makefile content...
endif
</code></pre>
<p>Hope that helps.</p> |
4,808,433 | Is it possible to disable the network in iOS Simulator? | <p>I am trying to debug some inconsistent behaviour I am seeing in an application that gets its primary data from the Internet. I don't see the issues in the simulator, just on the device, so I'd like to reproduce the network and connectivity environment in the simulator.</p>
<p>Is there a way of disabling the network in the simulator?</p>
<p>(I am connecting to the Mac remotely to code, and there isn't any other choice right now, so disabling the OS network isn't an option).</p> | 4,808,511 | 21 | 1 | null | 2011-01-26 18:30:54.127 UTC | 114 | 2022-03-20 11:06:18.557 UTC | 2021-07-18 22:21:12.457 UTC | null | 63,550 | null | 16,280 | null | 1 | 524 | ios|iphone|debugging|networking|ios-simulator | 299,425 | <p>I'm afraid not—the simulator shares whatever network connection the OS is using. I filed a <a href="http://bugreport.apple.com" rel="noreferrer">Radar bug report</a> about simulating network conditions a while back; you might consider doing the same.</p> |
14,898,994 | IOS How do I asynchronously download and cache images and videos for use in my app | <p>I have an iphone application that displays both images and videos. The way the app is structured most of the images and videos will remain the same, with one occasionally added. I would like an opinion on the best and easiest method for asynchronously downloading and caching both images and videos, so that they will persist even after the application has quit. Also, I am only really concerned with IOS 5 and later.</p>
<p>Here is some information I have found thus far, but I am still unclear about what the best method is, and if the cache will be persistent.</p>
<p><a href="http://davidgolightly.blogspot.com/2009/02/asynchronous-image-caching-with-iphone.html" rel="nofollow noreferrer">This article</a> about asynchronous image caching (old 2009)</p>
<p><a href="http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/" rel="nofollow noreferrer">This article</a> about NSURLCache</p>
<p><a href="https://github.com/rs/SDWebImage" rel="nofollow noreferrer">SDWebImage</a> (looks great but only works with images)</p>
<p><a href="https://github.com/steipete/AFDownloadRequestOperation" rel="nofollow noreferrer">AFDownloadRequestOperation</a></p>
<p>This seems like a pretty common use case, so I'm really looking for best practices and or references to example code.</p> | 14,961,854 | 2 | 0 | null | 2013-02-15 16:27:41.16 UTC | 21 | 2016-09-12 12:08:27.633 UTC | 2015-12-30 09:57:38.16 UTC | null | 1,413,133 | null | 379,468 | null | 1 | 15 | ios|caching|video|asynchronous|download | 17,378 | <p>It is very simple to download and cache. The following code will asynchronously download and cache. </p>
<pre><code>NSCache *memoryCache; //assume there is a memoryCache for images or videos
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSString *urlString = @"http://URL";
NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
if (downloadedData) {
// STORE IN FILESYSTEM
NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *file = [cachesDirectory stringByAppendingPathComponent:urlString];
[downloadedData writeToFile:file atomically:YES];
// STORE IN MEMORY
[memoryCache setObject:downloadedData forKey:urlString];
}
// NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA
});
</code></pre>
<p>Now there is something peculiar with UIImages that makes a library like SDWebImage so valuable , even though the asynchronously downloading images is so easy. When you display images, iOS uses a lazy image decompression scheme so there is a delay. This becomes jaggy scrolling if you put these images into tableView cells. The correct solution is to image decompress (or decode) in the background, then display the decompressed image in the main thread. </p>
<p>To read more about lazy image decompression, see this: <a href="http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/">http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/</a></p>
<p>My advice is to use SDWebImage for your images, and the code above for your videos. </p> |
14,589,964 | How to Set default combobox | <p>So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.</p>
<p>Actually, it works if I create a simple combobox and use <code>comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something")</code> but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.</p>
<p>This is how I fill my combo box (located in the class's constructor);</p>
<pre><code> string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
List<string[]> list = database.Select(command, false);
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
</code></pre>
<p>I can't seem to get it to work to set a default value, like if I place <code>cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")</code> below the above code, it won't work.</p>
<p>WinForms, by the way.</p>
<p>Thank you in advance.</p> | 14,590,012 | 5 | 5 | null | 2013-01-29 18:44:05.967 UTC | 2 | 2016-09-09 09:55:50.393 UTC | 2013-01-29 18:51:16.55 UTC | null | 479,512 | null | 1,608,566 | null | 1 | 17 | c#|winforms|combobox|populate | 84,266 | <p><code>cbxCategory.SelectedIndex</code> should be set to an integer from <code>0</code> to <code>Items.Count-1</code> like </p>
<pre><code>cbxCategory.SelectedIndex = 2;
</code></pre>
<p>your </p>
<pre><code> cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")
</code></pre>
<p>should return -1 as long as no ComboboxItem mutches the string ("New");</p>
<p>another solution though i don't like it much would be</p>
<pre><code>foreach(object obj in cbxCategory.Items){
String[2] objArray = (String[])obj ;
if(objArray[1] == "New"){
cbxCategory.SelectedItem = obj;
break;
}
}
</code></pre>
<p>perhaps this also requires the following transformation to your code</p>
<pre><code> foreach (string[] result in list)
{
cbxCategory.Items.Add(result);
}
</code></pre>
<p>I haven't tested the code and i am not sure about the casting to String[2] but something similar should work</p> |
14,471,109 | How to deal with bundler updates (Gemfile.lock) in collaborative context? | <p>I have been a lone programmer on a particular project, but now someone else has joined as collaborator. With just me in the picture, <code>bundler</code> updates have been smooth, and I never thought twice about <code>Gemfile.lock</code> being tracked by Git.</p>
<p>The new collaborator ran <code>bundle install</code> after cloning the repo, and <code>Gemfile.lock</code> was updated as follows:</p>
<p><strong>Gemfile.lock</strong></p>
<pre><code>@@ -141,7 +141,7 @@ GEM
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
- thor (< 2.0, >= 0.14.6)
+ thor (>= 0.14.6, < 2.0)
raindrops (0.10.0)
rake (0.9.2.2)
rdoc (3.12)
@@ -164,7 +164,7 @@ GEM
sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
- tilt (!= 1.3.0, ~> 1.1)
+ tilt (~> 1.1, != 1.3.0)
thor (0.16.0)
tilt (1.3.3)
treetop (1.4.10)
@@ -175,7 +175,7 @@ GEM
tzinfo (0.3.33)
uglifier (1.3.0)
execjs (>= 0.3.0)
- multi_json (>= 1.0.2, ~> 1.0)
+ multi_json (~> 1.0, >= 1.0.2)
unicorn (4.3.1)
kgio (~> 2.6)
rack
</code></pre>
<p>This change was pushed into a named branch off master. How am I supposed to deal with this change?</p>
<p>Thinking out loud: Do I merge the Pull Request on GitHub? Do I just pull from upstream without a Pull Request at first? Do I run a particular bundler command to sync things up with the other collaborator's <code>Gemfile.lock</code>? Is there something the other collaborator could have done differently, so that they did not cause any gems to update (rather, just to download the gems specified in the existing <code>Gemfile.lock</code>)? What are the best practices around this situation?</p> | 14,471,228 | 1 | 0 | null | 2013-01-23 01:35:21.837 UTC | 6 | 2013-01-23 01:53:00.227 UTC | null | null | null | null | 664,833 | null | 1 | 28 | ruby-on-rails|version-control|bundler|collaboration|gemfile | 26,850 | <p>Gemfile.lock <em>should</em> be version controlled. You should be committing any changes to it. When somebody (who you trust) updates it, you should run <code>bundle install</code> to install the gems currently locked in Gemfile.lock.</p>
<p>Just running <code>bundle install</code> will not update an existing Gemfile.lock. To do so, you need to run <code>bundle update</code>.</p>
<p>All that said, there are no actual changes to the versions in your Gemfile.lock. All that changed was the order of arguments for a few lines. You can safely merge those changes in or disregard them; the resulting Gemfile.lock will be (functionally) identical.</p> |
14,629,137 | JMSSerializer stand alone - Annotation does not exist, or cannot be auto-loaded | <p>I am attempting to use JMSSerializer as a stand alone library to map JSON responses from an API to my model classes and am running into some issues.</p>
<p>Executing the following code results in an exception:</p>
<pre><code><?php
require dirname(__DIR__) . '/vendor/autoload.php';
use JMS\Serializer\Annotation AS JMS;
class Trii {
/**
* User ID for this session
* @JMS\SerializedName("userID")
* @JMS\Annotation(getter="getUserId")
* @JMS\Type("string")
* @var string
*/
private $userId;
public function getUserId() {
return $this->userId;
}
public function setUserId($userId) {
$this->userId = $userId;
}
}
$serializer = \JMS\Serializer\SerializerBuilder::create()->setDebug(true)->build();
$object = $serializer->deserialize('{"userID":"Trii"}', 'Trii', 'json');
var_dump($object);
?>
</code></pre>
<p>Here is the exception</p>
<pre><code>Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@JMS\Serializer\Annotation\SerializedName" in property Trii::$userId does not exist, or could not be auto-loaded.
</code></pre>
<p>I have the following libraries installed for the project via composer</p>
<pre><code>{
"require": {
"jms/serializer": "1.0.*@dev"
}
}
</code></pre>
<p>Is there something obvious I am missing since I am not using the whole Doctrine 2 solution?</p>
<p>EDIT: my final solution was to create a bootstrap file with the following content:</p>
<pre><code><?php
// standard composer install vendor autoload magic
require dirname(__DIR__) . '/vendor/autoload.php';
// Bootstrap the JMS custom annotations for Object to Json mapping
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
'JMS\Serializer\Annotation',
dirname(__DIR__).'/vendor/jms/serializer/src'
);
?>
</code></pre> | 21,548,713 | 6 | 0 | null | 2013-01-31 15:20:44.68 UTC | 9 | 2019-02-08 13:22:41.557 UTC | 2013-06-26 18:17:25.493 UTC | null | 1,182,891 | null | 1,182,891 | null | 1 | 38 | php|jmsserializerbundle | 17,962 | <p>Pretty sure this enables silent auto-loading which is much more convenient than registering the namespaces yourself.</p>
<pre><code>AnnotationRegistry::registerLoader('class_exists');
</code></pre> |
14,379,185 | Function privacy and unit testing Haskell | <p>How do you deal with function visibility and unit testing in Haskell?</p>
<p>If you export every function in a module so that the unit tests have access to them, you risk other people calling functions that should not be in the public API.</p>
<p>I thought of using <code>{-# LANGUAGE CPP #-}</code> and then surrounding the exports with an <code>#ifdef</code>:</p>
<pre><code>{-# LANGUAGE CPP #-}
module SomeModule
#ifndef TESTING
( export1
, export2
)
#endif
where
</code></pre>
<p>Is there a better way?</p> | 14,379,426 | 2 | 1 | null | 2013-01-17 12:31:28.277 UTC | 15 | 2013-01-17 14:42:47.207 UTC | null | null | null | null | 96,233 | null | 1 | 47 | unit-testing|haskell|private-methods | 6,176 | <p>The usual convention is to split your module into public and private parts, i.e.</p>
<pre><code>module SomeModule.Internal where
-- ... exports all private methods
</code></pre>
<p>and then the public API</p>
<pre><code>module SomeModule where (export1, export2)
import SomeModule.Internal
</code></pre>
<p>Then you can import <code>SomeModule.Internal</code> in tests and other places where its crucial to get access to the internal implementation.</p>
<p>The idea is that the users of your library never <em>accidentally</em> call the private API, but they <em>can</em> use it if the know what they are doing (debugging etc.). This greatly increases the usability of you library compared to forcibly hiding the private API.</p> |
14,671,487 | What is the difference in python attributes with underscore in front and back | <p>I want to know what is the difference between these in Python?</p>
<pre><code>self._var1
self._var1_
self.__var1
self.__var1__
</code></pre> | 14,671,542 | 1 | 1 | null | 2013-02-03 10:25:00.457 UTC | 20 | 2022-07-30 00:01:16.32 UTC | 2022-07-29 23:54:16.373 UTC | null | 15,497,888 | null | 2,036,880 | null | 1 | 52 | python | 25,948 | <p>As a starting point, you will probably find helpful this quote from <a href="http://www.python.org/dev/peps/pep-0008/#naming-conventions" rel="nofollow noreferrer">PEP 8 - Style Guide For Python Code</a>:</p>
<blockquote>
<p>In addition, the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any
case convention):</p>
<p><code>_single_leading_underscore</code>: weak "internal use" indicator. E.g. <code>from M import *</code> does not import objects whose name starts with an underscore.</p>
<p><code>single_trailing_underscore_</code>: used by convention to avoid conflicts
with Python keyword, e.g.
<code>Tkinter.Toplevel(master, class_='ClassName')</code></p>
<p><code>__double_leading_underscore</code>: when naming a class attribute, invokes name mangling (inside class FooBar, <code>__boo</code> becomes <code>_FooBar__boo</code>; see
below).</p>
<p><code>__double_leading_and_trailing_underscore__</code>: "magic" objects or attributes that live in user-controlled namespaces. E.g. <code>__init__</code>,
<code>__import__</code> or <code>__file__</code>. Never invent such names; only use them as documented.</p>
</blockquote>
<p>You asked in the context of class attributes, though, so let's take a look at your specific examples:</p>
<h1>Single leading underscore</h1>
<p>Naming an attribute in your class <code>self._var1</code> indicates to the user of the class that the attribute should only be accessed by the class's internals (or perhaps those of a subclass) and that they need not directly access it and probably shouldn't modify it. You should use leading underscores in the same places that you would use a <code>private</code> or <code>protected</code> field in Java or C#, but be aware that the language doesn't actually enforce non-access - instead you trust your class's user to not do anything stupid, and leave them the option of accessing (or modifying) your class's private field if they're really, really sure that they know what they're doing and it makes sense.</p>
<h1>Single leading and trailing underscore</h1>
<p><code>self._var1_</code> isn't something I've ever seen. I don't think this naming style has any conventional meaning in the Python world.</p>
<h1>Double leading underscore</h1>
<p>This one actually has syntactical significance. Referring to <code>self.__var1</code> from within the scope of your class invokes <a href="http://docs.python.org/release/1.5/tut/node67.html" rel="nofollow noreferrer">name mangling</a>. From outside your class, the variable will appear to be at <code>self._YourClassName__var1</code> instead of <code>self.__var1</code>. Not everyone uses this - we don't at all where I work - and for simple classes it feels like a slightly absurd and irritating alternative to using a single leading underscore.</p>
<p>However, there is a justification for it existing; if you're using lots of inheritance, if you only use single leading underscores then you don't have a way of indicating to somebody reading your code the difference between 'private' and 'protected' variables - ones that aren't even meant to be accessed by subclasses, and ones that subclasses may access but that the outside world may not. Using a single leading underscore to mean 'protected' and a double underscore to mean 'private' may therefore be a useful convention in this situation (and the name mangling will allow a subclasses to use a variable with the same name in their subclass without causing a collision).</p>
<h1>Double leading and trailing underscore</h1>
<p><code>self.__var1__</code> is something you should never create as I've literally written it, because the double leading and trailing underscore naming style is meant to be used only for names that have a special meaning defined by Python, like the <code>__init__</code> or <code>__eq__</code> methods of classes. You're free to override those to change your class's behavior (indeed, almost all classes will have a programmer-defined <code>__init__</code>), but you shouldn't make up your own names in this style like <code>self.__var1__</code>.</p> |
14,657,375 | Cython: "fatal error: numpy/arrayobject.h: No such file or directory" | <p>I'm trying to speed up the answer <a href="https://stackoverflow.com/a/14469557/1658908">here</a> using Cython. I try to compile the code (after doing the <code>cygwinccompiler.py</code> hack explained <a href="https://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o/6035864#6035864">here</a>), but get a <code>fatal error: numpy/arrayobject.h: No such file or directory...compilation terminated</code> error. Can anyone tell me if it's a problem with my code, or some esoteric subtlety with Cython?</p>
<p>Below is my code. </p>
<pre><code>import numpy as np
import scipy as sp
cimport numpy as np
cimport cython
cdef inline np.ndarray[np.int, ndim=1] fbincount(np.ndarray[np.int_t, ndim=1] x):
cdef int m = np.amax(x)+1
cdef int n = x.size
cdef unsigned int i
cdef np.ndarray[np.int_t, ndim=1] c = np.zeros(m, dtype=np.int)
for i in xrange(n):
c[<unsigned int>x[i]] += 1
return c
cdef packed struct Point:
np.float64_t f0, f1
@cython.boundscheck(False)
def sparsemaker(np.ndarray[np.float_t, ndim=2] X not None,
np.ndarray[np.float_t, ndim=2] Y not None,
np.ndarray[np.float_t, ndim=2] Z not None):
cdef np.ndarray[np.float64_t, ndim=1] counts, factor
cdef np.ndarray[np.int_t, ndim=1] row, col, repeats
cdef np.ndarray[Point] indices
cdef int x_, y_
_, row = np.unique(X, return_inverse=True); x_ = _.size
_, col = np.unique(Y, return_inverse=True); y_ = _.size
indices = np.rec.fromarrays([row,col])
_, repeats = np.unique(indices, return_inverse=True)
counts = 1. / fbincount(repeats)
Z.flat *= counts.take(repeats)
return sp.sparse.csr_matrix((Z.flat,(row,col)), shape=(x_, y_)).toarray()
</code></pre> | 14,657,667 | 8 | 5 | null | 2013-02-02 00:38:35.74 UTC | 51 | 2021-11-01 00:10:00.473 UTC | 2019-11-20 18:44:19.433 UTC | null | 8,239,061 | null | 1,658,908 | null | 1 | 175 | python|windows-7|numpy|cython | 111,787 | <p>In your <code>setup.py</code>, the <code>Extension</code> should have the argument <code>include_dirs=[numpy.get_include()]</code>.</p>
<p>Also, you are missing <code>np.import_array()</code> in your code.</p>
<p>--</p>
<p><strong>Example setup.py:</strong></p>
<pre><code>from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
setup(
ext_modules=[
Extension("my_module", ["my_module.c"],
include_dirs=[numpy.get_include()]),
],
)
# Or, if you use cythonize() to make the ext_modules list,
# include_dirs can be passed to setup()
setup(
ext_modules=cythonize("my_module.pyx"),
include_dirs=[numpy.get_include()]
)
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.