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
2,248,131
Handling exceptions from Java ExecutorService tasks
<p>I'm trying to use Java's <code>ThreadPoolExecutor</code> class to run a large number of heavy weight tasks with a fixed number of threads. Each of the tasks has many places during which it may fail due to exceptions.</p> <p>I've subclassed <code>ThreadPoolExecutor</code> and I've overridden the <code>afterExecute</code> method which is supposed to provide any uncaught exceptions encountered while running a task. However, I can't seem to make it work.</p> <p>For example:</p> <pre><code>public class ThreadPoolErrors extends ThreadPoolExecutor { public ThreadPoolErrors() { super( 1, // core threads 1, // max threads 1, // timeout TimeUnit.MINUTES, // timeout units new LinkedBlockingQueue&lt;Runnable&gt;() // work queue ); } protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if(t != null) { System.out.println("Got an error: " + t); } else { System.out.println("Everything's fine--situation normal!"); } } public static void main( String [] args) { ThreadPoolErrors threadPool = new ThreadPoolErrors(); threadPool.submit( new Runnable() { public void run() { throw new RuntimeException("Ouch! Got an error."); } } ); threadPool.shutdown(); } } </code></pre> <p>The output from this program is "Everything's fine--situation normal!" even though the only Runnable submitted to the thread pool throws an exception. Any clue to what's going on here?</p> <p>Thanks!</p>
2,248,203
13
2
null
2010-02-11 22:09:49.287 UTC
105
2022-08-17 12:40:31.513 UTC
2017-06-20 15:01:47.75 UTC
null
5,091,346
null
223,201
null
1
235
java|multithreading|exception|executorservice|threadpoolexecutor
211,883
<p>From the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">docs</a>:</p> <blockquote> <p>Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.</p> </blockquote> <p>When you submit a Runnable, it'll get wrapped in a Future.</p> <p>Your afterExecute should be something like this:</p> <pre><code>public final class ExtendedExecutor extends ThreadPoolExecutor { // ... protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t == null &amp;&amp; r instanceof Future&lt;?&gt;) { try { Future&lt;?&gt; future = (Future&lt;?&gt;) r; if (future.isDone()) { future.get(); } } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (t != null) { System.out.println(t); } } } </code></pre>
1,436,425
How do you uninstall MySQL from Mac OS X?
<p>I accidentally installed the PowerPC version of MySQL on my Intel Mac in Snow Leopard, and it installed without a problem but of course doesn't run properly. I just didn't pay enough attention. Now when I try to install the correct x86 version it says that it can't install because a newer version is already installed. A Google query led me to perform these actions/delete these files to uninstall it:</p> <pre><code>sudo rm /usr/local/mysql sudo rm -rf /usr/local/mysql* sudo rm -rf /Library/StartupItems/MySQLCOM sudo rm -rf /Library/PreferencePanes/MySQL* rm -rf ~/Library/PreferencePanes/MySQL* sudo rm -rf /Library/Receipts/mysql* sudo rm -rf /Library/Receipts/MySQL* </code></pre> <p>And finally removed the line MYSQLCOM=-YES- from <code>/etc/hostconfig</code></p> <p>They haven't seemed to help at all. I am still receiving the same message about there being a newer version. I tried installing an even newer version (the current Beta) and it also gave me the same message about a newer version already being installed. I can't uninstall it from the Prefs Pane because I never installed the PrefPane also.</p>
1,447,758
15
2
null
2009-09-17 02:26:26.483 UTC
111
2021-03-09 01:28:25.953 UTC
2016-09-26 08:08:01.727 UTC
null
1,091,402
null
173,986
null
1
225
mysql|macos|osx-snow-leopard
250,110
<p>Try running also</p> <pre><code>sudo rm -rf /var/db/receipts/com.mysql.* </code></pre>
1,410,080
Code sign error with Xcode 3.2
<p>I had a fully working build environment before upgrading to iPhone OS 3.1 and Xcode 3.2. Now when I try to do a build, I get the following:</p> <blockquote> <p>Code Sign error: Provisioning profile 'FooApp test' specifies the Application Identifier 'no.fooapp.iphoneapp' which doesn't match the current setting 'TGECMYZ3VK.no.fooapp.iphoneapp'</p> </blockquote> <p>The problem is that Xcode somehow manages to think that the "FooApp Test" provisioning profile specifies the Application Identifier "no.fooapp.iphoneapp", but this is not the case.</p> <p>In the Organizer (and in the iPhone developer portal website) the app identifier is correctly seen as 'TGECMYZ3VK.no.fooapp.iphoneapp'.</p> <p>Also, when setting the provisioning profile in the build options at the project level, Xcode correctly identifies the app identifier, but when I go to the target, I'm unable to select any valid provisioning profile.</p> <p>What could be causing this problem?</p> <p>Update: I've tried to create a new provisioning profile, but still no luck. I also tried simply changing the app identified in Info.plist to just "no.fooapp.iphoneapp". The build succeeds, but now I get an error from the Organizer:</p> <blockquote> <p>The executable was signed with invalid entitlements. The entitlements specified in your application's Code Signing Entitlements file do not match those specified in your provisioning profile. (0xE8008016).</p> </blockquote> <p>This seems reasonable, as the provisioning profile still has the "TGECMYZ3VK.no.fooapp.iphoneapp" application identifier.</p> <p>I also double checked that all certiicates are valid in the Keychain.</p> <p>So my question is how I can get Xcode to see the correct application identifier?</p> <p>UPDATE: As noted below, what seems to fix the problem is deleting all provisioning profiles, certificates, etc., making new certificates / profiles and installing them again. If anyone has any other solutions, they would be welcome. :)</p>
1,438,966
16
0
null
2009-09-11 09:58:56.52 UTC
10
2012-03-06 11:49:19.93 UTC
2011-08-18 21:22:15.363 UTC
null
63,550
null
168,601
null
1
31
iphone|xcodebuild|provisioning
57,990
<p>Well, as seems to be the case with a lot of these code signing issues, deleting all provisioning profiles, certificates, etc. and revoking and generating everything all over again turned out to do the trick. I even created a new bundle identifier, app identifier, etc., and now AdHoc distribution is working again.</p>
2,001,086
How to make ThreadPoolExecutor's submit() method block if it is saturated?
<p>I want to create a <code>ThreadPoolExecutor</code> such that when it has reached its maximum size and the queue is full, the <code>submit()</code> method <strong>blocks</strong> when trying to add new tasks. Do I need to implement a custom <code>RejectedExecutionHandler</code> for that or is there an existing way to do this using a standard Java library?</p>
2,001,205
17
3
null
2010-01-04 17:59:37.007 UTC
56
2020-06-02 18:23:50.873 UTC
2019-03-20 04:06:56.293 UTC
null
2,361,308
null
6,533
null
1
110
java|concurrency|executor
62,514
<p>One of the possible solutions I've just found:</p> <pre><code>public class BoundedExecutor { private final Executor exec; private final Semaphore semaphore; public BoundedExecutor(Executor exec, int bound) { this.exec = exec; this.semaphore = new Semaphore(bound); } public void submitTask(final Runnable command) throws InterruptedException, RejectedExecutionException { semaphore.acquire(); try { exec.execute(new Runnable() { public void run() { try { command.run(); } finally { semaphore.release(); } } }); } catch (RejectedExecutionException e) { semaphore.release(); throw e; } } } </code></pre> <p>Are there any other solutions? I'd prefer something based on <code>RejectedExecutionHandler</code> since it seems like a standard way to handle such situations.</p>
1,921,539
Using boolean values in C
<p>C doesn't have any built-in boolean types. What's the best way to use them in C?</p>
1,921,557
18
2
null
2009-12-17 12:46:49.13 UTC
260
2021-10-31 03:58:50.343 UTC
2016-05-18 22:54:09.383 UTC
null
63,550
null
209,512
null
1
838
c|boolean
1,537,714
<p>From best to worse:</p> <p><strong>Option 1 (C99 and newer)</strong></p> <pre><code>#include &lt;stdbool.h&gt; </code></pre> <p><strong>Option 2</strong></p> <pre><code>typedef enum { false, true } bool; </code></pre> <p><strong>Option 3</strong></p> <pre><code>typedef int bool; enum { false, true }; </code></pre> <p><strong>Option 4</strong></p> <pre><code>typedef int bool; #define true 1 #define false 0 </code></pre> <h1>Explanation</h1> <ul> <li>Option 1 will work only if you use C99 (or newer) and it's the &quot;standard way&quot; to do it. Choose this if possible.</li> <li>Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.</li> </ul> <p>If you are undecided, go with #1!</p>
18,088,034
How to go up using __dirname in the folder hierarchy
<p>My app structure is:</p> <pre><code> /app /css /js .. /script /server.js </code></pre> <p>I'm trying to use __dirname to point to /app folder when using</p> <pre><code>app.use(express.static( __dirname + '/app')); </code></pre> <p>I dont realy know what to search for in the web, please help.</p>
18,088,133
4
1
null
2013-08-06 18:40:59.543 UTC
4
2016-12-08 20:18:42.617 UTC
null
null
null
null
2,658,042
null
1
49
express
26,082
<p>if you're in server.js then you mean</p> <pre><code>app.use(express.static( __dirname + '/../app')); </code></pre>
17,972,036
Center vertically in UILabel with autoshrink
<p>This is a little different from all the other "How do I center the text in a <code>UILabel</code>" questions here...</p> <p>I have a <code>UILabel</code> with some text in it, I want to center the text vertically in the <code>UILabel</code>. What's the big deal, right? That's the default. The problem comes because my text is dynamic and I have autoshrink turn on. As the text grows larger, the font size shrinks. You get this behavior.</p> <p><img src="https://i.stack.imgur.com/bb3zm.jpg" alt="enter image description here"></p> <p>Notice that the font baseline has not moved, I want it to move so the numbers are centered vertically in the <code>UILabel's</code> frame.</p> <p>Easy, right? I just remember the frame's original center in <code>viewDidLoad</code></p> <pre><code> self.workoutTimeCenter = _workoutTimeLabel.center; </code></pre> <p>and then I call <code>sizeToFit</code> after I change the the text, right?</p> <pre><code> [_workoutTimeLabel sizeToFit]; _workoutTimeLabel.center = _workoutTimeCenter; </code></pre> <p>Well, <code>sizeToFit</code> did, I guess, exactly what it was supposed to do, resize the frame so the text fits without shrinking!</p> <p><img src="https://i.stack.imgur.com/XApTL.jpg" alt="enter image description here"></p> <p>How can I vertically center the text in a <code>UILabel</code> while respecting baselines and autoshrink? (Note, an <strong>iOS5</strong> and later solution is fine and I can even deal with an <strong>iOS6</strong> and later solution.)</p>
18,087,634
5
7
null
2013-07-31 13:40:15.093 UTC
12
2017-03-01 15:47:56.137 UTC
2013-08-02 15:23:21.95 UTC
null
1,578,401
null
1,050,482
null
1
53
ios|uilabel
25,730
<p>In my experience you can just set the <code>-[UILabel baselineAdjustment]</code> property to <code>UIBaselineAdjustmentAlignCenters</code> to achieve the effect you're describing.</p> <p>From the <a href="http://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/baselineAdjustment">docs</a>:</p> <blockquote> <h2>baselineAdjustment</h2> <p>Controls how text baselines are adjusted when text needs to shrink to fit in the label.</p> <pre><code>@property(nonatomic) UIBaselineAdjustment baselineAdjustment </code></pre> <h3>Discussion</h3> <p>If the <code>adjustsFontSizeToFitWidth</code> property is set to <code>YES</code>, this property controls the behavior of the text baselines in situations where adjustment of the font size is required. The default value of this property is <code>UIBaselineAdjustment</code><strong><code>AlignBaselines</code></strong>. This property is effective only when the <code>numberOfLines</code> property is set to <code>1</code>.</p> </blockquote> <p>and</p> <blockquote> <p><code>UIBaselineAdjustmentAlignCenters</code><br> Adjust text based relative to the center of its bounding box.</p> </blockquote> <p><strong>EDIT: adding a full view-controller that demonstrates this:</strong></p> <pre><code>@interface TSViewController : UIViewController @end @implementation TSViewController - (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla { UILabel* label = [[UILabel alloc] initWithFrame: f]; label.baselineAdjustment = bla; label.adjustsFontSizeToFitWidth = YES; label.font = [UIFont fontWithName: @"Courier" size: 200]; label.text = @"00"; label.textAlignment = NSTextAlignmentCenter; label.backgroundColor = [UIColor lightGrayColor]; label.userInteractionEnabled = YES; [self.view addSubview: label]; UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)]; centerline.backgroundColor = [UIColor redColor]; [self.view addSubview: centerline]; UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]; [label addGestureRecognizer: tgr]; } - (void) viewDidLoad { [super viewDidLoad]; [self addLabelWithFrame: CGRectMake(0, 0, 320, 200) baselineAdjustment: UIBaselineAdjustmentAlignCenters]; [self addLabelWithFrame: CGRectMake(0, 220, 320, 200) baselineAdjustment: UIBaselineAdjustmentAlignBaselines]; } - (void) onTap: (UITapGestureRecognizer*) tgr { UILabel* label = (UILabel*)tgr.view; NSString* t = [label.text stringByAppendingString: @":00"]; label.text = t; } @end </code></pre>
18,165,863
Multirow axis labels with nested grouping variables
<p>I would like the levels of two different nested grouping variables to appear on separate lines below the plot, and not in the legend. What I have right now is this code:</p> <pre><code>data &lt;- read.table(text = "Group Category Value S1 A 73 S2 A 57 S1 B 7 S2 B 23 S1 C 51 S2 C 87", header = TRUE) ggplot(data = data, aes(x = Category, y = Value, fill = Group)) + geom_bar(position = 'dodge') + geom_text(aes(label = paste(Value, "%")), position = position_dodge(width = 0.9), vjust = -0.25) </code></pre> <p><img src="https://i.stack.imgur.com/3Vbu6.png" alt="enter image description here"></p> <p>What I would like to have is something like this:</p> <p><img src="https://i.stack.imgur.com/kFD2I.png" alt="enter image description here"></p> <p>Any ideas?</p>
18,167,422
6
6
null
2013-08-10 20:04:08.147 UTC
27
2019-09-21 04:29:18.643 UTC
2016-02-23 14:12:54.743 UTC
null
1,851,712
null
2,224,598
null
1
48
r|ggplot2|bar-chart|axis-labels
34,720
<p>You can create a custom element function for <code>axis.text.x</code>. </p> <p><img src="https://i.stack.imgur.com/D60lu.png" alt="enter image description here"></p> <pre><code>library(ggplot2) library(grid) ## create some data with asymmetric fill aes to generalize solution data &lt;- read.table(text = "Group Category Value S1 A 73 S2 A 57 S3 A 57 S4 A 57 S1 B 7 S2 B 23 S3 B 57 S1 C 51 S2 C 57 S3 C 87", header=TRUE) # user-level interface axis.groups = function(groups) { structure( list(groups=groups), ## inheritance since it should be a element_text class = c("element_custom","element_blank") ) } # returns a gTree with two children: # the categories axis # the groups axis element_grob.element_custom &lt;- function(element, x,...) { cat &lt;- list(...)[[1]] groups &lt;- element$group ll &lt;- by(data$Group,data$Category,I) tt &lt;- as.numeric(x) grbs &lt;- Map(function(z,t){ labs &lt;- ll[[z]] vp = viewport( x = unit(t,'native'), height=unit(2,'line'), width=unit(diff(tt)[1],'native'), xscale=c(0,length(labs))) grid.rect(vp=vp) textGrob(labs,x= unit(seq_along(labs)-0.5, 'native'), y=unit(2,'line'), vp=vp) },cat,tt) g.X &lt;- textGrob(cat, x=x) gTree(children=gList(do.call(gList,grbs),g.X), cl = "custom_axis") } ## # gTrees don't know their size grobHeight.custom_axis = heightDetails.custom_axis = function(x, ...) unit(3, "lines") ## the final plot call ggplot(data=data, aes(x=Category, y=Value, fill=Group)) + geom_bar(position = position_dodge(width=0.9),stat='identity') + geom_text(aes(label=paste(Value, "%")), position=position_dodge(width=0.9), vjust=-0.25)+ theme(axis.text.x = axis.groups(unique(data$Group)), legend.position="none") </code></pre>
17,857,304
Vertically aligning text next to a radio button
<p>This is a basic CSS question, I have a radio button with a small text label after it. I want the text to appear centered vertically but the text is always aligned with the button of the radio button in my case.</p> <pre><code>&lt;p&gt;&lt;input type="radio" id="opt1" name="opt1" value="1" /&gt;A label&lt;/p&gt; </code></pre> <p>Here is a Jsfiddle:</p> <p><a href="http://jsfiddle.net/UnA6j/" rel="noreferrer">http://jsfiddle.net/UnA6j/</a></p> <p>Any suggestions?</p> <p>Thanks,</p> <p>Alan.</p>
17,857,368
10
2
null
2013-07-25 11:53:50.633 UTC
5
2022-07-02 17:11:05.593 UTC
2022-07-02 17:11:05.593 UTC
null
213,269
null
2,269,829
null
1
48
css|radio-button|alignment
116,459
<p>Use it inside a <code>label</code>. Use <code>vertical-align</code> to set it to various values -- <code>bottom</code>, <code>baseline</code>, <code>middle</code> etc.</p> <p><a href="http://jsfiddle.net/UnA6j/5/">http://jsfiddle.net/UnA6j/5/</a></p>
42,084,116
Pushing to a different git repo
<p>I have a repo called <code>react</code>. I cloned it into a different repo locally called <code>different-repo</code>.</p> <p>How can I then get <code>different-repo</code> to push remotely to different-repo because currently it is pushing to <code>react</code>.</p> <p>Effectively I want to clone many times from <code>react</code> into different named repos but then when i push from those repos they push to their own repo.</p>
42,084,519
4
4
null
2017-02-07 07:31:04.21 UTC
18
2022-04-26 19:46:54.89 UTC
null
null
null
null
6,882,762
null
1
32
git|github
55,118
<p>You have to add an other <code>remote</code>. Usually, you have an <code>origin</code> remotes, which points to the github (maybe bitbucket) repository you cloned it from. Here's a few example of what it is:</p> <ul> <li><code>https://github.com/some-user/some-repo</code> (the <code>.git</code> is optional)</li> <li><code>[email protected]:some-user/some-repo</code> (this is ssh, it allows you to push/pull without having to type your ids every single time)</li> <li><code>C:/some/folder/on/your/computer</code> Yes! You can push to an other directory on your own computer.</li> </ul> <p>So, when you</p> <pre><code>$ git push origin master </code></pre> <p><code>origin</code> is replaced with it's value: the url</p> <p>So, it's basically just a <strong>shortcut</strong>. You could type the url yourself each time, it'd do the same!</p> <p><strong>Note</strong>: you can list all your <code>remote</code>s by doing <code>git remote -v</code>.</p> <h2>For your problem</h2> <blockquote> <p>How can I then get different-repo to push remotely to different-repo because currently it is pushing to react.</p> </blockquote> <p>I'm guessing you want to create a second repository, right? Well, you can create an other <code>remote</code> (or replace the current <code>origin</code>) with the url to this repo!</p> <h3>Add an other <code>remote</code> — recommended</h3> <pre><code>git remote add &lt;remote-name&gt; &lt;url&gt; </code></pre> <p>So, for example:</p> <pre><code>$ git remote add different-repo https://github.com/your-username/your-repo </code></pre> <p>And then, just</p> <pre><code>$ git push different-repo master </code></pre> <h3>Change the <code>origin</code> <code>remote</code></h3> <pre><code>git remote set-url &lt;remote-name&gt; &lt;url&gt; </code></pre> <p>So</p> <pre><code>git remote set-url origin https://github.com/your-username/your-repo </code></pre>
7,000,078
What exactly does glEnableVertexAttribArray do?
<p>I was reading: <em><a href="https://nicolbolas.github.io/oldtut/Basics/Tut01%20Dissecting%20Display.html" rel="nofollow noreferrer">Dissecting Display, Chapter 1. Hello, Triangle!</a></em>.</p> <p>What exactly does <code>glEnableVertexAttribArray</code> do? I <em>think</em> it enables the use of a given VBO, but I am not sure.</p> <p>I thought that is what <code>glEnableClientState(GL_VERTEX_ARRAY)</code> did.</p>
7,000,331
3
0
null
2011-08-09 17:12:06.217 UTC
20
2022-03-31 10:39:29.06 UTC
2022-03-31 10:33:49.41 UTC
null
11,573,842
null
514,773
null
1
59
opengl
42,499
<blockquote> <p>I have been reading: <em><a href="https://nicolbolas.github.io/oldtut/Basics/Tut01%20Dissecting%20Display.html" rel="nofollow noreferrer">Dissecting Display, Chapter 1. Hello, Triangle!.</a></em></p> </blockquote> <p>Then please read the <em>next</em> page; I explain exactly what it does there ;)</p> <p>If I may quote myself:</p> <blockquote> <p>We assigned the attribute index of the position attribute to <code>0</code> in the vertex shader, so the call to <code>glEnableVertexAttribArray(0)</code> enables the attribute index for the position attribute. [...] If the attribute is not enabled, it will not be used during rendering.</p> </blockquote>
15,981,465
c++ command line compilation with gcc
<p>I am trying to use a text editor instead of code::blocks to write some c++ code. Just wrote a "hello world" program. </p> <p>My code::blocks ide uses the gcc compiler that I installed, but I want to learn how to do it at a bit of a lower level. I read a few tutorials that said all I have to do is open a command prompt and type:</p> <pre><code>gcc helloWorld.cpp -o helloWOrld </code></pre> <p>but i get an error saying "gcc" is not a recognized anything. </p> <p>What do i do to make it work?</p>
15,981,617
4
5
null
2013-04-12 21:52:42.247 UTC
4
2015-10-10 04:39:45.7 UTC
2013-04-13 03:19:08.387 UTC
user405725
null
null
2,082,321
null
1
7
c++|gcc|windows-7|command-line|mingw
57,974
<p>If you can compile with code:blocks, than probably it ships out with compiler.</p> <p>You need to find a path to the compiler (probably somewhere in C:\Program Files\CodeBlocks...) The file name is something like mingw-gcc.exe or mingw-g++.exe I believe also, that you can find this path in IDE settings.</p> <p>When you know the path and filename, just add the path to the system PATH variable and call gccfilename.exe </p> <p>to compile c++ programms run g++filename.exe </p> <p>Also you can run simple compilation without modifying PATH: just run "c:\Full path to compiler\compiler.exe" </p>
19,189,522
What does 'killed' mean when processing a huge CSV with Python, which suddenly stops?
<p>I have a Python script that imports a large CSV file and then counts the number of occurrences of each word in the file, then exports the counts to another CSV file.</p> <p>But what is happening is that once that counting part is finished and the exporting begins it says <code>Killed</code> in the terminal.</p> <p>I don't think this is a memory problem (if it was I assume I would be getting a memory error and not <code>Killed</code>).</p> <p>Could it be that the process is taking too long? If so, is there a way to extend the time-out period so I can avoid this?</p> <p>Here is the code:</p> <pre><code>csv.field_size_limit(sys.maxsize) counter={} with open("/home/alex/Documents/version2/cooccur_list.csv",'rb') as file_name: reader=csv.reader(file_name) for row in reader: if len(row)&gt;1: pair=row[0]+' '+row[1] if pair in counter: counter[pair]+=1 else: counter[pair]=1 print 'finished counting' writer = csv.writer(open('/home/alex/Documents/version2/dict.csv', 'wb')) for key, value in counter.items(): writer.writerow([key, value]) </code></pre> <p>And the <code>Killed</code> happens after <code>finished counting</code> has printed, and the full message is: </p> <pre><code>killed (program exited with code: 137) </code></pre>
19,192,507
5
3
null
2013-10-04 19:44:44.837 UTC
19
2022-08-23 08:04:34.573 UTC
2022-08-23 08:04:34.573 UTC
null
11,154,841
null
1,893,354
null
1
135
python|csv|etl|kill
167,549
<p>Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is <code>SIGKILL</code>. This also explains the <code>killed</code> message. The question is, why did you receive that signal?</p> <p>The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.</p> <p>As I commented earlier, one reason you might hit a memory limit after printing <code>finished counting</code> is that your call to <code>counter.items()</code> in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use <code>counter.iteritems()</code> which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.</p> <p>So, I'd suggest trying this, as your final loop:</p> <pre><code>for key, value in counter.iteritems(): writer.writerow([key, value]) </code></pre> <p>Note that in Python 3, <code>items</code> returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces <code>iteritems</code>, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.</p>
51,280,090
What is AndroidX?
<p>I am reading about a room library of Android. I see they changed package <code>android</code> to <code>androidx</code>. I did not understand that. Can someone explain, please?</p> <pre><code>implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" </code></pre> <p>Even this is available with the <code>android</code> package also.</p> <pre><code>implementation "android.arch.persistence.room:runtime:$room_version" annotationProcessor "android.arch.persistence.room:compiler:$room_version" </code></pre> <ul> <li>What was in need of packaging new support libraries in <code>androidx</code> instead of <code>android</code>?</li> <li>Use case and affect factors in existing projects.</li> </ul>
52,517,772
10
4
null
2018-07-11 07:55:47.397 UTC
80
2022-07-02 23:24:09.43 UTC
2019-11-13 11:12:50.427 UTC
null
63,550
null
6,891,563
null
1
302
android|android-architecture-components|android-jetpack|androidx
191,044
<h3>AndroidX - Android Extension Library</h3> <p>From <a href="https://developer.android.com/topic/libraries/support-library/androidx-overview" rel="noreferrer">AndroidX documentation</a></p> <blockquote> <p>We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.</p> </blockquote> <h2>Need of AndroidX</h2> <p>AndroidX is a redesigned library to make package names more clear. So from now on <strong>android</strong> hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of <strong>androidx</strong> (makes more sense). So from now on all the new development will be updated in androidx.</p> <p>com.android.support.** : <strong>androidx.</strong><br /> com.android.support:appcompat-v7 : <strong>androidx.appcompat:appcompat</strong> com.android.support:recyclerview-v7 : <strong>androidx.recyclerview:recyclerview</strong> com.android.support:design : <strong>com.google.android.material:material</strong></p> <p><strong><a href="https://developer.android.com/topic/libraries/support-library/refactor" rel="noreferrer">Complete Artifact mappings for AndroidX packages</a></strong></p> <h3>AndroidX uses <a href="https://semver.org/" rel="noreferrer">Semantic-version</a></h3> <p>Previously, <code>support library</code> used the SDK version but AndroidX uses the <a href="https://semver.org/" rel="noreferrer"><code>Semantic-version</code></a>. It’s going to re-version from 28.0.0 → 1.0.0.</p> <h2>How to migrate current project</h2> <p>In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to <code>AndroidX</code>. This refactor all packages automatically.</p> <p><strong>Before you migrate, it is strongly recommended to backup your project.</strong></p> <blockquote> <h3>Existing project</h3> </blockquote> <ul> <li>Android Studio &gt; Refactor Menu &gt; Migrate to AndroidX...</li> <li>It will analyze and will open Refractor window in bottom. Accept changes to be done.</li> </ul> <p><a href="https://i.stack.imgur.com/DEV2M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DEV2M.png" alt="image" /></a></p> <blockquote> <h3>New project</h3> </blockquote> <p>Put these flags in your <code>gradle.properties</code></p> <pre><code>android.enableJetifier=true android.useAndroidX=true </code></pre> <p>Check @<a href="https://developer.android.com/topic/libraries/support-library/refactor" rel="noreferrer">Library mappings for equal AndroidX package</a>.</p> <p>Check @<a href="https://developer.android.com/topic/libraries/support-library/refactor" rel="noreferrer">Official page of Migrate to AndroidX</a></p> <h3><a href="https://stackoverflow.com/a/52518822/6891563">What is Jetifier?</a></h3> <h3>Bugs of migrating</h3> <ul> <li>If you build app, and find some errors after migrating, then you need to fix those minor errors. You will not get stuck there, because that can be easily fixed.</li> <li>3rd party libraries are not converted to AndroidX in directory, but they get converted at run time by <a href="http://www.akexorcist.com/2018/07/android-jetifier-binary-migration-tool.html" rel="noreferrer">Jetifier</a>, so don't worry about compile time errors, your app will run perfectly.</li> </ul> <h3>Support 28.0.0 is last release?</h3> <p>From <a href="https://developer.android.com/topic/libraries/support-library/revisions" rel="noreferrer">Android Support Revision 28.0.0</a></p> <blockquote> <p>This will be the <strong>last feature release under the android.support packaging</strong>, and developers are encouraged to migrate to AndroidX 1.0.0</p> </blockquote> <p>So go with AndroidX, because Android will update only androidx package from now.</p> <h3>Further Reading</h3> <p><a href="https://developer.android.com/topic/libraries/support-library/androidx-overview" rel="noreferrer">https://developer.android.com/topic/libraries/support-library/androidx-overview</a></p> <p><a href="https://android-developers.googleblog.com/2018/05/hello-world-androidx.html" rel="noreferrer">https://android-developers.googleblog.com/2018/05/hello-world-androidx.html</a></p>
41,137,596
How To Insert Incrementing Numbers with words by Multicursor in jetbrains IDE(IntelliJ IDEA)?
<p>I want to add Incrementing Numbers with words by Multicursor in jetbrains IDE(IntelliJ IDEA) .</p> <p>Is there any way to do it by Live template? I want to do things like this image :</p> <p><a href="https://i.stack.imgur.com/HTkLr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HTkLr.png" alt="enter image description here"></a></p>
41,152,483
3
3
null
2016-12-14 08:07:27.483 UTC
8
2022-04-13 20:16:28.3 UTC
2016-12-14 09:19:01.57 UTC
null
147,024
null
4,549,082
null
1
52
intellij-idea|live-templates
10,130
<p>You could use <a href="https://plugins.jetbrains.com/plugin/2162?pr=idea" rel="noreferrer">String Manipulation plugin</a> to do that (<code>Increment/Decrement | Increment duplicates</code> or <code>Create sequence</code>).</p> <p><a href="https://i.stack.imgur.com/IxrLt.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/IxrLt.gif" alt="" /></a></p>
5,216,891
Django: what is the difference (rel & field)
<p>What is the difference between Django's <code>models.ManyToManyField</code> and <code>models.ManyToManyRel</code>? I'm confused about this stuff.</p>
13,583,807
2
3
null
2011-03-07 07:17:24.47 UTC
2
2020-08-14 21:20:47.963 UTC
2015-03-02 16:38:45.763 UTC
null
542,270
null
256,465
null
1
58
python|django|entity-relationship
11,856
<p>ManyToManyRel is used by the ManyToManyField to implement the relationship object for the Field base class which it extends. If you were to create a new field class that extended the Field class and contained a many-to-many relationship you might find this class convenient but it should not be used in your models (which is where you will see the pop-up suggestion if your editor lists available calls).</p> <p>See class Field @: <a href="https://github.com/django/django/blob/master/django/db/models/fields/__init__.py" rel="noreferrer">https://github.com/django/django/blob/master/django/db/models/fields/__init__.py</a> class ManyToManyRel &amp; class ManyToManyField @: <a href="https://github.com/django/django/blob/master/django/db/models/fields/related.py" rel="noreferrer">https://github.com/django/django/blob/master/django/db/models/fields/related.py</a></p> <p><em>I am glad that the vast majority of the questions here are questions that can be answered by looking at reference material and documentation. Researching and sharing ideas and digging into code that is "not for external use" is the fun. I know how to start answering this question, if i didn't i would not have written anything. Good question dude!</em></p>
1,168,244
Why doesn't Java tell you which pointer is null?
<p>I've always wondered why the JVM doesn't tell you <em>which</em> pointer (or more precisely, which variable) is null when a <code>NullPointerException</code> is thrown.</p> <p>A line number isn't specific enough because the offending line can often contain numerous variables that could have caused the error.</p> <p>Is there any compiler or JVM flag that would make these exception messages more useful?</p>
1,168,550
7
4
null
2009-07-22 21:05:39.793 UTC
6
2020-10-28 07:13:33.083 UTC
null
null
null
null
100,335
null
1
29
java|debugging|nullpointerexception
2,333
<p>It's because the dereference always happens when there is no name available. The value is loaded onto the operand stack, and is then passed to one of the JRE opcodes that dereferences it. However, the operand stack does not have a name to associate with a null value. All it has is 'null'. With some clever runtime tracking code, a name can be derived, but that would add overhead with limited value. </p> <p>Because of this, there is no JRE option that will turn on extra information for null pointer exceptions.</p> <p>In this example, the reference is stored in local slot 1, which maps to a local variable name. But the dereference happens in the invokevirtual instruction, which only sees a 'null' value on the stack, and then throws an exception:</p> <pre><code>15 aload_1 16 invokevirtual #5 </code></pre> <p>Equally valid would be an array load followed by a dereference, but in this case there is no name to map to the 'null' value, just an index off of another value.</p> <pre><code>76 aload 5 78 iconst_0 79 aaload 80 invokevirtual #5 </code></pre> <p>You can't allocate the names statically to each instruction either - this example produces a lot of bytecode, but you can see that the dereference instruction will receive either objA or objB, and you would need to track this dynamically to report the right one, as both variables flow to the same dereference instruction:</p> <pre><code>(myflag ? objA : objB).toString() </code></pre>
908,903
Scope of the Java System Properties
<p>In Java we use System.setProperty() method to set some system properties. According to <a href="http://blogs.oracle.com/foo/entry/monitored_system_setproperty" rel="noreferrer">this article</a> the use of system properties is bit tricky.</p> <blockquote> <p>System.setProperty() can be an evil call. </p> <ul> <li>It is 100% thread-hostile</li> <li>It contains super-global variables</li> <li>It is extremely difficult to debug when these variables mysteriously change at runtime.</li> </ul> </blockquote> <p>My questions are as follows.</p> <ol> <li><p>How about the scope of the system properties? Are they specific for each and every Virtual Machine or they have a "Super Global nature" that shares the same set of properties over Each and every virtual machine instance? I guess the option 1</p></li> <li><p>Are there any tools that can be used to monitor the runtime changes for detect the changes in System properties. (Just for the ease of problem detection)</p></li> </ol>
908,965
7
0
null
2009-05-26 04:17:12.177 UTC
12
2018-06-29 04:54:19.053 UTC
2017-07-27 05:34:31.857 UTC
null
207,421
null
76,465
null
1
56
java|jvm|system-properties
39,441
<p><strong>Scope of the System properties</strong></p> <p>At least from reading the API Specifications for the <a href="http://java.sun.com/javase/6/docs/api/java/lang/System.html#setProperties(java.util.Properties)" rel="noreferrer"><code>System.setProperties</code></a> method, I was unable to get an answer whether the system properties are shared by all instances of the JVM or not.</p> <p>In order to find out, I wrote two quick programs that will set the system property via <code>System.setProperty</code>, using the same key, but different values:</p> <pre><code>class T1 { public static void main(String[] s) { System.setProperty("dummy.property", "42"); // Keep printing value of "dummy.property" forever. while (true) { System.out.println(System.getProperty("dummy.property")); try { Thread.sleep(500); } catch (Exception e) {} } } } class T2 { public static void main(String[] s) { System.setProperty("dummy.property", "52"); // Keep printing value of "dummy.property" forever. while (true) { System.out.println(System.getProperty("dummy.property")); try { Thread.sleep(500); } catch (Exception e) {} } } } </code></pre> <p>(Beware that running the two programs above will make them go into an infinite loop!)</p> <p>It turns out, when running the two programs using two separate <code>java</code> processes, the value for the property set in one JVM process does not affect the value of the other JVM process.</p> <p>I should add that this is the results for using Sun's JRE 1.6.0_12, and this behavior isn't defined at least in the API specifications (or I haven't been able to find it), the behaviors may vary.</p> <p><strong>Are there any tools to monitor runtime changes</strong></p> <p>Not to my knowledge. However, if one does need to check if there were changes to the system properties, one can hold onto a copy of the <code>Properties</code> at one time, and compare it with another call to <code>System.getProperties</code> -- after all, <a href="http://java.sun.com/javase/6/docs/api/java/util/Properties.html" rel="noreferrer"><code>Properties</code></a> is a subclass of <a href="http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a>, so comparison would be performed in a similar manner.</p> <p>Following is a program that demonstrates a way to check if there has been changes to the system properties. Probably not an elegant method, but it seems to do its job:</p> <pre><code>import java.util.*; class CheckChanges { private static boolean isDifferent(Properties p1, Properties p2) { Set&lt;Map.Entry&lt;Object, Object&gt;&gt; p1EntrySet = p1.entrySet(); Set&lt;Map.Entry&lt;Object, Object&gt;&gt; p2EntrySet = p2.entrySet(); // Check that the key/value pairs are the same in the entry sets // obtained from the two Properties. // If there is an difference, return true. for (Map.Entry&lt;Object, Object&gt; e : p1EntrySet) { if (!p2EntrySet.contains(e)) return true; } for (Map.Entry&lt;Object, Object&gt; e : p2EntrySet) { if (!p1EntrySet.contains(e)) return true; } return false; } public static void main(String[] s) { // System properties prior to modification. Properties p = (Properties)System.getProperties().clone(); // Modification of system properties. System.setProperty("dummy.property", "42"); // See if there was modification. The output is "false" System.out.println(isDifferent(p, System.getProperties())); } } </code></pre> <p><strong>Properties is not thread-safe?</strong></p> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a> <em>is thread-safe</em>, so I was expecting that <code>Properties</code> would be as well, and in fact, the API Specifications for the <a href="http://java.sun.com/javase/6/docs/api/java/util/Properties.html" rel="noreferrer"><code>Properties</code></a> class confirms it:</p> <blockquote> <p>This class is thread-safe: multiple threads can share a single <code>Properties</code> object without the need for external synchronization., <a href="http://java.sun.com/javase/6/docs/api/serialized-form.html#java.util.Properties" rel="noreferrer">Serialized Form</a></p> </blockquote>
62,936
What does the number in parentheses shown after Unix command names in manpages mean?
<p>For example: <code>man(1)</code>, <code>find(3)</code>, <code>updatedb(2)</code>? </p> <p>What do the numbers in parentheses (Brit. "brackets") mean?</p>
62,972
7
2
null
2008-09-15 13:37:47.13 UTC
170
2021-09-28 15:48:37.91 UTC
2020-03-21 16:04:15.503 UTC
null
264,325
duckyflip
7,370
null
1
629
linux|unix|command-line|manpage
53,722
<p>It's the section that the man page for the command is assigned to.</p> <p>These are split as</p> <ol> <li>General commands</li> <li>System calls</li> <li>C library functions</li> <li>Special files (usually devices, those found in /dev) and drivers</li> <li>File formats and conventions</li> <li>Games and screensavers</li> <li>Miscellanea</li> <li>System administration commands and daemons</li> </ol> <p>Original descriptions of each section can be seen in the <a href="https://web.archive.org/web/20170601064537/http://plan9.bell-labs.com/7thEdMan/v7vol1.pdf" rel="noreferrer">Unix Programmer's Manual</a> (page ii).</p> <p>In order to access a man page given as &quot;foo(5)&quot;, run:</p> <pre class="lang-sh prettyprint-override"><code>man 5 foo </code></pre>
28,002
Regular cast vs. static_cast vs. dynamic_cast
<p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p> <pre><code>MyClass *m = (MyClass *)ptr; </code></pre> <p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p> <pre><code>MyClass *m = (MyClass *)ptr; MyClass *m = static_cast&lt;MyClass *&gt;(ptr); MyClass *m = dynamic_cast&lt;MyClass *&gt;(ptr); </code></pre>
1,255,015
8
4
null
2008-08-26 13:20:55.357 UTC
968
2022-07-11 21:21:22.943 UTC
2014-05-15 15:15:29.143 UTC
null
46,642
Graeme
1,821
null
1
1,963
c++|pointers|casting
835,314
<h2>static_cast</h2> <p><code>static_cast</code> is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. <code>static_cast</code> performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:</p> <pre><code>void func(void *data) { // Conversion from MyClass* -&gt; void* is implicit MyClass *c = static_cast&lt;MyClass*&gt;(data); ... } int main() { MyClass c; start_thread(&amp;func, &amp;c) // func(&amp;c) will be called .join(); } </code></pre> <p>In this example, you know that you passed a <code>MyClass</code> object, and thus there isn't any need for a runtime check to ensure this.</p> <h2>dynamic_cast</h2> <p><code>dynamic_cast</code> is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a <code>bad_cast</code> exception is thrown in that case).</p> <pre><code>if (JumpStm *j = dynamic_cast&lt;JumpStm*&gt;(&amp;stm)) { ... } else if (ExprStm *e = dynamic_cast&lt;ExprStm*&gt;(&amp;stm)) { ... } </code></pre> <p>You can <strong>not</strong> use <code>dynamic_cast</code> for downcast (casting to a derived class) <strong>if</strong> the argument type is not polymorphic. For example, the following code is not valid, because <code>Base</code> doesn't contain any virtual function:</p> <pre><code>struct Base { }; struct Derived : Base { }; int main() { Derived d; Base *b = &amp;d; dynamic_cast&lt;Derived*&gt;(b); // Invalid } </code></pre> <p>An &quot;up-cast&quot; (cast to the base class) is always valid with both <code>static_cast</code> and <code>dynamic_cast</code>, and also without any cast, as an &quot;up-cast&quot; is an implicit conversion (assuming the base class is accessible, i.e. it's a <code>public</code> inheritance).</p> <h2>Regular Cast</h2> <p>These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering <code>dynamic_cast</code>. Needless to say, this is much more powerful as it combines all of <code>const_cast</code>, <code>static_cast</code> and <code>reinterpret_cast</code>, but it's also unsafe, because it does not use <code>dynamic_cast</code>.</p> <p>In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the &quot;equivalent&quot; <code>static_cast</code> sequence would give you a compile-time error for that.</p> <p>Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.</p>
591,667
Linux equivalent of the DOS "start" command?
<p>I'm writing a ksh script and I have to run a executable at a separate Command Prompt window.</p>
591,687
9
0
null
2009-02-26 17:52:06.03 UTC
10
2021-10-22 00:53:50.953 UTC
2012-09-12 10:43:33.173 UTC
epatel
40,342
Alceu Costa
64,138
null
1
24
windows|linux|scripting
27,251
<p>I believe you mean something like <code>xterm -e your.sh &amp;</code></p> <p>Don't forget the final <code>&amp;</code> </p>
275,891
jQuery hover and class selector
<p>I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:</p> <pre><code>&lt;div id=&quot;menu&quot;&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.menuItem{ display:inline; height:30px; width:100px; background-color:#000; } </code></pre> <p>Javascript:</p> <pre><code>$('.menuItem').hover( function(){ $(this).css('background-color', '#F00'); }, function(){ $(this).css('background-color', '#000'); }); </code></pre> <p><strong>EDIT:</strong> I forgot to say that I had reasons not to want to use the css way.</p> <p>And I indeed forgot to check if the DOM was loaded.</p>
275,912
10
0
null
2008-11-09 13:00:20.427 UTC
3
2020-09-19 17:08:27.953 UTC
2020-09-19 17:08:27.953 UTC
Pim Jager
13,368,658
Pim Jager
35,197
null
1
26
javascript|jquery|html|css
118,322
<p>Your code looks fine to me.</p> <p>Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:</p> <pre><code>$(function() { $('.menuItem').hover( function(){ $(this).css('background-color', '#F00'); }, function(){ $(this).css('background-color', '#000'); }); }); </code></pre>
47,972
What are some advantages of duck-typing vs. static typing?
<p>I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. </p> <p>Groovy gives me the ability to <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck-type</a>, but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it?</p> <p>I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp.</p>
275,998
10
1
null
2008-09-07 00:28:08.063 UTC
2
2018-04-18 06:53:44.197 UTC
2009-02-10 16:41:21.26 UTC
codeLes
3,030
codeLes
3,030
null
1
30
groovy|duck-typing
13,532
<p>Next, which is better: EMACS or vi? This is one of the running religious wars.</p> <p>Think of it this way: any program that is <em>correct</em>, will be correct if the language is statically typed. What static typing does is let the compiler have enough information to detect type mismatches at compile time instead of run time. This can be an annoyance if your doing incremental sorts of programming, although (I maintain) if you're thinking clearly about your program it doesn't much matter; on the other hand, if you're building a really big program, like an operating system or a telephone switch, with dozens or hundreds or thousands of people working on it, or with really high reliability requirements, then having he compiler be able to detect a large class of problems for you without needing a test case to exercise just the right code path.</p> <p>It's not as if dynamic typing is a new and different thing: C, for example, is effectively dynamically typed, since I can always cast a <code>foo*</code> to a <code>bar*</code>. It just means it's then my responsibility as a C programmer never to use code that is appropriate on a <code>bar*</code> when the address is really pointing to a <code>foo*</code>. But as a result of the issues with large programs, C grew tools like lint(1), strengthened its type system with <code>typedef</code> and eventually developed a strongly typed variant in C++. (And, of course, C++ in turn developed ways around the strong typing, with all the varieties of casts and generics/templates and with RTTI. </p> <p>One other thing, though --- don't confuse "agile programming" with "dynamic languages". <a href="http://agilemanifesto.org/" rel="noreferrer">Agile programming</a> is about the way people work together in a project: can the project adapt to changing requirements to meet the customers' needs while maintaining a humane environment for the programmers? It can be done with dynamically typed languages, and often is, because they can be more productive (eg, Ruby, Smalltalk), but it can be done, has been done successfully, in C and even assembler. In fact, <a href="http://www.rallydev.com/" rel="noreferrer">Rally Development</a> even uses agile methods (SCRUM in particular) to do marketing and documentation. </p>
473,797
How to build large applications
<p>I think I've become quite good at the basics of programming (for a variety of languages). I can write a <em>good</em> line of code. I can write a <em>good</em> method. I can write a <em>good</em> class. I can write a <em>good</em> group of classes. I can write <em>good</em> small or medium application.</p> <p>I do not however know how to build a <em>good</em> large application. Particularly in the case where multiple technologies are involved and more are likely to become involved with time. Say a project with a large web front-end, a large server back-end that connects to some other integration back-end and finally a large and complex database. Oh, I've been involved in a few of these applications and I could build one I'm sure. I'm not so sure however that it could qualify as "good". </p> <p>My question is thus for a reference to a book or other good source of reading where I could learn how to distribute and organize code and data for general large projects. For example, would I want to layer things very strictly or would I want to encapsulate it independent units instead? Would I want to try to keep most of the logic in the same pool, or should it just be distributed as it seems most logical when adding whatever feature I'm adding? </p> <p>I've seen lots of general principals on these issues (e.g. No spaghetti code, meatball code...) and read a few excellent articles that discuss the matter but I've never encountered a source which would lead me to concrete <strong>practical</strong> knowledge. I realize the difficulty of the question and so I'd be happy to just hear about the readings that others have found to help them in their quest for such knowledge.</p> <p>As always, thank you for your replies.</p> <blockquote> <p>****Given the debated nature of the definition of "good" code, the term "good" in this context won't be defined (it means whatever you think it ought to mean).</p> </blockquote>
474,228
12
5
null
2009-01-23 17:34:38.07 UTC
28
2019-05-09 04:29:56.907 UTC
2019-05-09 04:29:56.907 UTC
Totophil
8,710,452
null
41,662
null
1
31
architecture|distributed
8,661
<p>As programmers, we like to believe we are smart people, so it's hard to admit that something is too big and complex to even think about all at once. But for a large-scale software project it's true, and the sooner you acknowledge your <strong>finite brain capacity</strong> and start coming up with ways to simplify the problem, the better off you'll be.</p> <p>The other main thing to realise is that you will spend most of your time <strong>changing existing code</strong>. Building the initial codebase is just the honeymoon period -- you need to design your code with the idea in mind that, 6 months later you will be sitting in front of it trying to solve some problem without a clue how this particular module works, even though you wrote it yourself.</p> <p>So, what can we do?</p> <p><strong>Minimise coupling</strong> between unrelated parts of your code. Code is going to change over time in ways you can't anticipate -- there will be showstopper problems integrating with unfamiliar products, requirements changes -- and those will cause ripple-on changes. If you have established stable interfaces and coded to them, you can make any changes you need in the implementation without those changes affecting code that uses the interface. You need to <strong>spend time and effort</strong> developing interfaces that will stand the test of time -- if an interface needs to change too, you're back to square one.</p> <p><strong>Establish automated tests</strong> that you can use for regression testing. Yes, it's a lot of work up front. But it will pay off in the future when you can make a change, run the tests, and establish that <em>it still works</em> without that anxious feeling of wondering if everything will fall over if you commit your latest change to source control.</p> <p><strong>Lay off the tricky stuff.</strong> Every now and then I see some clever C++ template trick and think, "Wow! That's just what my code needs!" But the truth is, the decrease in how readable and readily understandable the code becomes is often simply not worth the increased genericity. If you're someone like me whose natural inclination is to try to solve every problem in as general a manner as possible, you need to learn to restrain it until you actually come across the <em>need</em> for that general solution. If that <em>need</em> arises, you might have to rewrite some code -- it's no big deal.</p>
936,304
Binding to static property
<p>I'm having a hard time binding a simple static string property to a TextBox. </p> <p>Here's the class with the static property:</p> <pre class="lang-csharp prettyprint-override"><code>public class VersionManager { private static string filterString; public static string FilterString { get { return filterString; } set { filterString = value; } } } </code></pre> <p>In my xaml, I just want to bind this static property to a TextBox:</p> <pre class="lang-XML prettyprint-override"><code>&lt;TextBox&gt; &lt;TextBox.Text&gt; &lt;Binding Source="{x:Static local:VersionManager.FilterString}"/&gt; &lt;/TextBox.Text&gt; &lt;/TextBox&gt; </code></pre> <p>Everything compiles, but at run time, I get the following exception:</p> <blockquote> <p>Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Markup.StaticExtension'. Error at object 'System.Windows.Data.Binding' in markup file 'BurnDisk;component/selectversionpagefunction.xaml' Line 57 Position 29.</p> </blockquote> <p>Any idea what I'm doing wrong?</p>
938,634
12
0
null
2009-06-01 19:20:48.663 UTC
47
2022-03-19 20:08:12.053 UTC
2019-10-21 14:45:58.2 UTC
null
1,506,454
null
76,939
null
1
192
wpf|xaml|data-binding
195,332
<p>If the binding needs to be two-way, you must supply a path.</p> <p>There's a trick to do two-way binding on a static property, provided the class is not static : declare a dummy instance of the class in the resources, and use it as the source of the binding.</p> <pre><code>&lt;Window.Resources&gt; &lt;local:VersionManager x:Key=&quot;versionManager&quot;/&gt; &lt;/Window.Resources&gt; ... &lt;TextBox Text=&quot;{Binding Source={StaticResource versionManager}, Path=FilterString}&quot;/&gt; </code></pre>
695,811
Pitfalls of code coverage
<p>I'm looking for real world examples of some bad side effects of code coverage.</p> <p>I noticed this happening at work recently because of a policy to achieve 100% code coverage. Code quality has been improving for sure but conversely the testers seem to be writing more lax test plans because 'well the code is fully unit tested'. Some logical bugs managed to slip through as a result. They were a REALLY BIG PAIN to debug because 'well the code is fully unit tested'.</p> <p>I think that was partly because our tool did statement coverage only. Still, it could have been time better spent.</p> <p>If anyone has other negative side effects of having a code coverage policy please share. I'd like to know what kind of other 'problems' are happening out there in the real-world.</p> <p>Thanks in advance.</p> <p>EDIT: Thanks for all the really good responses. There are a few which I would mark as the answer but I can only mark one unfortunately.</p>
695,888
13
4
null
2009-03-30 02:04:22.95 UTC
15
2012-04-06 17:54:01.203 UTC
2012-04-06 17:54:01.203 UTC
fung
50,776
fung
8,280
null
1
32
unit-testing|code-coverage
6,000
<p>In a sentence: Code coverage tells you what you definitely <strong>haven't</strong> tested, not what you <strong>have.</strong></p> <p>Part of building a valuable unit test suite is finding the most important, high-risk code and asking hard questions of it. You want to make sure the tough stuff works as a priority. Coverage figures have no notion of the 'importance' of code, nor the quality of tests. </p> <p>In my experience, many of the most important tests you will ever write are the tests that barely add any coverage at all (edge cases that add a few extra % here and there, but find loads of bugs). </p> <p>The problem with setting hard and (potentially counter-productive) coverage targets is that developers may have to start bending over backwards to test their code. There's making code testable, and then there's just torture. If you hit 100% coverage with great tests then that's fantastic, but in most situations the extra effort is just not worth it.</p> <p>Furthermore, people start obsessing/fiddling with numbers rather than focussing on the quality of the tests. I've seen badly written tests that have 90+% coverage, just as I've seen excellent tests that only have 60-70% coverage. </p> <p>Again, I tend to look at coverage as an indicator of what definitely <strong>hasn't</strong> been tested.</p>
84,209
Adding a guideline to the editor in Visual Studio
<p><strong>Introduction</strong></p> <p>I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters.</p> <p>Below is a guide to enable these so called <em>guidelines</em> for various versions of Visual Studio.</p> <p><strong>Visual Studio 2013 or later</strong></p> <p>Install Paul Harrington's <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459/view/Reviews" rel="noreferrer">Editor Guidelines extension</a>.</p> <p><strong>Visual Studio 2010 and 2012</strong></p> <ol> <li>Install Paul Harrington's Editor Guidelines extension for <a href="http://visualstudiogallery.msdn.microsoft.com/0fbf2878-e678-4577-9fdb-9030389b338c" rel="noreferrer">VS 2010</a> or <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459?SRC=Home" rel="noreferrer">VS 2012</a>.</li> <li>Open the registry at: <br />VS 2010: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor</code> <br />VS 2012: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor</code> <br />and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed.</li> <li>Or install the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91" rel="noreferrer">Guidelines UI</a> extension (which is also a part of the <a href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/" rel="noreferrer">Productivity Power Tools</a>), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly.</li> </ol> <p><strong>Visual Studio 2008 and Other Versions</strong></p> <p>If you are using Visual Studio 2008 open the registry at <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor</code> and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio.</p> <p>This trick also works for various other version of Visual Studio, as long as you use the correct path:</p> <pre><code>2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor 2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor 2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor </code></pre> <p><a href="https://stackoverflow.com/a/332577/11387">This also works in SQL Server 2005 and probably other versions.</a></p>
84,467
13
24
2008-12-05 20:52:42.877 UTC
2008-09-17 15:04:28.45 UTC
131
2022-07-12 17:02:28.59 UTC
2021-05-14 22:43:20.493 UTC
Ash
7,250,285
xsl
11,387
null
1
364
visual-studio|ide|registry
157,358
<p>This is originally from Sara's <a href="https://web.archive.org/web/20160221095812/http://blogs.msdn.com:80/b/saraford/archive/2004/11/15/257953.aspx" rel="nofollow noreferrer">blog</a>.</p> <p>It also works with almost any version of Visual Studio, you just need to change the &quot;8.0&quot; in the registry key to the appropriate version number for your version of Visual Studio.</p> <p>The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)</p> <p>You can also have the guide in multiple columns by listing more than one number after the color specifier:</p> <pre><code>RGB(230,230,230), 4, 80 </code></pre> <p>Puts a white line at column 4 and column 80. This should be the value of a string value <code>Guides</code> in &quot;Text Editor&quot; key (see bellow).</p> <p>Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).</p> <p>Here are the registry keys that I know of:</p> <p><strong>Visual Studio 2010</strong>: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor</p> <p><strong>Visual Studio 2008</strong>: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor</p> <p><strong>Visual Studio 2005</strong>: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor</p> <p><strong>Visual Studio 2003</strong>: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor</p> <p>For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:</p> <ul> <li><p><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c" rel="nofollow noreferrer">http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c</a></p> </li> <li><p><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91" rel="nofollow noreferrer">http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91</a></p> </li> </ul> <p>These are also part of the <a href="https://web.archive.org/web/20110119025922/http://visualstudiogallery.msdn.microsoft.com:80/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef" rel="nofollow noreferrer">Productivity Power Tools</a>, which includes many other very useful extensions.</p>
12,896
parsing raw email in php
<p>I'm looking for good/working/simple to use PHP code for parsing raw email into parts.</p> <p>I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.</p> <p>And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).</p> <p>Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.</p> <p>I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it &quot;right&quot;. This is one of those &quot;wheel&quot; problems that I know has already been solved.</p>
12,965
15
0
null
2008-08-15 23:50:17.527 UTC
13
2021-07-07 02:12:07.057 UTC
2021-07-07 02:12:07.057 UTC
null
13,176,802
Uberfuzzy
314
null
1
34
php|email
58,060
<p>What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with <a href="http://www.faqs.org/rfcs/rfc2822.html" rel="noreferrer">RFC2822</a> to understand the format of the mail, but here's the simplest rules for well formed email:</p> <pre><code>HEADERS\n \n BODY </code></pre> <p>That is, the first blank line (double newline) is the separator between the HEADERS and the BODY. A HEADER looks like this:</p> <pre><code>HSTRING:HTEXT </code></pre> <p>HSTRING always starts at the beginning of a line and doesn't contain any white space or colons. HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.</p> <p>The "BODY" is really just any data that follows the first double newline. (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).</p> <p>So, in really simple, circa-1982 <a href="http://www.faqs.org/rfcs/rfc822.html" rel="noreferrer">RFC822</a> terms, an email looks like this:</p> <pre><code>HEADER: HEADER TEXT HEADER: MORE HEADER TEXT INCLUDING A LINE CONTINUATION HEADER: LAST HEADER THIS IS ANY ARBITRARY DATA (FOR THE MOST PART) </code></pre> <p>Most modern email is more complex than that though. Headers can be encoded for charsets or <a href="http://www.faqs.org/rfcs/rfc2047.html" rel="noreferrer">RFC2047</a> mime words, or a ton of other stuff I'm not thinking of right now. The bodies are really hard to roll your own code for these days to if you want them to be meaningful. Almost all email that's generated by an MUA will be <a href="http://www.faqs.org/rfcs/rfc2045.html" rel="noreferrer">MIME</a> encoded. That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.</p> <p>I hope this helps provide a framework for understanding some of the very elemental buckets of email. If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.</p>
84,882
sudo echo "something" >> /etc/privilegedFile doesn't work
<p>This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.</p> <p>There are a lot of times when I just want to append something to <code>/etc/hosts</code> or a similar file but end up not being able to because both <code>&gt;</code> and <code>&gt;&gt;</code> are not allowed, even with root.</p> <p>Is there someway to make this work without having to <code>su</code> or <code>sudo su</code> into root?</p>
550,808
15
0
null
2008-09-17 16:09:00.84 UTC
197
2020-09-24 14:41:48.923 UTC
2019-03-06 01:57:22.103 UTC
Jim
608,639
null
9,908
null
1
676
bash|shell|scripting|permissions|sudo
259,700
<p>Use <code>tee --append</code> or <code>tee -a</code>.</p> <pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list </code></pre> <p>Make sure to avoid quotes inside quotes.</p> <p>To avoid printing data back to the console, redirect the output to /dev/null.</p> <pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list &gt; /dev/null </code></pre> <p>Remember about the (<code>-a</code>/<code>--append</code>) flag! Just <code>tee</code> works like <code>&gt;</code> and will overwrite your file. <code>tee -a</code> works like <code>&gt;&gt;</code> and will write at the end of the file.</p>
895,110
What is your favorite feature of jQuery?
<p>I just had the jQuery epiphany the other day and still feel like there is tons of power in it that I'm not utilizing.</p> <p>So that said, what is your favorite feature of jQuery that saves you time and/or makes your client side applications that much more cool or powerful?</p>
895,217
16
4
2009-05-21 21:16:52.373 UTC
2009-05-21 20:56:55.47 UTC
10
2009-05-28 19:57:50.807 UTC
null
null
null
null
100,288
null
1
9
jquery
752
<p>My favorite feature of jQuery is how it helped to turned JavaScript from a hated language into a sexy language almost overnight.</p>
562,894
Java: Detect duplicates in ArrayList?
<p>How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?</p> <p>Many thanks, Terry</p> <p><strong>Edit</strong> Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different. I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();</p>
562,906
16
2
null
2009-02-18 21:22:31.11 UTC
26
2019-12-16 11:07:34.01 UTC
2009-02-19 01:14:39.103 UTC
Terry
null
Terry
null
null
1
118
java|arrays|arraylist|duplicates
306,081
<p>Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.</p> <pre><code>List&lt;Integer&gt; list = ...; Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;(list); if(set.size() &lt; list.size()){ /* There are duplicates */ } </code></pre> <p>Update: If I'm understanding your question correctly, you have a 2d array of Block, as in</p> <p>Block table[][];</p> <p>and you want to detect if any row of them has duplicates?</p> <p>In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:</p> <pre><code>for (Block[] row : table) { Set set = new HashSet&lt;Block&gt;(); for (Block cell : row) { set.add(cell); } if (set.size() &lt; 6) { //has duplicate } } </code></pre> <p>I'm not 100% sure of that for syntax, so it might be safer to write it as</p> <pre><code>for (int i = 0; i &lt; 6; i++) { Set set = new HashSet&lt;Block&gt;(); for (int j = 0; j &lt; 6; j++) set.add(table[i][j]); ... </code></pre> <p><code>Set.add</code> returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns <code>false</code> if all you want to know is whether there are any duplicates.</p>
522,563
Accessing the index in 'for' loops
<p>How do I access the index while iterating over a sequence with a <code>for</code> loop?</p> <pre><code>xs = [8, 23, 45] for x in xs: print(&quot;item #{} = {}&quot;.format(index, x)) </code></pre> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code>item #1 = 8 item #2 = 23 item #3 = 45 </code></pre>
522,578
24
1
null
2009-02-06 22:47:54.433 UTC
911
2022-08-08 00:51:54.6 UTC
2022-08-08 00:51:54.6 UTC
hop
523,612
Joan Venge
51,816
null
1
4,845
python|loops|list
3,407,197
<p>Use the built-in function <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="noreferrer" title="enumerate"><code>enumerate()</code></a>:</p> <pre><code>for idx, x in enumerate(xs): print(idx, x) </code></pre> <p>It is <em><a href="https://stackoverflow.com/questions/25011078/what-does-pythonic-mean">non-pythonic</a></em> to manually index via <code>for i in range(len(xs)): x = xs[i]</code> or manually manage an additional state variable.</p> <p>Check out <a href="https://www.python.org/dev/peps/pep-0279/" rel="noreferrer" title="PEP 279">PEP 279</a> for more.</p>
834,303
startsWith() and endsWith() functions in PHP
<p>How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?</p> <p>For example:</p> <pre><code>$str = '|apples}'; echo startsWith($str, '|'); //Returns true echo endsWith($str, '}'); //Returns true </code></pre>
834,355
33
5
null
2009-05-07 12:14:27.567 UTC
274
2022-08-10 20:59:15.693 UTC
2018-02-03 16:31:37.51 UTC
null
479,156
null
49,153
null
1
1,667
php|string
955,780
<h2>PHP 8.0 and higher</h2> <p>Since PHP 8.0 you can use the</p> <p><code>str_starts_with</code> <a href="https://www.php.net/manual/en/function.str-starts-with" rel="noreferrer">Manual</a> and</p> <p><code>str_ends_with</code> <a href="https://www.php.net/manual/en/function.str-ends-with" rel="noreferrer">Manual</a></p> <h5>Example</h5> <p><code>echo str_starts_with($str, '|');</code></p> <h2>PHP before 8.0</h2> <pre class="lang-php prettyprint-override"><code>function startsWith( $haystack, $needle ) { $length = strlen( $needle ); return substr( $haystack, 0, $length ) === $needle; } </code></pre> <pre class="lang-php prettyprint-override"><code>function endsWith( $haystack, $needle ) { $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; } </code></pre>
6,918,989
How to get the _locale variable inside in a Symfony layout?
<p>I'm working with Symfony 2 on a site which having 2 languages, and I want to change patterns of my routes depending on user locale language !</p> <p>Example:</p> <pre><code>user_login_en: pattern: /en/user/login.html defaults: { _controller: SfErrorsAppBundle:User:login, _locale: en } user_login_fr: pattern: /fr/utilisateur/connexion.html defaults: { _controller: SfErrorsAppBundle:User:login, _locale: fr} </code></pre> <p>Inside a template, this is not difficult, i just have to pass the $this->get('session')->getLocale() from the controller to the template...</p> <p>To work, I have to call my routes:</p> <pre><code>$router-&gt;generate('user_login_'.$locale, array()); </code></pre> <p>But inside my layouts, I have of course a menu, and sidebars, which have links... So I want to get the locale variable to use it ! So my question is simple: how to get this variable inside a "layout" template ? Otherwise, have you got any idea to change the pattern depending on the language ?</p> <p>The reasons are that I want beautiful routes for all users, whether they're english or french... And also for a SEO reason !</p>
7,441,612
4
0
null
2011-08-02 21:39:02.35 UTC
7
2014-10-23 10:08:06.49 UTC
null
null
null
null
875,519
null
1
71
templates|layout|routing|translation|symfony
94,390
<p>---<strong>UPDATED FROM THE COMMENTS</strong>---</p> <p>As Symfony 2.1, you must use</p> <pre><code>{{ app.request.locale }} </code></pre> <p>or</p> <pre><code>{{ app.request.getLocale() }} </code></pre> <p>which returns <code>app.request.locale</code> if available and <code>app.request.defaultLocale</code> if <code>app.request.locale</code> is not set.</p>
6,595,259
Fans-only content in facebook with asp.net C# sdk
<p>Hi i'm developing an application in facebook with c# sdk and i want that the user whom liked my page can only use my application. (Like <a href="http://woobox.com/" rel="noreferrer">woobox</a>) </p> <p>I found some solutions in php in <a href="https://developers.facebook.com/docs/authentication/signed_request/" rel="noreferrer">this link</a> but there isn't any source about .net how can i get the liked info in ASP.NET </p> <p>I find another examples in php in <a href="http://thinkdiff.net/facebook/how-to-detect-fan-of-a-facebook-page/" rel="noreferrer">this</a> link again but i can't find c# answer :\</p> <p>Thanks</p>
7,403,427
5
2
null
2011-07-06 10:55:43.57 UTC
10
2011-09-13 14:21:01.927 UTC
2011-09-08 15:46:15.34 UTC
null
331,798
null
331,798
null
1
6
c#|asp.net|facebook-graph-api|facebook-c#-sdk
9,020
<p>You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:</p> <pre><code>if (Request.Params["signed_request"] != null) { string payload = Request.Params["signed_request"].Split('.')[1]; var encoding = new UTF8Encoding(); var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/'); var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '=')); var json = encoding.GetString(base64JsonArray); var o = JObject.Parse(json); var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", ""); var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", ""); var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", ""); } </code></pre> <p>You need to add reference to json libraries in order to parse signed requestin C#, download from <a href="http://json.codeplex.com/" rel="nofollow noreferrer">http://json.codeplex.com/</a></p> <p>Also refere to <a href="https://stackoverflow.com/questions/3433252/how-to-decode-oauth-2-0-for-canvas-signed-request-in-c">How to decode OAuth 2.0 for Canvas signed_request in C#?</a> if you are worndering about signed request.</p>
16,025,138
Call two functions from same onclick
<p><strong>HTML &amp; JS</strong></p> <p>How do I call 2 functions from one onclick event? Here's my code</p> <pre><code> &lt;input id ="btn" type="button" value="click" onclick="pay() cls()"/&gt; </code></pre> <p>the two functions being pay() and cls(). Thanks! </p>
16,025,176
9
2
null
2013-04-15 21:38:48.477 UTC
39
2016-07-19 11:17:55.013 UTC
2014-08-22 03:10:48.383 UTC
null
213,098
null
2,080,736
null
1
144
javascript|html|onclick
640,087
<p>Add semi-colons <code>;</code> to the end of the function calls in order for them both to work.</p> <pre><code> &lt;input id="btn" type="button" value="click" onclick="pay(); cls();"/&gt; </code></pre> <p>I don't believe the last one is <em>required</em> but hey, might as well add it in for good measure.</p> <p>Here is a good reference from SitePoint <a href="http://reference.sitepoint.com/html/event-attributes/onclick">http://reference.sitepoint.com/html/event-attributes/onclick</a></p>
10,656,510
Qt connect "no such slot" when slot definitely does exist
<p>Qt v4.8.0, VC2010 compiler</p> <p>I have a <code>QMainWindow</code> based class and I'm trying to send it signals involving <code>QUuid</code></p> <p>However, every time I run it I get the errors:</p> <pre><code>Object::connect: No such slot MainWindow::on_comp_connected(QUuid) in ..\..\src\mainwindow.cpp:143 Object::connect: (receiver name: 'MainWindow') </code></pre> <p>It's driving me potty as the slot definitely does exist (it's in the moc_)</p> <pre><code>class MainWindow : public QMainWindow { Q_OBJECT // SNIP private typedefs public: MainWindow(QWidget *parent = 0, Qt::WFlags flags = 0); ~MainWindow(); // SNIP public methods signals: void testSendQuuid(const QUuid &amp;qcid); public slots: void on_comp_connected(const QUuid &amp;qcid); private: // SNIP private parts QOpenAcnController *acnInt; // This is where the signal comes from }; </code></pre> <p>At the end of the <code>MainWindow</code> constructor (the line 143 mentioned) I have:</p> <pre><code>connect(acnInt, SIGNAL(callback_comp_connected(QUuid)), this, SLOT(on_comp_connected(QUuid))); </code></pre> <p>Given that the slot is <em>definitely</em> there in the moc_mainwindow.cpp (I checked, it's slot #1), what on earth could be stopping the connection happening?</p> <p>If I try to connect the <code>testSendQuuid(QUuid)</code> signal to the slot, I get no such signal and no such slot as well.</p> <p>I cannot for the life of me figure out why Qt is denying the existence of a slot that is <em>most definitely there</em>!</p>
10,657,003
4
3
null
2012-05-18 16:38:24.98 UTC
2
2022-09-06 08:46:59.893 UTC
2018-09-12 04:31:34.03 UTC
null
8,464,442
null
1,403,832
null
1
10
qt|signals-slots
47,126
<p>Check whether whether that <code>moc_mainwindow.cpp</code> is in your <code>Build Path</code>. Or you are using some other moc_window.cpp file. Because, for ex: In QtCreator, it build the source to a new build directory. And also it uses old moc_cpp file(s) if you try to open the source in a different location. </p> <p>What I am trying to say is the moc file which you checked may contain those slot definition, but compiler might be using some other moc file which was created earlier.</p>
31,888,226
Android Studio ADB connection error
<p>i got this problem that is annoying me after updating to 1.3 , i fired up Android Studio and got a message saying :</p> <p>***Unable to establish a connection to adb This usually happens if you have an incompatible version of adb running already. Try reopening Android Studio after killing any existing adb daemons. If this happens repeatedly ,please file a bug at <a href="http://b.android.com">http://b.android.com</a> including the following :</p> <ol> <li>Output of the command 'C:\Users\username\AppData\Local\Android\sdk\platform-tools\adb.exe devices'</li> </ol> <p>2.you Idea.log file (Help |Show log in explorer)***</p> <p>Whats the solution ,i'm running Win7 32bit</p>
35,078,826
5
2
null
2015-08-08 00:03:50.473 UTC
7
2019-05-20 16:26:20.467 UTC
null
null
null
null
4,406,749
null
1
19
android-studio|adb
62,402
<p>You need to kill the adb process that is running, to do so, </p> <ol> <li><p>Go to Spotlight search, open Activity Monitor, </p></li> <li><p>Loop for adb under CPU tag, </p></li> <li><p>Now Select it and Force Quit the process. </p></li> </ol> <p>You can kill adb process through Terminal command too, by simply typing Kill -9 adb </p> <p><strong><em>Note</em></strong>: Sometimes When u tried to force close them they kept restarting. Make sure you quit any emulators and disconnect any devices to avoid any mistake.</p>
31,950,362
Factory method with DI and IoC
<p>I am familiar with these patterns but still don't know how to handle following situation:</p> <pre><code>public class CarFactory { public CarFactory(Dep1,Dep2,Dep3,Dep4,Dep5,Dep6) { } public ICar CreateCar(type) { switch(type) { case A: return new Car1(Dep1,Dep2,Dep3); break; case B: return new Car2(Dep4,Dep5,Dep6); break; } } } </code></pre> <p>In general the problem is with amount of references that needs to be injected. It will be even worse when there are more cars.</p> <p>First approach that comes to my mind is to inject Car1 and Car2 in factory constructor but it is against factory approach because factory will return always the same object. The second approach is to inject servicelocator but it's antipattern everywhere. How to solve it?</p> <h2>Edit:</h2> <p>Alternative way 1:</p> <pre><code>public class CarFactory { public CarFactory(IContainer container) { _container = container; } public ICar CreateCar(type) { switch(type) { case A: return _container.Resolve&lt;ICar1&gt;(); break; case B: return _container.Resolve&lt;ICar2&gt;(); break; } } } </code></pre> <p>Alternative way 2 (too hard to use because of too many of dependencies in tree):</p> <pre><code>public class CarFactory { public CarFactory() { } public ICar CreateCar(type) { switch(type) { case A: return new Car1(new Dep1(),new Dep2(new Dep683(),new Dep684()),....) break; case B: return new Car2(new Dep4(),new Dep5(new Dep777(),new Dep684()),....) break; } } } </code></pre>
31,971,691
6
4
null
2015-08-11 19:31:11.943 UTC
43
2021-05-07 02:25:47.357 UTC
2018-02-13 12:29:31.133 UTC
null
181,087
null
1,411,104
null
1
58
c#|dependency-injection|inversion-of-control|factory-pattern
53,073
<p>Having a switch case statement inside of a factory is a code smell. Interestingly, you don't seem to be focusing on solving that issue at all.</p> <p>The best, most DI friendly solution for this scenario is the <a href="https://sourcemaking.com/design_patterns/strategy" rel="noreferrer">strategy pattern</a>. It allows your DI container to inject the dependencies into the factory instances where they belong, without cluttering up other classes with those dependencies or resorting to a service locator.</p> <h1>Interfaces</h1> <pre><code>public interface ICarFactory { ICar CreateCar(); bool AppliesTo(Type type); } public interface ICarStrategy { ICar CreateCar(Type type); } </code></pre> <h1>Factories</h1> <pre><code>public class Car1Factory : ICarFactory { private readonly IDep1 dep1; private readonly IDep2 dep2; private readonly IDep3 dep3; public Car1Factory(IDep1 dep1, IDep2 dep2, IDep3 dep3) { this.dep1 = dep1 ?? throw new ArgumentNullException(nameof(dep1)); this.dep2 = dep2 ?? throw new ArgumentNullException(nameof(dep2)); this.dep3 = dep3 ?? throw new ArgumentNullException(nameof(dep3)); } public ICar CreateCar() { return new Car1(this.dep1, this.dep2, this.dep3); } public bool AppliesTo(Type type) { return typeof(Car1).Equals(type); } } public class Car2Factory : ICarFactory { private readonly IDep4 dep4; private readonly IDep5 dep5; private readonly IDep6 dep6; public Car2Factory(IDep4 dep4, IDep5 dep5, IDep6 dep6) { this.dep4 = dep4 ?? throw new ArgumentNullException(nameof(dep4)); this.dep5 = dep5 ?? throw new ArgumentNullException(nameof(dep5)); this.dep6 = dep6 ?? throw new ArgumentNullException(nameof(dep6)); } public ICar CreateCar() { return new Car2(this.dep4, this.dep5, this.dep6); } public bool AppliesTo(Type type) { return typeof(Car2).Equals(type); } } </code></pre> <h1>Strategy</h1> <pre><code>public class CarStrategy : ICarStrategy { private readonly ICarFactory[] carFactories; public CarStrategy(ICarFactory[] carFactories) { this.carFactories = carFactories ?? throw new ArgumentNullException(nameof(carFactories)); } public ICar CreateCar(Type type) { var carFactory = this.carFactories .FirstOrDefault(factory =&gt; factory.AppliesTo(type)); if (carFactory == null) { throw new InvalidOperationException($&quot;{type} not registered&quot;); } return carFactory.CreateCar(); } } </code></pre> <h1>Usage</h1> <pre><code>// I am showing this in code, but you would normally // do this with your DI container in your composition // root, and the instance would be created by injecting // it somewhere. var strategy = new CarStrategy(new ICarFactory[] { new Car1Factory(dep1, dep2, dep3), new Car2Factory(dep4, dep5, dep6) }); // And then once it is injected, you would simply do this. // Note that you could use a magic string or some other // data type as the parameter if you prefer. var car1 = strategy.CreateCar(typeof(Car1)); var car2 = strategy.CreateCar(typeof(Car2)); </code></pre> <p>Note that because there is no switch case statement, you can add additional factories to the strategy without changing the design, and each of those factories can have their own dependencies that are injected by the DI container.</p> <pre><code>var strategy = new CarStrategy(new ICarFactory[] { new Car1Factory(dep1, dep2, dep3), new Car2Factory(dep4, dep5, dep6), new Car3Factory(dep7, dep8, dep9) }); var car1 = strategy.CreateCar(typeof(Car1)); var car2 = strategy.CreateCar(typeof(Car2)); var car3 = strategy.CreateCar(typeof(Car3)); </code></pre>
37,935,393
Pass by value vs pass by rvalue reference
<p>When should I declare my function as:</p> <p><code>void foo(Widget w);</code></p> <p>as opposed to</p> <p><code>void foo(Widget&amp;&amp; w);</code>?</p> <p>Assume this is the only overload (as in, I pick one or the other, not both, and no other overloads). No templates involved. Assume that the function <code>foo</code> requires ownership of the <code>Widget</code> (e.g. <code>const Widget&amp;</code> is not part of this discussion). I'm not interested in any answer outside the scope of these circumstances. See addendum at end of post for <em>why</em> these constraints are part of the question.</p> <p>The primary difference that my colleagues and I can come up with is that the rvalue reference parameter forces you to be explicit about copies. The caller is responsible for making an explicit copy and then passing it in with <code>std::move</code> when you want a copy. In the pass by value case, the cost of the copy is hidden:</p> <pre><code> //If foo is a pass by value function, calling + making a copy: Widget x{}; foo(x); //Implicit copy //Not shown: continues to use x locally //If foo is a pass by rvalue reference function, calling + making a copy: Widget x{}; //foo(x); //This would be a compiler error auto copy = x; //Explicit copy foo(std::move(copy)); //Not shown: continues to use x locally </code></pre> <p>Other than that difference. Other than forcing people to be explicit about copying and changing how much syntactic sugar you get when calling the function, how else are these different? What do they say differently about the interface? Are they more or less efficient than one another?</p> <p>Other things that my colleagues and I have already thought of:</p> <ul> <li>The rvalue reference parameter means that you <em>may</em> move the argument, but does not mandate it. It is possible that the argument you passed in at the call site will be in its original state afterwards. It's also possible the function would eat/change the argument without ever calling a move constructor but assume that because it was an rvalue reference, the caller relinquished control. Pass by value, if you move into it, you must assume that a move happened; there's no choice.</li> <li>Assuming no elisions, a single move constructor call is eliminated with pass by rvalue.</li> <li>The compiler has better opportunity to elide copies/moves with pass by value. Can anyone substantiate this claim? Preferably with a link to gcc.godbolt.org showing optimized generated code from gcc/clang rather than a line in the standard. My attempt at showing this was probably not able to successfully isolate the behavior: <a href="https://godbolt.org/g/4yomtt">https://godbolt.org/g/4yomtt</a></li> </ul> <p><strong>Addendum:</strong> <em>why</em> am I constraining this problem so much?</p> <ul> <li>No overloads - if there were other overloads, this would devolve into a discussion of pass by value vs a set of overloads that include both const reference and rvalue reference, at which point the set of overloads is obviously more efficient and wins. This is well known, and therefore not interesting.</li> <li>No templates - I'm not interested in how forwarding references fit into the picture. If you have a forwarding reference, you call std::forward anyway. The goal with a forwarding reference is to pass things as you received them. Copies aren't relevant because you just pass an lvalue instead. It's well known, and not interesting.</li> <li><code>foo</code> requires ownership of <code>Widget</code> (aka no <code>const Widget&amp;</code>) - We're not talking about read-only functions. If the function was read-only or didn't need to own or extend the lifetime of the <code>Widget</code>, then the answer trivially becomes <code>const Widget&amp;</code>, which again, is well known, and not interesting. I also refer you to why we don't want to talk about overloads.</li> </ul>
37,940,520
7
7
null
2016-06-21 04:05:49.393 UTC
28
2020-04-30 17:44:44.227 UTC
2016-06-21 17:28:36.363 UTC
null
2,843,835
null
2,843,835
null
1
91
c++|c++11|c++14
31,100
<blockquote> <p>The rvalue reference parameter forces you to be explicit about copies.</p> </blockquote> <p>Yes, pass-by-rvalue-reference got a point.</p> <blockquote> <p>The rvalue reference parameter means that you may move the argument, but does not mandate it.</p> </blockquote> <p>Yes, pass-by-value got a point. </p> <p>But that also gives to pass-by-rvalue the opportunity to handle exception guarantee: if <code>foo</code> throws, <code>widget</code> value is not necessary consumed.</p> <p>For move-only types (as <code>std::unique_ptr</code>), pass-by-value seems to be the norm (mostly for your second point, and first point is not applicable anyway).</p> <p>EDIT: standard library contradicts my previous sentence, one of <code>shared_ptr</code>'s constructor takes <code>std::unique_ptr&lt;T, D&gt;&amp;&amp;</code>.</p> <p>For types which have both copy/move (as <code>std::shared_ptr</code>), we have the choice of the coherency with previous types or force to be explicit on copy.</p> <p><strike>Unless you want to guarantee there is no unwanted copy, I would use pass-by-value for coherency.</strike></p> <p>Unless you want guaranteed and/or immediate sink, I would use pass-by-rvalue.</p> <p>For existing code base, I would keep consistency.</p>
13,700,632
convert to Uppercase in shell
<p>I am reading a character from keyboard and converting it to uppercase and then displaying the character again. But this is showing error. How can I do this.</p> <p>my code:-</p> <pre><code>read a; a=echo $a | tr 'a-z' 'A-Z' echo $a </code></pre> <p>I also tried this :-</p> <pre><code>read option; eval $(awk -v option=$option '{print "a="toupper(option);}') echo $a </code></pre>
13,700,726
7
0
null
2012-12-04 10:19:03.953 UTC
3
2021-07-25 10:00:29.44 UTC
null
null
null
null
661,801
null
1
12
shell|awk|uppercase
60,720
<p>If you want to store the result of <code>a</code> back in <code>a</code>, then you can do use <em>command substitution</em>:</p> <pre><code>read a; a=$(echo $a | tr 'a-z' 'A-Z') echo $a </code></pre>
13,296,169
AngularJS - controller method doesn't get called on ngClick - no error
<p>I try to call the method <code>removePlayer(playerId)</code> if a button gets clicked. But, the method doesn't get called, or at least the statements inside it aren't firing, because I put a <code>console.log()</code> statement at the top.</p> <p>The console is empty, so I'm really clueless. Here is my code:</p> <p>Controller:</p> <pre><code>function appController($scope) { $scope.players = []; var playercount = 0; $scope.addPlayer = function(playername) { $scope.players.push({name: playername, score: 0, id: playercount}); playercount++; } function getIndexOfPlayerWithId(playerId) { for (var i = $scope.players.length - 1; i &gt; -1; i--) { if ($scope.players[i].id == playerId) return i; } } $scope.removePlayer = function(playerId) { console.log("remove"); var index = getIndexOfPlayerWithId(playerId); $scope.players.slice(index, 1); } } appController.$inject = ['$scope']; </code></pre> <p>HTML:</p> <pre><code>... &lt;table id="players"&gt; &lt;tr ng-repeat="player in players"&gt; &lt;td&gt;{{player.name}}&lt;/td&gt; &lt;td&gt;{{player.score}}&lt;/td&gt; &lt;td&gt;&lt;button ng-click="removePlayer({{player.id}})"&gt;Remove&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; ... </code></pre>
13,296,479
3
2
null
2012-11-08 19:20:14.97 UTC
3
2013-08-28 18:06:06.457 UTC
null
null
null
null
1,087,848
null
1
20
javascript|angularjs
41,719
<p>You shouldn't be using curly braces (<code>{{ }}</code>) in the ng-click expression. You should write:</p> <p><code>&lt;button ng-click="removePlayer(player.id)"&gt;Remove&lt;/button&gt;</code></p>
13,555,386
Starting Celery: AttributeError: 'module' object has no attribute 'celery'
<p>I try to start a Celery worker server from a command line:</p> <pre><code>celery -A tasks worker --loglevel=info </code></pre> <p>The code in tasks.py:</p> <pre><code>import os os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings" from celery import task @task() def add_photos_task( lad_id ): ... </code></pre> <p>I get the next error:</p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in &lt;module&gt; load_entry_point('celery==3.0.12', 'console_scripts', 'celery')() File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/__main__.py", line 14, in main main() File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 946, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/celery.py", line 890, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 177, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 295, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/local/lib/python2.7/site-packages/celery-3.0.12-py2.7.egg/celery/bin/base.py", line 313, in find_app return sym.celery AttributeError: 'module' object has no attribute 'celery' </code></pre> <p>Does anybody know why the 'celery' attribute cannot be found? Thank you for help.</p> <p>The operating system is Linux Debian 5.</p> <p><strong>Edit</strong>. May be the clue. Could anyone explain me the next comment to a function (why we must be sure that it finds modules in the current directory)?</p> <pre><code># from celery/utils/imports.py def import_from_cwd(module, imp=None, package=None): """Import module, but make sure it finds modules located in the current directory. Modules located in the current directory has precedence over modules located in `sys.path`. """ if imp is None: imp = importlib.import_module with cwd_in_path(): return imp(module, package=package) </code></pre>
13,569,129
6
4
null
2012-11-25 20:52:25.063 UTC
6
2018-09-26 10:23:44.703 UTC
2012-11-26 10:57:25.063 UTC
null
749,288
null
749,288
null
1
27
python|django|celery|django-celery
61,831
<p>I forgot to create a celery object in tasks.py:</p> <pre><code>from celery import Celery from celery import task celery = Celery('tasks', broker='amqp://guest@localhost//') #! import os os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings" @task() def add_photos_task( lad_id ): ... </code></pre> <p>After that we could normally start tasks:</p> <pre><code>celery -A tasks worker --loglevel=info </code></pre>
13,538,324
Avoiding infinite loops in __getattribute__
<p>The method <code>__getattribute__</code> needs to be written carefully in order to avoid the infinite loop. For example:</p> <pre><code>class A: def __init__(self): self.x = 100 def __getattribute__(self, x): return self.x &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.x # infinite looop RuntimeError: maximum recursion depth exceeded while calling a Python object class B: def __init__(self): self.x = 100 def __getattribute__(self, x): return self.__dict__[x] &gt;&gt;&gt; b = B() &gt;&gt;&gt; b.x # infinite looop RuntimeError: maximum recursion depth exceeded while calling a Python object </code></pre> <p>Hence we need to write the method in this way:</p> <pre><code>class C: def __init__(self): self.x = 100 def __getattribute__(self, x): # 1. error # AttributeError: type object 'object' has no attribute '__getattr__' # return object.__getattr__(self, x) # 2. works return object.__getattribute__(self, x) # 3. works too # return super().__getattribute__(x) </code></pre> <p>My question is why does <code>object.__getattribute__</code> method work? From where does <code>object</code> get the <code>__getattribute__</code> method? And if <code>object</code> does not have any <code>__getattribute__</code>, then we are just calling the same method on class <code>C</code> but via the super class. Why, then calling the method via super class does not result in an infinite loop?</p>
13,538,433
3
5
null
2012-11-24 04:39:05.567 UTC
8
2021-03-08 00:24:22.723 UTC
2021-03-08 00:24:22.723 UTC
null
6,862,601
null
1,206,051
null
1
33
python|python-3.x
13,207
<p>You seem to be under the impression that your implementation of <code>__getattribute__</code> is merely a hook, that if you provide it Python will call it, and otherwise the interpreter will do its normal magic directly.</p> <p>That is not correct. When python looks up attributes on instances, <code>__getattribute__</code> is the main entry for all attribute access, and <code>object</code> provides the default implementation. Your implementation is thus <em>overriding</em> the original, and if your implementation provides no alternative means of returning attributes it fails. You <em>cannot</em> use attribute access in that method, since all attribute access to the instance (<code>self</code>) is channelled again through <code>type(self).__getattribute__(self, attr)</code>.</p> <p>The best way around this is by calling the overridden original again. That's where <code>super(C, self).__getattribute__(attr)</code> comes in; you are asking the next class in the class-resolution order to take care of the attribute access for you.</p> <p>Alternatively, you can call the unbound <code>object.__getattribute__()</code> method directly. The C implementation of this method is the final stop for attribute access (it has direct access to <code>__dict__</code> and is thus not bound to the same limitations).</p> <p>Note that <code>super()</code> returns a proxy object that'll look up whatever method can be found next in the method-resolution ordered base classes. If no such method exists, it'll fail with an attribute error. It will <em>never</em> call the original method. Thus <code>Foo.bar()</code> looking up <code>super(Foo, self).bar</code> will either be a base-class implementation or an attribute error, <em>never</em> <code>Foo.bar</code> itself.</p>
13,431,313
Android emulator crashing on Mac
<p>When I try to launch Android emulator, it crashes on Mac OS X. It was working some time ago, but now it isn't and I don't have an idea why.</p> <p>Crash log: <a href="http://pastebin.com/04MjCqaS" rel="noreferrer">http://pastebin.com/04MjCqaS</a></p> <p>Terminal log in verbose mode: <a href="http://pastebin.com/L6y6rUr0" rel="noreferrer">http://pastebin.com/L6y6rUr0</a></p>
13,610,300
8
3
null
2012-11-17 14:05:18.993 UTC
8
2019-04-23 13:48:34.9 UTC
null
null
null
null
911,679
null
1
40
android|macos|android-emulator|android-sdk-tools
22,008
<p>Same issue here, I'm running a mac mini with 8GB of RAM and MacOS Lion. It used to work with the old AVD with some random crashes every now and then but since the last update to APi 17 it's a pain in the neck.</p> <p>The ADT bundle doesn't work at all. After tweaking the memory limits on eclipse.ini file it throws random memory errors. Also it's not been able to download and install the m2e (maven to eclipse) plugin.</p> <p>I moved to IntelliJ and I'm able to launch AVD manager but none of the "old" created devices work. If I create a new one and I launch it it works until I close it, then I have to restart the Mac and create a new device. Also it randomly shows errors when I want to delete those old created virtual devices.</p> <p>Also the DDMS fails to start. I launch it, shows its icon on the Dock but it doesn't respond until I force close. What a Nightmare. </p> <p>** EDIT ** I found at android dev bug tracker this issue when you're running 2 screens: <a href="https://issuetracker.google.com/issues/36959630" rel="nofollow noreferrer">here</a></p> <p>This is happening to me with the android emulator. I solved it like this: cd ~/.android/avd ls *.avd </p> <p>Now choose the emulator that is crashing and</p> <pre><code>cd name_of_the_emulator.avd touch emulator-user.ini vi emulator-user.ini </code></pre> <p>And now reset window.x, that's window.x=0 exit and run the emulator.</p> <p>If you move and close the emulator to the secondary screen it will crash the next time you want to run it. </p>
13,393,892
Inserting text in TinyMCE Editor where the cursor is
<p>I've been trying to insert text into the TinyMCE Editor at the focused paragraph element (<code>&lt;p&gt;</code>) exactly where the cursor is but got no luck!!</p> <pre><code>var elem = tinyMCE.activeEditor.dom.get('tinymce'); var child = elem.firstChild; while (child) { if (child.focused) { $(child).insertAtCaret("some text"); } child = child.nextSibling; } </code></pre> <p>If anyone has any idea on how to solve this I'll be very thankful.</p>
13,393,918
5
1
null
2012-11-15 08:36:11.533 UTC
14
2022-05-14 01:01:34.783 UTC
2016-03-24 19:06:27.013 UTC
null
404,623
null
1,577,264
null
1
45
javascript|jquery|tinymce|cursor-position
48,624
<p>You should use the command <code>mceInsertContent</code>. See the <a href="http://www.tinymce.com/wiki.php/TinyMCE3x:Command_identifiers" rel="noreferrer">TinyMCE documentation</a>.</p> <pre><code>tinymce.activeEditor.execCommand('mceInsertContent', false, "some text"); </code></pre>
13,297,406
Using File Extension Wildcards in os.listdir(path)
<p>I have a directory of files that I am trying to parse using Python. I wouldn't have a problem if they were all the same extension, but for whatever reason they are created with sequential numeric extensions after their original extension. For example: <code>foo.log foo.log.1 foo.log.2 bar.log bar.log.1 bar.log.2 etc.</code> On top of that, foo.log is in XML format, while bar.log is not. What's the best route to take in order to read and parse only the <code>foo.log.*</code> <em>and</em> <code>foo.log</code> files? The <code>bar.log</code> files do not need to be read. Below is my code:</p> <pre><code>import os from lxml import etree path = 'C:/foo/bar//' listing = os.listdir(path) for files in listing: if files.endswith('.log'): print files data = open(os.path.join(path, files), 'rb').read() tree = etree.fromstring(data) search = tree.findall('.//QueueEntry') </code></pre> <p>This doesn't work as it doesn't read any <code>.log.*</code> files and the parser chokes on the files that are read, but are not in xml format. Thanks!</p>
13,297,537
4
0
null
2012-11-08 20:37:30.723 UTC
10
2021-03-06 10:43:13.063 UTC
2013-12-06 18:58:56.44 UTC
null
1,636,876
null
1,636,876
null
1
57
python
101,291
<p>Maybe the <a href="http://docs.python.org/2/library/glob.html" rel="noreferrer">glob</a> module can help you:</p> <pre><code>import glob listing = glob.glob('C:/foo/bar/foo.log*') for filename in listing: # do stuff </code></pre>
39,824,219
Install php 5.3 or 5.4 on Ubuntu 16.04 Xenial and apache
<p>I want to Install php 5.3 or 5.4 on Ubuntu 16.04 Xenial and Apache.<br> A tutorial points me to use PPA but they are not helping me in what I need. </p> <p>I know that PHP 5.3 and 4 are obsolete but I need this for a project and is this possible? If yes then please teach me how in a step by step procedure with Apache2.</p>
39,881,104
5
3
null
2016-10-03 03:30:59.273 UTC
0
2018-11-22 11:25:50.657 UTC
2016-10-05 17:25:26.377 UTC
null
924,299
null
4,790,677
null
1
13
php|linux|ubuntu
57,720
<p>Before installing PHP 5.4 you need to read this <a href="https://launchpad.net/~ondrej/+archive/ubuntu/php5-oldstable" rel="nofollow noreferrer">notice</a>:</p> <blockquote> <p>Security support for PHP 5.4 has ended. You are using this repository knowing that there might be and probably are unfixed security vulnerabilities. Please upgrade to PHP 5.6 or PHP 7.0 as found in the main repository: <code>ppa:ondrej/php</code></p> </blockquote> <p>After understanding the risks , to install PHP 5.4 ,add the PPA to your <code>sources.list</code>:</p> <pre><code>sudo add-apt-repository ppa:ondrej/php5-oldstable sudo apt-get update </code></pre> <p>Install it:</p> <pre><code>sudo apt-get install -y php5 </code></pre> <p>To be safe , the PHP 5.6 version can be installed as follows:</p> <pre><code>sudo add-apt-repository ppa:ondrej/php sudo apt-get update sudo apt-get install php7.0 php5.6 php5.6-mysql php-gettext php5.6-mbstring php-xdebug libapache2-mod-php5.6 libapache2-mod-php7.0 sudo a2dismod php7.0 ; sudo a2enmod php5.6 ; sudo service apache2 restart </code></pre> <p><strong>Update</strong></p> <p>All version prior to PHP 5.6 are <a href="https://secure.php.net/eol.php" rel="nofollow noreferrer">unsupported</a> </p> <blockquote> <p>This page lists the end of life date for each unsupported branch of PHP. If you are using these releases, you are strongly urged to upgrade to a <a href="https://secure.php.net/supported-versions.php" rel="nofollow noreferrer">current version</a>, as using older versions may expose you to security vulnerabilities and bugs that have been fixed in more recent versions of PHP.</p> </blockquote>
24,054,773
Java 8 Streams: multiple filters vs. complex condition
<p>Sometimes you want to filter a <code>Stream</code> with more than one condition:</p> <pre><code>myList.stream().filter(x -&gt; x.size() &gt; 10).filter(x -&gt; x.isCool()) ... </code></pre> <p>or you could do the same with a complex condition and a <em>single</em> <code>filter</code>:</p> <pre><code>myList.stream().filter(x -&gt; x.size() &gt; 10 &amp;&amp; x -&gt; x.isCool()) ... </code></pre> <p>My guess is that the second approach has better performance characteristics, but I don't <em>know</em> it.</p> <p>The first approach wins in readability, but what is better for the performance?</p>
24,055,107
4
2
null
2014-06-05 08:01:18.07 UTC
64
2019-07-19 16:33:00.397 UTC
2016-05-10 10:56:36.947 UTC
null
2,711,488
null
238,134
null
1
315
java|lambda|filter|java-8|java-stream
277,885
<p>The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.</p> <p>Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace <code>filter(x -&gt; x.isCool())</code> by <code>filter(ItemType::isCool)</code>. That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single <code>filter</code> invocation using a lambda expression with <code>&amp;&amp;</code>.</p> <p>But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.</p> <p>In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.</p> <p>So there is no simple answer.</p> <p>The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.</p> <hr> <p>¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation</p>
16,558,948
How to use textview.getLayout()? It returns null
<p>I’m trying set a layout for <code>textview</code> so I can use <code>getEllipsisCount()</code> method. But below code returns null as layout value. How can I take layout and then use <code>getEllipsisCount(0)</code> method.</p> <pre><code>public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView mytextview =(TextView) findViewById(R.id.textView1); mytextview.setText(myText); Layout layout = mytextview.getLayout(); if(layout != null){ mytextview.setText(&quot;very good layout worked\n&quot;); } } } </code></pre>
16,559,856
6
1
null
2013-05-15 07:14:57.203 UTC
8
2021-01-29 22:26:37.98 UTC
2021-01-29 22:26:37.98 UTC
null
641,451
null
2,382,106
null
1
19
android|android-layout|textview
14,794
<p>You are calling it too early, thats why it is returning <code>null</code></p> <p>Try this</p> <pre><code> ViewTreeObserver vto = mytextview.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Layout layout = mytextview.getLayout(); } }); </code></pre>
58,131,602
Unable to resolve module `react-native-reanimated`
<p>React native project running fine without react navigation tab module, once I installed the tab module using </p> <blockquote> <p><code>npm install --save react-navigation-tab</code></p> </blockquote> <p>The following error occure on node terminal.</p> <p>React-tab-navigation throwing the following error.</p> <p>error: bundling failed: Error: Unable to resolve module <code>react-native-reanimated</code> from <code>node_modules\react-navigation-tabs\lib\module\views\MaterialTopTabBar.js</code>: react-native-reanimated could not be found within the project.</p>
58,145,312
12
1
null
2019-09-27 09:22:38.613 UTC
5
2022-04-06 13:34:11.977 UTC
null
null
null
null
665,485
null
1
22
react-native
68,548
<p>react-navigation-tabs depends on react-navigation package.<br> So I think you missed the <a href="https://reactnavigation.org/docs/en/getting-started.html" rel="noreferrer">Getting Started</a> section.</p> <p>Currently for react-navigation 4.x you should:</p> <pre><code>yarn add react-navigation yarn add react-native-reanimated react-native-gesture-handler react-native-screens@^1.0.0-alpha.23 </code></pre> <p>Then for ios: </p> <pre><code>cd ios pod install </code></pre> <p>To finalize installation of react-native-screens for Android, add the following two lines to dependencies section in <code>android/app/build.gradle</code>:</p> <pre><code>implementation 'androidx.appcompat:appcompat:1.1.0-rc01' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02' </code></pre> <p>And then</p> <pre><code>react-native link react-native-reanimated </code></pre>
15,315,315
How do I add a button to a td using js?
<p>I have a table that is generated on the fly, as it is generating its TDs, I want to set the first TD to be a button. Below is my code, obviously doesn't work. I remember from another problem I had that we can change the content of a div using the .html(), but that doesnt work here neither.</p> <p>Code:</p> <pre><code> var table = document.getElementById("userinfo"); var thead, tr, td; table.appendChild(thead = document.createElement("thead")); thead.appendChild(tr = document.createElement("tr")); tr.appendChild(td = document.createElement("td")); td.innerHTML = "Email"; tr.appendChild(td = document.createElement("td")); td.innerHTML = "First Name"; tr.appendChild(td = document.createElement("td")); td.innerHTML = "Last Name"; tr.appendChild(td = document.createElement("td")); td.innerHTML = "Is Active?"; for (var i in data) { tr = document.createElement("tr"); tr.setAttribute("id", "row" + i); if (i%2 == 0) { tr.setAttribute("style", "background:white"); } var entry = data[i]; console.log(entry); table.appendChild(tr); tr.appendChild(td = document.createElement("td")); td.setAttribute("html", "&lt;input type=\"button\" class=\"btn\" value=\'" + entry.email + "\" onclick=\"" + chooseUser(entry) + "\"/&gt;"); tr.appendChild(td = document.createElement("td")); td.innerHTML = entry.first_name; tr.appendChild(td = document.createElement("td")); td.innerHTML = entry.last_name; tr.appendChild(td = document.createElement("td")); td.innerHTML = entry.isActive; } </code></pre>
15,315,359
2
2
null
2013-03-09 20:04:48.74 UTC
2
2019-11-28 21:30:54.307 UTC
null
null
null
null
802,281
null
1
6
javascript|button
46,824
<p>You can either use <code>td.innerHTML = '&lt;input type="button"...';</code> or you can do it the "proper" way:</p> <pre><code>var btn = document.createElement('input'); btn.type = "button"; btn.className = "btn"; btn.value = entry.email; btn.onclick = (function(entry) {return function() {chooseUser(entry);}})(entry); td.appendChild(btn); </code></pre>
26,790,129
Swift: Receive UDP with GCDAsyncUdpSocket
<p>BACKGROUND:</p> <p>I want to be able to send and receive UDP packets between my iOS app and a server. The server echoes back every incoming message to the client the app. <strong>The server is tested and confirmed working</strong>. I have a StartViewController which starting up two classes that implements GCDAsyncUdpSocketDelegate, one for sending and one for receiving. The "sending socket" is working, the server receives the messages.</p> <p>PROBLEM:</p> <p>The app never get the incoming message back after it been sent. Something with the listening socket setup is probably wrong since didReceiveData never get called.</p> <p>Have I done this completely wrong?</p> <p>Start:</p> <pre><code>class StartViewController: UIViewController { var inSocket : InSocket! var outSocket : OutSocket! override func viewDidLoad() { super.viewDidLoad() inSocket = InSocket() outSocket = OutSocket() } @IBAction func goButton(sender: UIButton) { outSocket.send("This is a message!") } } </code></pre> <p>Receive:</p> <pre><code>class InSocket: NSObject, GCDAsyncUdpSocketDelegate { let IP = "255.255.255.255" let PORT:UInt16 = 5556 var socket:GCDAsyncUdpSocket! override init(){ super.init() setupConnection() } func setupConnection(){ var error : NSError? socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) socket.bindToPort(PORT, error: &amp;error) socket.enableBroadcast(true, error: &amp;error) socket.joinMulticastGroup(IP, error: &amp;error) socket.beginReceiving(&amp;error) } func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) { println("incoming message: \(data)"); } } </code></pre> <p>Send:</p> <pre><code>class OutSocket: NSObject, GCDAsyncUdpSocketDelegate { let IP = "90.112.76.180" let PORT:UInt16 = 5556 var socket:GCDAsyncUdpSocket! override init(){ super.init() setupConnection() } func setupConnection(){ var error : NSError? socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) socket.connectToHost(IP, onPort: PORT, error: &amp;error) } func send(message:String){ let data = message.dataUsingEncoding(NSUTF8StringEncoding) socket.sendData(data, withTimeout: 2, tag: 0) } func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) { println("didConnectToAddress"); } func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) { println("didNotConnect \(error)") } func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) { println("didSendDataWithTag") } func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) { println("didNotSendDataWithTag") } } </code></pre> <p><strong>Edit:</strong> Added forgotten code line.</p>
26,818,254
2
2
null
2014-11-06 21:54:16.037 UTC
8
2020-08-01 13:33:29.79 UTC
2014-11-07 07:08:04.567 UTC
null
1,915,820
null
1,915,820
null
1
18
ios|swift|udp|cocoaasyncsocket|gcdasyncudpsocket
22,352
<p>I finally got it to work with this socket setup:</p> <pre><code>func setupConnection(){ var error : NSError? socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) socket.bindToPort(PORT, error: &amp;error) socket.connectToHost(SERVER_IP, onPort: PORT, error: &amp;error) socket.beginReceiving(&amp;error) send("ping") } func send(message:String){ let data = message.dataUsingEncoding(NSUTF8StringEncoding) socket.sendData(data, withTimeout: 2, tag: 0) } </code></pre>
19,650,368
Hide div by class id
<p>If I have <code>&lt;div id="ad1" class="ad"&gt;</code> and <code>&lt;div id="ad2" class="ad"&gt;</code> how can I hide both by hiding all divs with class ad</p> <p>I tried <code>document.getElementsByClassName(ad).style.visibility="hidden";</code> but only this works<br> <code>function hidestuff(boxid){ document.getElementById(boxid).style.visibility="hidden"; }</code></p>
19,650,569
4
4
null
2013-10-29 05:29:14.75 UTC
1
2016-03-02 06:58:28.9 UTC
null
null
null
null
2,881,151
null
1
8
javascript|html|visibility
46,413
<p>As Matt Ball's clue left, you need to iterate through the results of your getElementsByClassName result. </p> <p>Try something along the lines of:</p> <pre><code> var divsToHide = document.getElementsByClassName("ad"); for(var i = 0; i &lt; divsToHide.length; i++) { divsToHide[i].style.visibility="hidden"; } </code></pre>
19,796,590
com.google.gson.internal.LinkedHashTreeMap cannot be cast to my object
<p>I have JSON file looks like </p> <pre><code>{ "SUBS_UID" : { "featureSetName" : "SIEMENSGSMTELEPHONY MULTISIM", "featureName" : "MULTISIMIMSI", "featureKey" : [{ "key" : "SCKEY", "valueType" : 0, "value" : "0" } ] }, } </code></pre> <p>So the key is a String "SUBS_ID" and the value is a model called FeatureDetails which contains attributes "featureSetName,featureName,...". So i read from the JSON file using google.json lib like this,</p> <pre><code>HashMap&lt;String, FeatureDetails&gt; featuresFromJson = new Gson().fromJson(JSONFeatureSet, HashMap.class); </code></pre> <p>then I'm trying to loop over this HashMap getting the value and cast it to my FeatureDetails model,</p> <pre><code>for (Map.Entry entry : featuresFromJson.entrySet()) { featureDetails = (FeatureDetails) entry.getValue(); } </code></pre> <p>and here is my FeatureDetails Model,</p> <pre><code>public class FeatureDetails { private String featureSetName; private String featureName; private ArrayList&lt;FeatureKey&gt; featureKey; private String groupKey; private String groupValue; public FeatureDetails() { featureKey = new ArrayList&lt;FeatureKey&gt;(); } public ArrayList&lt;FeatureKey&gt; getFeatureKey() { return featureKey; } public void setFeatureKey(ArrayList&lt;FeatureKey&gt; featureKey) { this.featureKey = featureKey; } public String getGroupKey() { return groupKey; } public void setGroupKey(String groupKey) { this.groupKey = groupKey; } public String getGroupValue() { return groupValue; } public void setGroupValue(String groupValue) { this.groupValue = groupValue; } public String getFeatureName() { return featureName; } public void setFeatureName(String featureName) { this.featureName = featureName; } public String getFeatureSetName() { return featureSetName; } public void setFeatureSetName(String featureSetName) { this.featureSetName = featureSetName; } } </code></pre> <p>but i got an exception "com.google.gson.internal.LinkedHashTreeMap cannot be cast to com.asset.vsv.models.FeatureDetail".</p>
19,796,788
4
6
null
2013-11-05 18:55:32.777 UTC
4
2020-09-25 08:34:30.413 UTC
2013-11-05 19:04:25.863 UTC
null
801,763
null
801,763
null
1
26
java|json|gson
52,993
<p>try this:</p> <pre><code>HashMap&lt;String, FeatureDetails&gt; featuresFromJson = new Gson().fromJson(JSONFeatureSet, new TypeToken&lt;Map&lt;String, FeatureDetails&gt;&gt;() {}.getType()); </code></pre> <p>and when you going through your hash map do this:</p> <pre><code>for (Map.Entry&lt;String, FeatureDetails&gt; entry : featuresFromJson.entrySet()) { FeatureDetails featureDetails = entry.getValue(); } </code></pre>
21,640,561
JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors
<p>I'm attempting to send a XMLHttpRequest to a paste site. I'm sending an object containing all the fields that the api requires, but I keep getting this issue. I have read over the issue, and I thought:</p> <pre><code>httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); </code></pre> <p>Would fix it,but it didn't. Does anyone have any information on this error and/or how I can fix it?</p> <p>Here is my code:</p> <pre><code>(function () { 'use strict'; var httpReq = new XMLHttpRequest(); var url = 'http://paste.ee/api'; var fields = 'key=public&amp;description=test&amp;paste=this is a test paste&amp;format=JSON'; var fields2 = {key: 'public', description: 'test', paste: 'this is a test paste', format: 'JSON'}; httpReq.open('POST', url, true); console.log('good'); httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); httpReq.setRequestHeader('Content-type', 'application/ecmascript'); httpReq.setRequestHeader('Access-Control-Allow-Origin', '*'); console.log('ok'); httpReq.onreadystatechange = function () { console.log('test'); if (httpReq.readyState === 4 &amp;&amp; httpReq.status === 'success') { console.log('test'); alert(httpReq.responseText); } }; httpReq.send(fields2); }()); </code></pre> <p>And here is the exact console output:</p> <pre><code>good ok Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. http://paste.ee/api XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. index.html:1 test </code></pre> <p>Here is the console output when I test it locally on a regular Chromium browser:</p> <pre><code>good ok XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. index.html:1 test </code></pre>
21,640,909
3
10
null
2014-02-08 01:09:12.573 UTC
13
2021-09-01 09:54:03.047 UTC
2014-02-08 01:15:20.777 UTC
null
2,852,423
null
2,852,423
null
1
33
javascript|xmlhttprequest
179,522
<p>I think you've missed the point of access control.</p> <p>A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to <em>other sites</em>, masquerading as you and exploiting the trust <em>those sites</em> have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.</p> <p>Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. <code>paste.ee</code>) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.</p> <p>In your specific case, it seems that <code>paste.ee</code> doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).</p>
17,397,724
Point Sprites for particle system
<p>Are point sprites the best choice to build a particle system?</p> <p>Are point sprites present in the newer versions of OpenGL and drivers of the latest graphics cards? Or should I do it using vbo and glsl?</p>
17,400,234
1
0
null
2013-07-01 05:03:48.337 UTC
29
2014-07-02 14:32:07.7 UTC
2013-07-01 13:39:20.407 UTC
null
44,729
null
1,723,776
null
1
35
c++|c|opengl|glsl
21,574
<p>Point sprites are indeed well suited for particle systems. But they don't have anything to do with VBOs and GLSL, meaning they are a completely orthogonal feature. No matter if you use point sprites or not, you always have to use VBOs for uploading the geometry, be they just points, pre-made sprites or whatever, and you always have to put this geometry through a set of shaders (in modern OpenGL of course).</p> <p>That being said point sprites are very well supported in modern OpenGL, just not that automatically as with the old fixed-function approach. What is not supported are the point attenuation features that let you scale a point's size based on it's distance to the camera, you have to do this manually inside the vertex shader. In the same way you have to do the texturing of the point manually in an appropriate fragment shader, using the special input variable <code>gl_PointCoord</code> (that says where in the [0,1]-square of the whole point the current fragment is). For example a basic point sprite pipeline could look this way:</p> <pre><code>... glPointSize(whatever); //specify size of points in pixels glDrawArrays(GL_POINTS, 0, count); //draw the points </code></pre> <p>vertex shader:</p> <pre><code>uniform mat4 mvp; layout(location = 0) in vec4 position; void main() { gl_Position = mvp * position; } </code></pre> <p>fragment shader:</p> <pre><code>uniform sampler2D tex; layout(location = 0) out vec4 color; void main() { color = texture(tex, gl_PointCoord); } </code></pre> <p>And that's all. Of course those shaders just do the most basic drawing of textured sprites, but are a starting point for further features. For example to compute the sprite's size based on its distance to the camera (maybe in order to give it a fixed world-space size), you have to <code>glEnable(GL_PROGRAM_POINT_SIZE)</code> and write to the special output variable <code>gl_PointSize</code> in the vertex shader:</p> <pre><code>uniform mat4 modelview; uniform mat4 projection; uniform vec2 screenSize; uniform float spriteSize; layout(location = 0) in vec4 position; void main() { vec4 eyePos = modelview * position; vec4 projVoxel = projection * vec4(spriteSize,spriteSize,eyePos.z,eyePos.w); vec2 projSize = screenSize * projVoxel.xy / projVoxel.w; gl_PointSize = 0.25 * (projSize.x+projSize.y); gl_Position = projection * eyePos; } </code></pre> <p>This would make all point sprites have the same world-space size (and thus a different screen-space size in pixels).</p> <hr> <p>But point sprites while still being perfectly supported in modern OpenGL have their disadvantages. One of the biggest disadvantages is their clipping behaviour. Points are clipped at their center coordinate (because clipping is done before rasterization and thus before the point gets "enlarged"). So if the center of the point is outside of the screen, the rest of it that might still reach into the viewing area is not shown, so at the worst once the point is half-way out of the screen, it will suddenly disappear. This is however only noticable (or annyoing) if the point sprites are too large. If they are very small particles that don't cover much more than a few pixels each anyway, then this won't be much of a problem and I would still regard particle systems the canonical use-case for point sprites, just don't use them for large billboards.</p> <p>But if this is a problem, then modern OpenGL offers many other ways to implement point sprites, apart from the naive way of pre-building all the sprites as individual quads on the CPU. You can still render them just as a buffer full of points (and thus in the way they are likely to come out of your GPU-based particle engine). To actually generate the quad geometry then, you can use the geometry shader, which lets you generate a quad from a single point. First you do only the modelview transformation inside the vertex shader:</p> <pre><code>uniform mat4 modelview; layout(location = 0) in vec4 position; void main() { gl_Position = modelview * position; } </code></pre> <p>Then the geometry shader does the rest of the work. It combines the point position with the 4 corners of a generic [0,1]-quad and completes the transformation into clip-space:</p> <pre><code>const vec2 corners[4] = { vec2(0.0, 1.0), vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0) }; layout(points) in; layout(triangle_strip, max_vertices = 4) out; uniform mat4 projection; uniform float spriteSize; out vec2 texCoord; void main() { for(int i=0; i&lt;4; ++i) { vec4 eyePos = gl_in[0].gl_Position; //start with point position eyePos.xy += spriteSize * (corners[i] - vec2(0.5)); //add corner position gl_Position = projection * eyePos; //complete transformation texCoord = corners[i]; //use corner as texCoord EmitVertex(); } } </code></pre> <p>In the fragment shader you would then of course use the custom <code>texCoord</code> varying instead of <code>gl_PointCoord</code> for texturing, since we're no longer drawing actual points.</p> <hr> <p>Or another possibility (and maybe faster, since I remember geometry shaders having a reputation for being slow) would be to use instanced rendering. This way you have an additional VBO containing the vertices of <em>just a single generic 2D quad</em> (i.e. the [0,1]-square) and your good old VBO containing just the point positions. What you then do is draw this single quad multiple times (instanced), while sourcing the individual instances' positions from the point VBO:</p> <pre><code>glVertexAttribPointer(0, ...points...); glVertexAttribPointer(1, ...quad...); glVertexAttribDivisor(0, 1); //advance only once per instance ... glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); //draw #count quads </code></pre> <p>And in the vertex shader you then assemble the per-point position with the actual corner/quad-position (which is also the texture coordinate of that vertex):</p> <pre><code>uniform mat4 modelview; uniform mat4 projection; uniform float spriteSize; layout(location = 0) in vec4 position; layout(location = 1) in vec2 corner; out vec2 texCoord; void main() { vec4 eyePos = modelview * position; //transform to eye-space eyePos.xy += spriteSize * (corner - vec2(0.5)); //add corner position gl_Position = projection * eyePos; //complete transformation texCoord = corner; } </code></pre> <p>This achieves the same as the geometry shader based approach, properly-clipped point sprites with a consistent world-space size. If you actually want to mimick the screen-space pixel size of actual point sprites, you need to put some more computational effort into it. But this is left as an exercise and would be quite the oppisite of the world-to-screen transformation from the the point sprite shader.</p>
17,561,697
ArgumentError: A copy of ApplicationController has been removed from the module tree but is still active
<p>I am using ActiveAdmin (with customized gemset for Rails 4) with Rails 4.0.0.rc2. Application also has custom-built authorization code based on railscasts <a href="http://railscasts.com/episodes/385-authorization-from-scratch-part-1" rel="noreferrer">#385</a> and <a href="http://railscasts.com/episodes/386-authorization-from-scratch-part-2" rel="noreferrer">#386</a>.</p> <p>When I change something in a ActiveAdmin resource file and try to refresh the browser page, I get this error at the <code>current_permission</code> method:</p> <blockquote> <p><strong>ArgumentError at /admin/courses</strong></p> <p><strong>A copy of ApplicationController has been removed from the module tree but is still active!</strong></p> </blockquote> <p>If I try a refresh again, I get:</p> <blockquote> <p><strong>Circular dependency detected while autoloading constant Permissions</strong></p> </blockquote> <p>I think this problem has something to do with autoloading of classes in development mode, after a change in the source file. I have seen similar problem posts, but they are for rails 2.3.x. Also, the solution seems to be specifying <code>unloadable</code> in the controller throwing this error, but I am not sure where to put in this snippet in ActiveAdmin.</p> <p>This might not have anything to do with ActiveAdmin either. It might be about how Permissions class has been built and its usage within Application Controller. If I add a <code>skip_before_filter :authorize</code> in the ActiveAdmin resource class, this error vanishes.</p> <p>ApplicationController:</p> <pre><code>class ApplicationController &lt; ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :authenticate_user! before_filter :authorize delegate :allow_action?, to: :current_permission helper_method :allow_action? delegate :allow_param?, to: :current_permission helper_method :allow_param? private def current_permission @current_permission ||= Permissions.permission_for(current_user) end def current_resource nil end def authorize if current_permission.allow_action?(params[:controller], params[:action], current_resource) current_permission.permit_params! params else redirect_to root_url, alert: &quot;Not authorized.&quot; end end end </code></pre> <p>Permissions.rb:</p> <pre><code>module Permissions def self.permission_for(user) if user.nil? GuestPermission.new elsif user.admin? AdminPermission.new(user) else UserPermission.new(user) end end end </code></pre> <p>admin/courses.rb:</p> <pre><code>ActiveAdmin.register Course do index do column :name column :description column :duration column :status column :price default_actions end filter :discipline filter :level filter :lessons filter :name filter :status end </code></pre> <p>Gemfile (relevant lines):</p> <pre><code>gem 'rails', '4.0.0.rc2' # Use puma as the app server gem 'puma' # Administration - Temporary github refs until rails 4 compatible releases gem 'responders', github: 'plataformatec/responders' gem 'inherited_resources', github: 'josevalim/inherited_resources' gem 'ransack', github: 'ernie/ransack', branch: 'rails-4' gem 'activeadmin', github: 'gregbell/active_admin', branch: 'rails4' gem 'formtastic', github: 'justinfrench/formtastic' </code></pre> <p>ArgumentError:</p> <pre><code>ArgumentError - A copy of ApplicationController has been removed from the module tree but is still active!: activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:445:in `load_missing_constant' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:183:in `const_missing' rspec-core (2.13.1) lib/rspec/core/backward_compatibility.rb:24:in `const_missing' app/controllers/application_controller.rb:17:in `current_permission' app/controllers/application_controller.rb:25:in `authorize' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:417:in `_run__1040990970961152968__process_action__callbacks' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:80:in `run_callbacks' actionpack (4.0.0.rc2) lib/abstract_controller/callbacks.rb:17:in `process_action' actionpack (4.0.0.rc2) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (4.0.0.rc2) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action' activesupport (4.0.0.rc2) lib/active_support/notifications.rb:159:in `block in instrument' activesupport (4.0.0.rc2) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.0.0.rc2) lib/active_support/notifications.rb:159:in `instrument' actionpack (4.0.0.rc2) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (4.0.0.rc2) lib/action_controller/metal/params_wrapper.rb:245:in `process_action' activerecord (4.0.0.rc2) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (4.0.0.rc2) lib/abstract_controller/base.rb:136:in `process' actionpack (4.0.0.rc2) lib/abstract_controller/rendering.rb:44:in `process' actionpack (4.0.0.rc2) lib/action_controller/metal.rb:195:in `dispatch' actionpack (4.0.0.rc2) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' actionpack (4.0.0.rc2) lib/action_controller/metal.rb:231:in `block in action' actionpack (4.0.0.rc2) lib/action_dispatch/routing/route_set.rb:80:in `dispatch' actionpack (4.0.0.rc2) lib/action_dispatch/routing/route_set.rb:48:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/journey/router.rb:71:in `block in call' actionpack (4.0.0.rc2) lib/action_dispatch/journey/router.rb:59:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/routing/route_set.rb:655:in `call' omniauth (1.1.4) lib/omniauth/strategy.rb:184:in `call!' omniauth (1.1.4) lib/omniauth/strategy.rb:164:in `call' omniauth (1.1.4) lib/omniauth/strategy.rb:184:in `call!' omniauth (1.1.4) lib/omniauth/strategy.rb:164:in `call' omniauth (1.1.4) lib/omniauth/strategy.rb:184:in `call!' omniauth (1.1.4) lib/omniauth/strategy.rb:164:in `call' newrelic_rpm (3.6.4.122) lib/new_relic/rack/error_collector.rb:12:in `call' newrelic_rpm (3.6.4.122) lib/new_relic/rack/agent_hooks.rb:22:in `call' newrelic_rpm (3.6.4.122) lib/new_relic/rack/browser_monitoring.rb:16:in `call' newrelic_rpm (3.6.4.122) lib/new_relic/rack/developer_mode.rb:28:in `call' meta_request (0.2.7) lib/meta_request/middlewares/app_request_handler.rb:13:in `call' rack-contrib (1.1.0) lib/rack/contrib/response_headers.rb:17:in `call' meta_request (0.2.7) lib/meta_request/middlewares/headers.rb:16:in `call' meta_request (0.2.7) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call' warden (1.2.1) lib/warden/manager.rb:35:in `block in call' warden (1.2.1) lib/warden/manager.rb:34:in `call' rack (1.5.2) lib/rack/etag.rb:23:in `call' rack (1.5.2) lib/rack/conditionalget.rb:25:in `call' rack (1.5.2) lib/rack/head.rb:11:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/flash.rb:241:in `call' rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context' rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/cookies.rb:486:in `call' activerecord (4.0.0.rc2) lib/active_record/query_cache.rb:36:in `call' activerecord (4.0.0.rc2) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call' activerecord (4.0.0.rc2) lib/active_record/migration.rb:369:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:373:in `_run__2183739952227501342__call__callbacks' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:80:in `run_callbacks' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/reloader.rb:64:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/remote_ip.rb:76:in `call' better_errors (0.9.0) lib/better_errors/middleware.rb:84:in `protected_app_call' better_errors (0.9.0) lib/better_errors/middleware.rb:79:in `better_errors_call' better_errors (0.9.0) lib/better_errors/middleware.rb:56:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.0.0.rc2) lib/rails/rack/logger.rb:38:in `call_app' railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `block in call' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `block in tagged' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:25:in `tagged' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `tagged' railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.5.2) lib/rack/methodoverride.rb:21:in `call' rack (1.5.2) lib/rack/runtime.rb:17:in `call' activesupport (4.0.0.rc2) lib/active_support/cache/strategy/local_cache.rb:83:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/static.rb:64:in `call' railties (4.0.0.rc2) lib/rails/engine.rb:511:in `call' railties (4.0.0.rc2) lib/rails/application.rb:97:in `call' rack (1.5.2) lib/rack/content_length.rb:14:in `call' puma (2.1.1) lib/puma/server.rb:369:in `handle_request' puma (2.1.1) lib/puma/server.rb:246:in `process_client' puma (2.1.1) lib/puma/server.rb:145:in `block in run' puma (2.1.1) lib/puma/thread_pool.rb:92:in `block in spawn_thread' </code></pre> <p>RuntimeError: Circular Dependency:</p> <pre><code>RuntimeError - Circular dependency detected while autoloading constant Permissions: activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:460:in `load_missing_constant' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:183:in `const_missing' rspec-core (2.13.1) lib/rspec/core/backward_compatibility.rb:24:in `const_missing' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:686:in `remove_constant' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:516:in `block in remove_unloadable_constants!' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:516:in `remove_unloadable_constants!' activesupport (4.0.0.rc2) lib/active_support/dependencies.rb:300:in `clear' railties (4.0.0.rc2) lib/rails/application/finisher.rb:90:in `block (2 levels) in &lt;module:Finisher&gt;' activesupport (4.0.0.rc2) lib/active_support/file_update_checker.rb:75:in `execute' railties (4.0.0.rc2) lib/rails/application/finisher.rb:105:in `block (2 levels) in &lt;module:Finisher&gt;' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:377:in `_run__2753119820186226816__prepare__callbacks' activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:80:in `run_callbacks' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/reloader.rb:74:in `prepare!' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/reloader.rb:62:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/remote_ip.rb:76:in `call' better_errors (0.9.0) lib/better_errors/middleware.rb:84:in `protected_app_call' better_errors (0.9.0) lib/better_errors/middleware.rb:79:in `better_errors_call' better_errors (0.9.0) lib/better_errors/middleware.rb:56:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.0.0.rc2) lib/rails/rack/logger.rb:38:in `call_app' railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `block in call' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `block in tagged' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:25:in `tagged' activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `tagged' railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.5.2) lib/rack/methodoverride.rb:21:in `call' rack (1.5.2) lib/rack/runtime.rb:17:in `call' activesupport (4.0.0.rc2) lib/active_support/cache/strategy/local_cache.rb:83:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' actionpack (4.0.0.rc2) lib/action_dispatch/middleware/static.rb:64:in `call' railties (4.0.0.rc2) lib/rails/engine.rb:511:in `call' railties (4.0.0.rc2) lib/rails/application.rb:97:in `call' rack (1.5.2) lib/rack/content_length.rb:14:in `call' puma (2.1.1) lib/puma/server.rb:369:in `handle_request' puma (2.1.1) lib/puma/server.rb:246:in `process_client' puma (2.1.1) lib/puma/server.rb:145:in `block in run' puma (2.1.1) lib/puma/thread_pool.rb:92:in `block in spawn_thread' </code></pre> <p>Any clue will help. Let me know if you need to view other code snippets in the application.</p>
18,423,438
5
1
null
2013-07-10 02:48:20.867 UTC
13
2021-02-23 13:24:50.83 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,858,466
null
1
50
ruby-on-rails|activeadmin|ruby-on-rails-4
28,684
<p>I'm not sure exactly why this is happening, but I found a workaound. Change this:</p> <pre><code>def current_permission @current_permission ||= Permissions.permission_for(current_user) end </code></pre> <p>To this:</p> <pre><code>def current_permission @current_permission ||= ::Permissions.permission_for(current_user) end </code></pre> <p>The error is raised <a href="https://github.com/rails/rails/blob/375d9a0a7fb329b0fbbd75a13e93e53a00520587/activesupport/lib/active_support/dependencies.rb#L444-L446">at this point in ActiveSupport</a>:</p> <pre><code># Load the constant named +const_name+ which is missing from +from_mod+. If # it is not possible to load the constant into from_mod, try its parent # module using +const_missing+. def load_missing_constant(from_mod, const_name) log_call from_mod, const_name unless qualified_const_defined?(from_mod.name) &amp;&amp; Inflector.constantize(from_mod.name).equal?(from_mod) raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!" end # ... end </code></pre> <p>The problem only occurs when you don't fully qualify the constant name, so Rails tries looking it up in the <code>ApplicationController</code> namespace.</p>
17,570,446
How do I add Git version control (Bitbucket) to an existing source code folder?
<p>How can I add the contents of an existing folder to Git version control?</p> <p>The tutorial <a href="https://confluence.atlassian.com/display/BITBUCKET/Create+an+Account+and+a+Git+Repo" rel="noreferrer">here</a> covers the case of making a directory and then adding source contents to it. I have some source code in a folder that is path dependent and don't want to move it.</p> <p>So, how can I just go into my folder and make it a repository?</p>
36,550,960
5
4
null
2013-07-10 11:03:15.6 UTC
45
2017-11-29 23:00:46.707 UTC
2017-11-29 22:53:30.803 UTC
null
63,550
user1406716
1,406,716
null
1
86
git|bitbucket
150,794
<p><strong>Final working solution</strong> using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:</p> <ol> <li>Suppose you have your project folder on PC;</li> <li><p>Create a new repository on bitbucket: <a href="https://i.stack.imgur.com/yOLBC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/yOLBC.jpg" alt="enter image description here"></a></p></li> <li><p>Press on <em>I have an existing project</em>: <a href="https://i.stack.imgur.com/4tj5n.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/4tj5n.jpg" alt="enter image description here"></a></p></li> <li><p>Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)</p></li> <li><p>Type command <code>git init</code></p></li> <li><p>Type command <code>git add --all</code></p></li> <li><p>Type command 2 from second picture (<code>git remote add origin YOUR_LINK_TO_REPO</code>)</p></li> <li><p>Type command <code>git commit -m "my first commit"</code></p></li> <li><p>Type command <code>git push -u origin master</code></p></li> </ol> <p>Note: if you get error unable to detect email or name, just type following commands after 5th step:</p> <pre><code> git config --global user.email "yourEmail" #your email at Bitbucket git config --global user.name "yourName" #your name at Bitbucket </code></pre>
17,510,688
Single script to run in both Windows batch and Linux Bash?
<p>Is it possible to write a single script file which executes in both Windows (treated as .bat) and Linux (via Bash)?</p> <p>I know the basic syntax of both, but didn't figure out. It could probably exploit some Bash's obscure syntax or some Windows batch processor glitch.</p> <p>The command to execute may be just a single line to execute other script.</p> <p>The motivation is to have just a single application boot command for both Windows and Linux.</p> <p><strong>Update:</strong> The need for system's "native" shell script is that it needs to pick the right interpreter version, conform to certain well-known environment variables etc. Installing additional environments like CygWin is not preferable - I'd like to keep the concept "download &amp; run".</p> <p>The only other language to consider for Windows is Windows Scripting Host - WSH, which is preset by default since 98.</p>
17,623,721
11
6
null
2013-07-07 09:05:48.81 UTC
45
2022-02-02 17:10:41.753 UTC
2013-07-07 13:05:45.69 UTC
null
145,989
null
145,989
null
1
112
bash|batch-file
55,018
<p>What I have done is <a href="http://www.robvanderwoude.com/comments.php" rel="noreferrer">use cmd’s label syntax as comment marker</a>. The label character, a colon (<code>:</code>), is equivalent to <code>true</code> in most POSIXish shells. If you immediately follow the label character by another character which can’t be used in a <code>GOTO</code>, then commenting your <code>cmd</code> script should not affect your <code>cmd</code> code.</p> <p>The hack is to put lines of code after the character sequence “<code>:;</code>”. If you’re writing mostly one-liner scripts or, as may be the case, can write one line of <code>sh</code> for many lines of <code>cmd</code>, the following might be fine. Don’t forget that any use of <code>$?</code> must be before your next colon <code>:</code> because <code>:</code> resets <code>$?</code> to 0.</p> <pre><code>:; echo "Hi, I’m ${SHELL}."; exit $? @ECHO OFF ECHO I'm %COMSPEC% </code></pre> <p>A very contrived example of guarding <code>$?</code>:</p> <pre><code>:; false; ret=$? :; [ ${ret} = 0 ] || { echo "Program failed with code ${ret}." &gt;&amp;2; exit 1; } :; exit ECHO CMD code. </code></pre> <p>Another idea for skipping over <code>cmd</code> code is to use <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_07_04" rel="noreferrer">heredocs</a> so that <code>sh</code> treats the <code>cmd</code> code as an unused string and <code>cmd</code> interprets it. In this case, we make sure that our heredoc’s delimiter is both quoted (to stop <code>sh</code> from doing any sort of interpretation on its contents when running with <code>sh</code>) and starts with <code>:</code> so that <code>cmd</code> skips over it like any other line starting with <code>:</code>.</p> <pre><code>:; echo "I am ${SHELL}" :&lt;&lt;"::CMDLITERAL" ECHO I am %COMSPEC% ::CMDLITERAL :; echo "And ${SHELL} is back!" :; exit ECHO And back to %COMSPEC% </code></pre> <p>Depending on your needs or coding style, interlacing <code>cmd</code> and <code>sh</code> code may or may not make sense. Using heredocs is one method to perform such interlacing. This could, however, be extended with the <a href="https://stackoverflow.com/a/17510832/429091"><code>GOTO</code> technique</a>:</p> <pre><code>:&lt;&lt;"::CMDLITERAL" @ECHO OFF GOTO :CMDSCRIPT ::CMDLITERAL echo "I can write free-form ${SHELL} now!" if :; then echo "This makes conditional constructs so much easier because" echo "they can now span multiple lines." fi exit $? :CMDSCRIPT ECHO Welcome to %COMSPEC% </code></pre> <p>Universal comments, of course, can be done with the character sequence <code>: #</code> or <code>:;#</code>. The space or semicolon are necessary because <code>sh</code> considers <code>#</code> to be part of a command name if it is not the first character of an identifier. For example, you might want to write universal comments in the first lines of your file before using the <code>GOTO</code> method to split your code. Then you can inform your reader of why your script is written so oddly:</p> <pre><code>: # This is a special script which intermixes both sh : # and cmd code. It is written this way because it is : # used in system() shell-outs directly in otherwise : # portable code. See https://stackoverflow.com/questions/17510688 : # for details. :; echo "This is ${SHELL}"; exit @ECHO OFF ECHO This is %COMSPEC% </code></pre> <p>Thus, some ideas and ways to accomplish <code>sh</code> and <code>cmd</code>-compatible scripts without serious side effects as far as I know (and without having <code>cmd</code> output <code>'#' is not recognized as an internal or external command, operable program or batch file.</code>).</p>
18,596,732
Specifying custom screen resolution in Selenium tests
<p>As mentioned in the below blog, we can modify screen resolution during selenium test runs. <a href="http://blog.testingbot.com/2013/03/15/screen-resolution-option-now-available-for-all-selenium-tests" rel="noreferrer">http://blog.testingbot.com/2013/03/15/screen-resolution-option-now-available-for-all-selenium-tests</a></p> <p>Tried the below code(as mentioned in "<a href="https://saucelabs.com/docs/additional-config" rel="noreferrer">https://saucelabs.com/docs/additional-config</a>"), but not setting the specified resolution. Is this still not available for Selenium?</p> <pre><code>DesiredCapabilities dc=new DesiredCapabilities(); dc.setCapability("screen-resolution","1280x1024"); </code></pre>
18,608,119
4
1
null
2013-09-03 16:02:41.81 UTC
1
2018-10-01 04:35:06.763 UTC
2018-10-01 04:35:06.763 UTC
null
2,622,033
null
2,622,033
null
1
14
java|selenium|webdriver|screen-resolution
49,729
<p>Sauce Labs != Selenium</p> <p>Sauce labs use that capability to provision you a VM with the desired resolution, it's not a capability that Selenium itself knows about.</p> <p><strong>Selenium is not capable of modifying your desktop resolution!</strong></p> <p>If you want to modify your browser size in Selenium so that it matches a specific resolution you can do a:</p> <pre><code>driver.manage().window().setSize(new Dimension(1024, 768)) </code></pre> <p>The above is not supported with Opera driver, so instead you would need to do:</p> <pre><code>DesiredCapabilities capabilities = DesiredCapabilities.opera() capabilities.setCapability("opera.arguments", "-screenwidth 1024 -screenheight 768") </code></pre> <p>While setting the browser size is not the same as setting the screen resolution, it should for all intents and purposes meet your requirements.</p>
26,109,264
pip, proxy authentication and "Not supported proxy scheme"
<p>Trying to install pip on a new python installation. I am stuck with proxy errors. Looks like a bug in <code>get-pip</code> or <code>urllib3</code>??</p> <p>Question is do I have to go through the pain of setting up <a href="https://stackoverflow.com/questions/14149422/using-pip-behind-a-proxy">CNTLM as described here</a> or is there a shortcut?</p> <p><a href="http://pip.readthedocs.org/en/latest/installing.html" rel="noreferrer">get-pip.py documentation</a> says use <code>--proxy="[user:passwd@]proxy.server:port"</code> option to specify proxy and relevant authentication. But seems like pip passes on the whole thing as it is to <code>urllib3</code> which interprets "myusr" as the url scheme, because of the ':' I guess (?).</p> <pre><code>C:\ProgFiles\Python27&gt;get-pip.py --proxy myusr:[email protected]:80 Downloading/unpacking pip Cleaning up... Exception: Traceback (most recent call last): File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\basecommand.py", line 122, in main status = self.run(options, args) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\commands\install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\req.py", line 1177, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\index.py", line 194, in find_requirement page = self._get_page(main_index_url, req) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\index.py", line 568, in _get_page session=self.session, File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\index.py", line 670, in get_page resp = session.get(url, headers={"Accept": "text/html"}) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\sessions.py", line 468, in get return self.request('GET', url, **kwargs) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\download.py", line 237, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\sessions.py", line 456, in request resp = self.send(prep, **send_kwargs) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\sessions.py", line 559, in send r = adapter.send(request, **kwargs) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\adapters.py", line 305, in send conn = self.get_connection(request.url, proxies) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\adapters.py", line 215, in get_connection block=self._pool_block) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\packages\urllib3\poolmanager.py", line 258, in proxy_fro m_url return ProxyManager(proxy_url=url, **kw) File "c:\users\sg0219~1\appdata\local\temp\tmpxwg_en\pip.zip\pip\_vendor\requests\packages\urllib3\poolmanager.py", line 214, in __init__ 'Not supported proxy scheme %s' % self.proxy.scheme AssertionError: Not supported proxy scheme myusr Storing debug log for failure in C:\Users\myusr\pip\pip.log C:\ProgFiles\Python27&gt; </code></pre> <p>When I run the command without the usrname and password it works fine, but proxy rejects the request saying it needs authentication ("407 authenticationrequired").</p> <pre><code>C:\ProgFiles\Python27&gt;get-pip.py --proxy 111.222.333.444:80 Downloading/unpacking pip Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement pip Cleaning up... No distributions at all found for pip Storing debug log for failure in C:\Users\sg0219898\pip\pip.log C:\ProgFiles\Python27&gt;cat C:\Users\sg0219898\pip\pip.log ------------------------------------------------------------ C:\ProgFiles\Python27\get-pip.py run on 09/29/14 16:23:26 Downloading/unpacking pip Getting page https://pypi.python.org/simple/pip/ Could not fetch URL https://pypi.python.org/simple/pip/: connection error: ('Cannot connect to proxy.', error('Tunnel connection failed: 407 authenticationrequired',)) Will skip URL https://pypi.python.org/simple/pip/ when looking for download links for pip Getting page https://pypi.python.org/simple/ Could not fetch URL https://pypi.python.org/simple/: connection error: ('Cannot connect to proxy.', error('Tunnel connection failed: 407 authenticationrequired',)) Will skip URL https://pypi.python.org/simple/ when looking for download links for pip Cannot fetch index base URL https://pypi.python.org/simple/ URLs to search for versions for pip: * https://pypi.python.org/simple/pip/ Getting page https://pypi.python.org/simple/pip/ Could not fetch URL https://pypi.python.org/simple/pip/: connection error: ('Cannot connect to proxy.', error('Tunnel connection failed: 407 authenticationrequired',)) Will skip URL https://pypi.python.org/simple/pip/ when looking for download links for pip Could not find any downloads that satisfy the requirement pip Cleaning up... Removing temporary dir c:\users\sg0219~1\appdata\local\temp\pip_build_SG0219898... No distributions at all found for pip Exception information: Traceback (most recent call last): File "c:\users\sg0219~1\appdata\local\temp\tmp36ynxd\pip.zip\pip\basecommand.py", line 122, in main status = self.run(options, args) File "c:\users\sg0219~1\appdata\local\temp\tmp36ynxd\pip.zip\pip\commands\install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "c:\users\sg0219~1\appdata\local\temp\tmp36ynxd\pip.zip\pip\req.py", line 1177, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "c:\users\sg0219~1\appdata\local\temp\tmp36ynxd\pip.zip\pip\index.py", line 277, in find_requirement raise DistributionNotFound('No distributions at all found for %s' % req) DistributionNotFound: No distributions at all found for pip C:\ProgFiles\Python27&gt; </code></pre> <p>I had a brief look at <a href="https://github.com/shazow/urllib3/blob/master/urllib3/poolmanager.py" rel="noreferrer"><code>urllib3\poolmanager.py</code></a> and it doesn't seem to have anything to do with username/passwords.</p>
26,123,205
9
2
null
2014-09-29 21:31:16.843 UTC
2
2022-01-12 06:22:06.653 UTC
2017-05-23 12:02:21.55 UTC
null
-1
null
496,289
null
1
19
python|pip|urllib|pypi|urllib3
73,195
<p>This is complaining about the scheme for the URL (which <code>urlparse</code> is understanding to be <code>myusr</code>), to work around that you should instead be doing:</p> <pre><code>get-pip.py --proxy http://myusr:[email protected]:80 </code></pre>
9,666,362
Automated Export to CSV Using SQL Server Management Studio
<p>Using Microsoft SQL Server Management Studio, I have created a view, which pulls in columns from several tables. I need to export this view into a CSV file on a weekly basis, and so I would like to set up some sort of automated process for this. I have read many examples of how I can do a simple right click and "Save Results As", or using the export wizard, but I do not know how I can automate this process to run weekly.</p> <p>I am somewhat of a newbie with all things microsoft, so any help is much appreciated, thanks!</p>
9,666,435
3
1
null
2012-03-12 11:40:47.587 UTC
3
2022-02-12 16:28:25.133 UTC
null
null
null
null
931,002
null
1
2
sql|sql-server|sql-server-2008
46,826
<p>What you need is to schedule a job to run every week. Please have a look at here <a href="http://msdn.microsoft.com/en-us/library/ms191439.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms191439.aspx</a></p>
5,296,290
NOTICES for sequence after running migration in rails on postgresql Application
<p>When i run my migration in Rails application on postgresql i got following NOTICES </p> <pre><code>NOTICE: CREATE TABLE will create implicit sequence "notification_settings_id_seq" for serial column "notification_settings.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "notification_settings_pkey" for table "notification_settings" </code></pre> <p>My migration file contains 088_create_notification_settings.rb</p> <pre><code>class CreateNotificationSettings &lt; ActiveRecord::Migration def self.up create_table :notification_settings do |t| t.integer :user_id t.integer :notification_id t.boolean :notification_on t.boolean :outbound end end def self.down drop_table :notification_settings end end </code></pre> <p>I would like to know </p> <p>what this NOTICES means?</p> <p>How to avoid this NOTICES?</p> <p>What will be the impact of such NOTICES on the Application if not avoided?</p> <p>Regards,</p> <p>Salil</p>
5,296,464
3
0
null
2011-03-14 08:29:06.44 UTC
9
2013-02-03 01:41:44.307 UTC
2011-03-14 08:34:59.167 UTC
null
21,234
null
297,087
null
1
34
ruby-on-rails|ruby|postgresql|database-migration
5,420
<p>Rails (ActiveRecord to be more precise) is adding an <code>id</code> column to your table and making this column the primary key. For PostgreSQL, this column will have type <code>serial</code>. A <a href="http://www.postgresql.org/docs/current/static/datatype-numeric.html" rel="noreferrer"><code>serial</code> column</a> is essentially a four byte integer combined with a sequence to automatically provide auto-incrementing values.</p> <p>The first notice:</p> <blockquote> <p>NOTICE: CREATE TABLE will create implicit sequence "notification_settings_id_seq" for serial column "notification_settings.id"</p> </blockquote> <p>is just telling you that PostgreSQL is creating a sequence behind the scenes to make the <code>serial</code> column function.</p> <p>The second notice:</p> <blockquote> <p>NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "notification_settings_pkey" for table "notification_settings"</p> </blockquote> <p>is just telling you that PostgreSQL is creating an index to help implement the primary key even though you didn't explicitly ask it to.</p> <p>You can just ignore these notices, they're just informational. If you want to suppress them, you can add <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html" rel="noreferrer"><code>min_messages: WARNING</code></a> to the appropriate section of your <code>database.yml</code>.</p>
5,082,249
pushing to git remote branch
<p>I could use a hand with learning how to push a local branch to a remote branch. Please see below. Help much appreciated!</p> <p>The local branch was created after cloning the repo then doing</p> <pre><code>$ git checkout -b mybranch remotes/origin/mybranch $ git branch -a master * mybranch remotes/origin/HEAD -&gt; origin/master remotes/origin/master remotes/origin/mybranch </code></pre> <p>But when trying to push changes back up:</p> <pre><code>$ git push mybranch mybranch fatal: 'mybranch' does not appear to be a git repository fatal: The remote end hung up unexpectedly $ git push remotes/origin/mybranch mybranch fatal: 'mybranch' does not appear to be a git repository fatal: The remote end hung up unexpectedly $ git push origin/mybranch mybranch fatal: 'mybranch' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre>
5,082,389
3
0
null
2011-02-22 18:31:01.323 UTC
19
2017-11-24 07:05:07.583 UTC
null
null
null
null
208,367
null
1
38
git|github
91,799
<p>Try</p> <pre><code>git push origin mybranch </code></pre> <p>This pushes your branch named <strong>mybranch</strong> to the remote named <strong>origin</strong></p>
9,121,233
Quick Java String/toString Printing one char on each line
<p>I need to take a String, and print each character of it on a seperate line.</p> <p>I would use a for loop right?</p> <pre><code> public String toString(){ for (int count=0; count &lt; password.length(); count++) { System.out.print(password.charAt(count)); System.out.print("\n"); } return password; // I am confused on this. I don't want it to //return anything, really but I cannot make return type void } </code></pre> <p>Is what I have, but I keep getting NullPointExceptions. I have a method above that stores the password from the input, and the variable is defined in the class. So, I figured it would pull it from that. </p> <p>My Question is: How would I take a string and print each character from it, one on each line?</p>
9,121,309
5
3
null
2012-02-02 22:53:49.613 UTC
3
2017-11-25 11:18:38.917 UTC
null
null
null
null
1,176,922
null
1
3
java|string
67,308
<p>This would do the job:</p> <pre class="lang-java prettyprint-override"><code>String s = "someString"; for (int i = 0; i &lt; s.length(); i++) { System.out.println(s.charAt(i)); } </code></pre>
9,559,372
How to set .net Framework 4.5 version in IIS 7 application pool
<p>I installed the Visual Studio 11 Beta and suddenly all the async action methods I had created under the VS 11 Developer preview started hanging (apparently this issue: <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/03/03/10277166.aspx" rel="noreferrer">http://blogs.msdn.com/b/pfxteam/archive/2012/03/03/10277166.aspx</a>).</p> <p>My app is using v4.0.30319 as the Framework Version, but there is no option to use 4.5. I repaired my .net 4.5 install to be sure, but nothing. Is there a way to configure this in IIS? Do I need to bin deploy the files (and if so which)? </p>
9,559,405
3
4
null
2012-03-04 22:21:21.543 UTC
33
2017-08-12 04:02:21.47 UTC
null
null
null
null
122,589
null
1
204
.net|visual-studio|iis
353,561
<p>There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.</p>
20,296,929
UICollectionView update a single cell
<p>I am attempting to update a single cell inside a <code>UICollectionView</code>, specifically I am just trying to update an image in that specific cell detonated by <code>cell.imageView</code>. <code>[self.collectionView reloadData]</code> is not really an option because it makes the whole collection view flash. <code>[self.collectionView beginUpdates]</code> is not a thing in a <code>UICollectionView</code>it seems. </p> <p>I understand I may be able to use:</p> <pre><code>[self.collectionView performBatchUpdates:^{ //do something } completion:nil]; </code></pre> <p>I am not exactly sure what to put inside a completion block to update that certain cell's <code>imageView</code>. This is all being done inside of <code>didSelectItemAtIndexPath</code>.Also I am not using <code>NSFetchedResultsController</code>. Any ideas?</p>
20,297,056
3
2
null
2013-11-30 05:30:57 UTC
12
2013-12-02 06:08:59.057 UTC
null
null
null
null
1,933,131
null
1
56
ios|objective-c|uitableview|uicollectionview|uicollectionviewcell
67,973
<p><code>- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths</code></p> <p>Here it is a method to reload the specific <code>indexPaths</code> in your <code>collectionView</code></p>
15,217,524
What is the difference between thread per connection vs thread per request?
<p>Can you please explain the two methodologies which has been implemented in various servlet implementations:</p> <ol> <li>Thread per connection</li> <li>Thread per request</li> </ol> <p>Which of the above two strategies scales better and why?</p>
15,223,098
5
1
null
2013-03-05 06:50:06.177 UTC
26
2018-06-12 13:06:13.51 UTC
2013-03-05 10:17:39.36 UTC
null
1,527,084
null
1,527,084
null
1
39
java|multithreading|http|servlets
36,694
<blockquote> <p>Which of the above two strategies scales better and why?</p> </blockquote> <p>Thread-per-request scales better than thread-per-connection.</p> <p>Java threads are rather expensive, typically using a 1Mb memory segment each, whether they are active or idle. If you give each connection its own thread, the thread will typically sit idle between successive requests on the connection. Ultimately the framework needs to either stop accepting new connections ('cos it can't create any more threads) or start disconnecting old connections (which leads to connection churn if / when the user wakes up).</p> <p>HTTP connection requires significantly less resources than a thread stack, although there is a limit of 64K open connections per IP address, due to the way that TCP/IP works.</p> <p>By contrast, in the thread-per-request model, the thread is only associated while a request is being processed. That usually means that the service needs fewer threads to handle the same number of users. And since threads use significant resources, that means that the service will be more scalable.</p> <p>(And note that thread-per-request does not mean that the framework has to close the TCP connection between HTTP request ...)</p> <hr> <p>Having said that, the thread-per-request model is not ideal when there are long pauses during the processing of each request. (And it is especially non-ideal when the service uses the <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29" rel="noreferrer">comet</a> approach which involves keeping the reply stream open for a long time.) To support this, the Servlet 3.0 spec provides an "asynchronous servlet" mechanism which allows a servlet's request method to suspend its association with the current request thread. This releases the thread to go and process another request.</p> <p>If the web application can be designed to use the "asynchronous" mechanism, it is likely to be more scalable than either thread-per-request or thread-per-connection.</p> <hr> <p><strong>FOLLOWUP</strong></p> <blockquote> <p>Let's assume a single webpage with 1000 images. This results in 1001 HTTP requests. Further let's assume HTTP persistent connections is used. With the TPR strategy, this will result in 1001 thread pool management operations (TPMO). With the TPC strategy, this will result in 1 TPMO... Now depending on the actual costs for a single TPMO, I can imagine scenarios where TPC may scale better then TPR.</p> </blockquote> <p>I think there are some things you haven't considered:</p> <ul> <li><p>The web browser faced with lots of URLs to fetch to complete a page may well open multiple connections.</p></li> <li><p>With TPC and persistent connections, the thread has to wait for the client to receive the response and send the next request. This wait time could be significant if the network latency is high. </p></li> <li><p>The server has no way of knowing when a given (persistent) connection can be closed. If the browser doesn't close it, it could "linger", tying down the TPC thread until the server times out the connection.</p></li> <li><p>The TPMO overheads are not huge, especially when you separate the pool overheads from the context switch overheads. (You need to do that, since TPC is going to incur context switches on a persistent connections; see above.)</p></li> </ul> <p>My feeling is that these factors are likely to outweigh the TPMO saving of having one thread dedicated to each connection.</p>
8,223,742
How to pass multiple parameters to a thread in C
<p>I am trying to pass two parameters to a thread in C. I have created an array (of size 2) and am trying to pass that array into the thread. Is this the right approach of passing multiple parameters into a thread ?</p> <pre><code>// parameters of input. These are two random numbers int track_no = rand()%15; // getting the track number for the thread int number = rand()%20 + 1; // this represents the work that needs to be done int *parameters[2]; parameters[0]=track_no; parameters[1]=number; // the thread is created here pthread_t server_thread; int server_thread_status; //somehow pass two parameters into the thread server_thread_status = pthread_create(&amp;server_thread, NULL, disk_access, parameters); </code></pre>
8,223,833
2
3
null
2011-11-22 08:12:24.44 UTC
3
2011-11-22 10:07:22.513 UTC
2011-11-22 09:42:52.867 UTC
null
694,576
null
775,936
null
1
13
c|pthreads|posix
40,529
<p>Since you pass in a void pointer, it can point to anything, including a structure, as per the following <em>example:</em></p> <pre><code>typedef struct s_xyzzy { int num; char name[20]; float secret; } xyzzy; xyzzy plugh; plugh.num = 42; strcpy (plugh.name, "paxdiablo"); plugh.secret = 3.141592653589; status = pthread_create (&amp;server_thread, NULL, disk_access, &amp;plugh); // pthread_join down here somewhere to ensure plugh // stay in scope while server_thread is using it. </code></pre>
9,081,479
Is there a good reason for always enclosing a define in parentheses in C?
<p>Clearly, there are times where <code>#define</code> statements must have parentheses, like so:</p> <pre><code>#define WIDTH 80+20 int a = WIDTH * 2; // expect a==200 but a==120 </code></pre> <p>So I always parenthesize, even when it's just a single number:</p> <pre><code>#define WIDTH (100) </code></pre> <p>Someone new to C asked me why I do this, so I tried to find an edge case where the absence of parentheses on a single number <code>#define</code> causes issues, but I can't think of one.</p> <p>Does such a case exist?</p>
9,081,708
9
7
null
2012-01-31 14:46:01.657 UTC
17
2019-10-01 15:59:22.833 UTC
2019-04-17 02:06:53.623 UTC
null
10,795,151
null
360,211
null
1
59
c|c-preprocessor|parentheses
26,366
<p><strong>Yes</strong>. The preprocessor concatenation operator (<code>##</code>) will cause issues, for example:</p> <pre><code>#define _add_penguin(a) penguin ## a #define add_penguin(a) _add_penguin(a) #define WIDTH (100) #define HEIGHT 200 add_penguin(HEIGHT) // expands to penguin200 add_penguin(WIDTH) // error, cannot concatenate penguin and (100) </code></pre> <p>Same for stringization (<code>#</code>). Clearly this is a corner case and probably doesn't matter considering how <code>WIDTH</code> will presumably be used. Still, it is something to keep in mind about the preprocessor.</p> <p>(The reason why adding the second penguin fails is a subtle detail of the preprocessing rules in C99 - <em>iirc</em> it fails because concatenating to two non-placeholder preprocessing tokens must always result in a single preprocessing token - but this is irrelevant, even if the concatenation was allowed it would still give a different result than the unbracketed <code>#define</code>!).</p> <p>All other responses are correct only insofar that it doesn't matter from the point of view of the C++ scanner because, indeed, a number is atomic. However, to my reading of the question there is no sign that only cases with no further preprocessor expansion should be considered, so the other responses are, even though I totally agree with the advice contained therein, wrong.</p>
9,290,498
How can I limit Parallel.ForEach?
<p>I have a Parallel.ForEach() async loop with which I download some webpages. My bandwidth is limited so I can download only x pages per time but Parallel.ForEach executes whole list of desired webpages.</p> <p>Is there a way to limit thread number or any other limiter while running Parallel.ForEach?</p> <p>Demo code:</p> <pre><code>Parallel.ForEach(listOfWebpages, webpage =&gt; { Download(webpage); }); </code></pre> <p>The real task has nothing to do with webpages, so creative web crawling solutions won't help.</p>
9,290,531
4
10
null
2012-02-15 09:08:36.487 UTC
65
2020-02-17 10:40:00.093 UTC
2015-08-29 21:26:50.477 UTC
null
41,956
null
185,824
null
1
358
c#|.net|asynchronous|parallel.foreach
205,099
<p>You can specify a <code>MaxDegreeOfParallelism</code> in a <code>ParallelOptions</code> parameter:</p> <pre><code>Parallel.ForEach( listOfWebpages, new ParallelOptions { MaxDegreeOfParallelism = 4 }, webpage =&gt; { Download(webpage); } ); </code></pre> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/dd783747.aspx" rel="noreferrer">Parallel.ForEach</a></p> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism.aspx" rel="noreferrer">ParallelOptions.MaxDegreeOfParallelism</a></p>
8,506,881
Nice Label Algorithm for Charts with minimum ticks
<p>I need to calculate the Ticklabels and the Tickrange for charts manually. </p> <p>I know the "standard" algorithm for nice ticks (see <a href="http://books.google.de/books?id=fvA7zLEFWZgC&amp;pg=PA61&amp;lpg=PA61&amp;redir_esc=y#v=onepage&amp;q&amp;f=false" rel="noreferrer">http://books.google.de/books?id=fvA7zLEFWZgC&amp;pg=PA61&amp;lpg=PA61&amp;redir_esc=y#v=onepage&amp;q&amp;f=false</a>) and I also know <a href="http://erison.blogspot.nl/2011/07/algorithm-for-optimal-scaling-on-chart.html" rel="noreferrer">this Java implementation</a>. </p> <p>The problem is, that with this algorithm, the ticks are "too smart". That means, The algorithm decides how much ticks should be displayed. My requirement is, that there are always 5 Ticks, but these should of course be "pretty". The naive approach would be to get the maximum value, divide with 5 and multiply with the ticknumber. The values here are - of course - not optimal and the ticks are pretty ugly. </p> <p>Does anyone know a solution for the problem or have a hint for a formal algorithm description?</p>
8,507,299
20
4
null
2011-12-14 15:15:21.773 UTC
44
2022-06-24 00:16:12.49 UTC
2016-10-27 13:52:13.943 UTC
null
2,486,904
null
441,467
null
1
39
java|algorithm|math|charts
21,169
<p>You should be able to use the Java implementation with minor corrections. </p> <p>Change maxticks to 5.</p> <p>Change the calculate mehod to this:</p> <pre><code>private void calculate() { this.range = niceNum(maxPoint - minPoint, false); this.tickSpacing = niceNum(range / (maxTicks - 1), true); this.niceMin = Math.floor(minPoint / tickSpacing) * tickSpacing; this.niceMax = this.niceMin + tickSpacing * (maxticks - 1); // Always display maxticks } </code></pre> <p>Disclaimer: Note that I haven't tested this, so you may have to tweak it to make it look good. My suggested solution adds extra space at the top of the chart to always make room for 5 ticks. This may look ugly in some cases.</p>
8,614,335
Android: How to safely unbind a service
<p>I have a service which is binded to application context like this: </p> <pre><code>getApplicationContext().bindService( new Intent(this, ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE ); protected void onDestroy() { super.onDestroy(); getApplicationContext().unbindService(serviceConnection); } </code></pre> <p>For some reason, only sometimes the application context does not bind properly (I can't fix that part), however in onDestroy() I do <code>unbindservice</code> which throws an error</p> <pre><code>java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection. </code></pre> <p>My question is: Is there a way to call <code>unbindservice</code> safely or check if it is already bound to a service before unbinding it?</p> <p>Thanks in advance.</p>
8,873,328
8
5
null
2011-12-23 09:34:24.04 UTC
22
2020-05-19 03:03:44.72 UTC
2014-04-02 06:45:07.24 UTC
null
1,133,730
null
712,779
null
1
46
android
67,570
<p>Try this:</p> <pre><code>boolean isBound = false; ... isBound = getApplicationContext().bindService( new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE ); ... if (isBound) getApplicationContext().unbindService(serviceConnection); </code></pre> <p><strong>Note:</strong></p> <p>You should use same <code>context</code> for binding a service and unbinding a service. If you are binding Service with <code>getApplicationContext()</code> so you should also use <code>getApplicationContext.unbindService(..)</code></p>
5,133,781
How to format all Java files in an Eclipse project at one time?
<p>I have an old Eclipse project and the code is not well formatted. I'd like to format all the <code>.java</code> files according to the settings in Eclipse. I don't want to edit every individual file with <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd>. Is there a way to format all my files? Perhaps an Eclipse plugin?</p>
5,133,787
5
0
null
2011-02-27 14:37:49.267 UTC
24
2017-12-13 17:26:49.693 UTC
2013-06-26 05:19:15.697 UTC
null
366,904
null
636,529
null
1
174
eclipse|code-formatting
73,915
<p>Right click on the project root and select Source -> Format. This should work for at least version 3.8.1. and above.</p> <p>If the above does not work, you're probably using an older Eclipse-version. In such case you can select your Source Folders by clicking on them while holding down CTRL, then select Source -> Format from the right-click -menu. Works with package-folders and class files also, in case you don't want to format the entire project.</p>
5,351,342
reload parent window from within an iframe
<p>I have my login page in an iframe and wished to reload the parent window using ajax and jquery from within iframe without refreshing but i'm getting errors like this<pre> (this[0].ownerDocument || this[0]).createDocumentFragment is not a function</pre> please help!</p>
5,950,328
6
1
null
2011-03-18 11:31:43.807 UTC
4
2022-05-31 09:50:47.76 UTC
null
null
null
null
657,354
null
1
19
jquery|ajax|iframe
94,747
<p>I could achieve this by reloading the page using javascript</p> <pre><code>parent.location.reload(); </code></pre> <p>then i fired a trigger to open the target iframe</p> <pre><code>$("#log-inout").trigger("click"); </code></pre> <p>I needed such system for a peculiar condition. This might help others in similar conditions.</p>
4,965,159
How to redirect output with subprocess in Python?
<p>What I do in the command line:</p> <pre><code>cat file1 file2 file3 &gt; myfile </code></pre> <p>What I want to do with python:</p> <pre><code>import subprocess, shlex my_cmd = 'cat file1 file2 file3 &gt; myfile' args = shlex.split(my_cmd) subprocess.call(args) # spits the output in the window i call my python program </code></pre>
4,965,176
6
4
null
2011-02-11 02:49:01.25 UTC
24
2022-01-31 13:36:54.207 UTC
2019-02-16 23:41:44.763 UTC
null
608,639
null
612,441
null
1
118
python|subprocess
126,879
<p>UPDATE: os.system is discouraged, albeit still available in Python 3.</p> <hr> <p>Use <code>os.system</code>:</p> <pre><code>os.system(my_cmd) </code></pre> <p>If you really want to use subprocess, here's the solution (mostly lifted from the documentation for subprocess):</p> <pre><code>p = subprocess.Popen(my_cmd, shell=True) os.waitpid(p.pid, 0) </code></pre> <p>OTOH, you can avoid system calls entirely:</p> <pre><code>import shutil with open('myfile', 'w') as outfile: for infile in ('file1', 'file2', 'file3'): shutil.copyfileobj(open(infile), outfile) </code></pre>
5,552,258
Collections.emptyList() vs. new instance
<p>In practice, is it better to return an empty list like <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#emptyList%28%29">this</a>:</p> <pre><code>return Collections.emptyList(); </code></pre> <p>Or like <a href="http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28%29">this</a>:</p> <pre><code>return new ArrayList&lt;Foo&gt;(); </code></pre> <p>Or is this completely dependent upon what you're going to do with the returned list?</p>
5,552,287
7
0
null
2011-04-05 13:02:38.11 UTC
68
2020-07-08 13:32:51.76 UTC
2015-06-04 08:13:07.443 UTC
null
276,052
null
584,862
null
1
274
java|collections|empty-list
219,108
<p>The main difference is that <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#emptyList%28%29" rel="noreferrer"><code>Collections.emptyList()</code></a> returns an <em>immutable</em> list, i.e., a list to which you cannot add elements. (Same applies to the <a href="https://docs.oracle.com/javase/9/docs/api/java/util/List.html#of--" rel="noreferrer"><code>List.of()</code></a> introduced in Java 9.)</p> <p>In the rare cases where you <em>do</em> want to modify the returned list, <code>Collections.emptyList()</code> and <code>List.of()</code> are thus <strong>not</strong> a good choices.</p> <p>I'd say that returning an immutable list is perfectly fine (and even the preferred way) as long as the contract (documentation) does not explicitly state differently.</p> <hr> <p>In addition, <code>emptyList()</code> <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#emptyList--" rel="noreferrer">might not create a new object with each call.</a></p> <blockquote> <p>Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)</p> </blockquote> <p>The implementation of <code>emptyList</code> looks as follows:</p> <pre><code>public static final &lt;T&gt; List&lt;T&gt; emptyList() { return (List&lt;T&gt;) EMPTY_LIST; } </code></pre> <p>So if your method (which returns an empty list) is called very often, this approach may even give you slightly better performance both CPU and memory wise.</p>
5,226,043
Java: What is a good data structure for storing a coordinate map for an infinite game world?
<p>I am used to coding in PHP but I am not really proficient with Java and this has been a problem for some time now. I expect it to be a fairly easy solution, however I cannot find any good example code any way I search it, so here goes:</p> <p>I am programming a game that takes place in a 2d random generated infinite world on a tile based map (nitpicking: I know it will not be truly infinite. I just expect the world to be quite large). The usual approach of map[x][y] multidimensional array started out as a basic idea, but since Java does not provide a way for non-integer (i.e. negative) array key shenanigans like PHP does, I cannot properly have a (-x,+x,-y,+y) coordinate system with array keys.</p> <p>I need to be able to find the objects on a tile at a specific x,y coordinate as well as finding "adjacent tiles" of a certain tile. (Trivial if I can getObjectAt(x,y), I can get(x+1,y) and so on)</p> <p>I have read about quad trees and R-trees and the like. The concept is exciting, however I haven't seen any good, simple example implementation in Java. And besides I am not really sure if that is what I need exactly.</p> <p>Any advice is welcome</p> <p>Thank you</p>
10,935,324
11
4
null
2011-03-07 22:30:10.523 UTC
15
2016-01-01 11:37:47.447 UTC
null
null
null
null
648,930
null
1
46
java|map|tile|coordinate
20,874
<p>I came to this thread with the same problem, but my solution was to use <a href="http://www.javamex.com/tutorials/collections/using_4.shtml" rel="nofollow noreferrer">Map/HashMaps</a>, but these are one dimensional. </p> <p>To overcome this, instead of using a map within a map (which would be messy and very inefficient) I used a generic <a href="https://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b?pli=1" rel="nofollow noreferrer">Pair</a> class (not something that you'll find in the stock java library) although you could replace this with a Position class (virtually the same code, but not generic, instead integers or floats). </p> <p>So when defining the map: <code>Map&lt;Pair, Tile&gt; tiles = new HashMap&lt;Pair, Tile&gt;;</code> </p> <p>For placing tile objects onto the map I used <code>tiles.put(new Pair(x, y), new GrassTile());</code> and for retrieving the object <code>tiles.get(new Pair(x, y));</code>. </p> <p>[x/y would be any coordinate you wish to place (<strong>this allows negative coordinates</strong> without any mess!), "new GrassTile()" is just an example of placing a tile of a certain type during map creation. Obviously - as previously stated - the Pair class is replacable.]</p> <p>Why not ArrayLists you may ask? Because array lists are much more linear than mapping, and in my opinion are more difficult to add and retrieve tiles, especially on 2 Dimensions.</p> <p><strong>Update:</strong></p> <p>For anyone wondering why there isn't a Pair() class in Java, here's an <a href="https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java">explanation</a>.</p>
5,492,023
Transfer files to/from session I'm logged in with PuTTY
<p>I'm logged into a remote host using PuTTY. </p> <p>What is the command to transfer files from my local machine to the machine I'm logged into on PuTTY?</p>
5,492,065
13
0
null
2011-03-30 20:32:50.743 UTC
27
2022-03-15 16:51:22.94 UTC
2015-03-03 15:08:33.603 UTC
null
850,848
null
470,184
null
1
110
sftp|file-transfer|putty|scp
343,024
<p>This is probably not a direct answer to what you're asking, but when I need to transfer files over a SSH session I use <a href="http://winscp.net/eng/index.php" rel="noreferrer">WinSCP</a>, which is an excellent file transfer program over SCP or SFTP. Of course this assumes you're on Windows.</p>
5,391,564
How to use DISTINCT and ORDER BY in same SELECT statement?
<p>After executing the following statement:</p> <pre><code>SELECT Category FROM MonitoringJob ORDER BY CreationDate DESC </code></pre> <p>I am getting the following values from the database:</p> <pre><code>test3 test3 bildung test4 test3 test2 test1 </code></pre> <p>but I want the duplicates removed, like this:</p> <pre><code>bildung test4 test3 test2 test1 </code></pre> <p>I tried to use DISTINCT but it doesn't work with ORDER BY in one statement. Please help.</p> <p>Important:</p> <ol> <li><p>I tried it with:</p> <pre><code>SELECT DISTINCT Category FROM MonitoringJob ORDER BY CreationDate DESC </code></pre> <p>it doesn't work.</p></li> <li><p>Order by CreationDate is very important.</p></li> </ol>
5,391,642
13
2
null
2011-03-22 12:55:01.8 UTC
42
2022-08-02 13:18:26.067 UTC
2015-07-18 00:39:48.497 UTC
null
1,402,846
null
291,120
null
1
144
sql|sql-order-by|distinct
413,046
<p>The problem is that the columns used in the <code>ORDER BY</code> aren't specified in the <code>DISTINCT</code>. To do this, you need to use an <a href="https://msdn.microsoft.com/nl-nl/library/ms173454(v=sql.110).aspx" rel="noreferrer">aggregate function</a> to sort on, and use a <code>GROUP BY</code> to make the <code>DISTINCT</code> work.</p> <p>Try something like this:</p> <pre><code>SELECT DISTINCT Category, MAX(CreationDate) FROM MonitoringJob GROUP BY Category ORDER BY MAX(CreationDate) DESC, Category </code></pre>
16,952,718
Spring's SecurityContextHolder.getContext().getAuthentication() returns null after RedirectView is used in HTTPS/SSL
<p>I have a typical Spring MVC running on Tomcat. After switching the system to run on HTTPS (everything is working OK under plain HTTP), the login stopped working. The reason is that Spring's <code>SecurityContextHolder.getContext().getAuthentication()</code> object becomes <code>null</code> after <code>RedirectView</code> is used. </p> <p>I already searched for the answer, the only one I found suggested to set property <code>redirectHttp10Compatible</code> to <code>false</code> in the <code>viewResolver</code> bean setup. This did not help. </p> <p>I also checked that throughout redirect, my session id remains the same and the connection remains secure, i.e. it is not an issue (at least as far as I could tell) of a change between http and https or vice versa. </p> <p>What could be the problem?</p> <pre><code>&lt;beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"&gt; &lt;http auto-config="true"&gt; &lt;intercept-url pattern="/**" requires-channel="https" /&gt; &lt;intercept-url pattern="/index*" access="ROLE_USER"/&gt; &lt;intercept-url pattern="/dashboard*" access="ROLE_USER" requires-channel="https"/&gt; &lt;intercept-url pattern="/login*" access="ROLE_GUEST, ROLE_ANONYMOUS, ROLE_USER"/&gt; &lt;intercept-url pattern="/signin*" access="ROLE_GUEST, ROLE_ANONYMOUS, ROLE_USER"/&gt; &lt;intercept-url pattern="/signup*" access="ROLE_GUEST, ROLE_ANONYMOUS, ROLE_USER"/&gt; &lt;form-login login-page="/home" default-target-url="/home" authentication-failure-url="/home?authentication_error=true" authentication-success-handler-ref="redefineTargetURL" /&gt; &lt;anonymous username="guest" granted-authority="ROLE_GUEST" key="anonymousKey"/&gt; &lt;logout invalidate-session="true" logout-success-url="/logout?message=Logout Successful" /&gt; &lt;/http&gt; &lt;authentication-manager alias="authenticationManager"&gt; &lt;authentication-provider user-service-ref="userDetailsService" /&gt; &lt;/authentication-manager&gt; &lt;beans:bean id="redefineTargetURL" class="com.groupskeed.common.RedefineTargetURL" /&gt; &lt;beans:bean id="userDetailsService" class="com.groupskeed.security.UserDetailsServiceImpl" /&gt; </code></pre> <p></p>
17,040,501
1
6
null
2013-06-06 02:19:51.267 UTC
4
2020-10-01 17:35:18.55 UTC
2015-08-14 23:48:39.467 UTC
null
192,465
null
2,278,625
null
1
12
java|spring|tomcat|https|spring-security
40,801
<p>The <code>SecurityContextHolder.getContext().getAuthentication()</code> becoming null after redirect is correct since it is threadbound. But it should be repopulated from the session. Therefore try to keep track of the <code>SPRING_SECURITY_CONTEXT</code> Attribute in the Session. Here is some example code to get an idea:</p> <pre><code>HttpSession session = request.getSession(true); System.out.println(session.getAttribute(&quot;SPRING_SECURITY_CONTEXT&quot;)); </code></pre> <p>In the Spring Security documentation there is a Part about how HTTPS/HTTP switching can screw up the session perhaps there is a hint to your problem somewhere in there. <a href="http://static.springsource.org/spring-security/site/faq.html#d0e223" rel="nofollow noreferrer">http://static.springsource.org/spring-security/site/faq.html#d0e223</a></p> <p>The above FAQ leads to an examination of how the session is handled in your application. I probably would start looking at the AuthenticationSuccessHandler implementation. (You can post it into your question if you like.)</p> <p>For more detail on how the security context is handled in web applications see the following: (<a href="https://docs.spring.io/spring-security/site/docs/3.0.x/reference/technical-overview.html" rel="nofollow noreferrer">section 5.4 Authentication in a Web Application</a>): <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/reference/technical-overview.html" rel="nofollow noreferrer">http://static.springsource.org/spring-security/site/docs/3.0.x/reference/technical-overview.html</a></p>
12,583,349
Command to open "Configure advanced user profile properties" (Windows 7)
<p>I'm trying to figure out how to open the "Configure advanced user profile properties" control panel window by command line, so that I can provide a link to it in my application.</p> <p>It can be opened without going through the control panel by typing "userprofile" in Start->Search box. So I assume that it must have a valid command to open it directly, but I can't seem to figure out what the command is.</p> <p>I've found that "control nusrmgr.cpl" opens the control panel for "User Accounts" which has the link to "Configure advanced user profile properties", but I want to provide a direct link.</p> <p>Anyone have any insight to how this can be done?</p>
12,587,748
2
0
null
2012-09-25 12:51:56.503 UTC
5
2021-10-08 23:02:52.897 UTC
null
null
null
null
934,676
null
1
7
windows|cmd
57,902
<p>The actual command line for <code>Configure advanced user profile properties</code> is:<br> <code>rundll32.exe sysdm.cpl,EditUserProfiles</code>. You can just copy &amp; paste this into cmd window to run.</p> <p><strong>Further reading:</strong> <a href="https://archive.is/EMb0j#selection-1805.20-1805.59" rel="noreferrer">Entry for <code>run</code> at ss64.com</a></p>
12,613,402
android statistic 3g traffic for each APP, how?
<p>For statistic network traffic per APP, what I'm using now is <a href="http://developer.android.com/reference/android/net/TrafficStats.html">Android TrafficStats</a></p> <p>That I can get result like following :</p> <ul> <li>Youtube 50.30 MBytes</li> <li>Facebook 21.39 MBytes</li> <li>Google Play 103.38 MBytes</li> <li>(and more...)</li> </ul> <p>As I know, the "Android Trafficstats" just a native pointer to a c file. (maybe an .so ?)</p> <p>But it mixed Wifi &amp; 3g traffic, is there any way to only get non-WiFi traffic statistic ?</p>
12,837,108
4
1
null
2012-09-27 02:53:07.143 UTC
10
2015-04-28 13:48:43.467 UTC
2012-09-27 04:18:06.553 UTC
null
1,589,880
null
316,441
null
1
15
android|3g|traffic|network-traffic|traffic-measurement
10,890
<p>Evening all, I got some way to do that...</p> <p>First I have to create a class which extends BroadcasrReceiver, like this:</p> <p>Manifest definition:</p> <pre><code>&lt;receiver android:name=".core.CoreReceiver" android:enabled="true" android:exported="false"&gt; &lt;intent-filter&gt; &lt;action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" /&gt; &lt;action android:name="android.net.wifi.STATE_CHANGE" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>Codes:</p> <pre><code>/** * @author me */ public class CoreReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (Constants.phone == null) { // Receive [network] event Constants.phone=new PhoneListen(context); TelephonyManager telephony=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(Constants.phone, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); } WifiManager wifi=(WifiManager)context.getSystemService(Context.WIFI_SERVICE); boolean b=wifi.isWifiEnabled(); if (Constants.STATUS_WIFI != b) { // WiFi status changed... } } } </code></pre> <p>And a phone stats listener below...</p> <pre><code>public class PhoneListen extends PhoneStateListener { private Context context; public PhoneListen(Context c) { context=c; } @Override public void onDataConnectionStateChanged(int state) { switch(state) { case TelephonyManager.DATA_DISCONNECTED:// 3G //3G has been turned OFF break; case TelephonyManager.DATA_CONNECTING:// 3G //3G is connecting break; case TelephonyManager.DATA_CONNECTED:// 3G //3G has turned ON break; } } } </code></pre> <p>Finally, here's my logic</p> <ol> <li>Collect count into SQLite DB.</li> <li>Collect all app network usage via TrafficStats every 1 minute, only when 3G is ON.</li> <li>If 3G is OFF, then stop collecting.</li> <li>If both 3G &amp; WiFi are ON, stop collecting.</li> </ol> <p>As I know, network traffic will go through WiFi only, if both 3G &amp; WiFi are available.</p>
12,428,670
Calculate size in megabytes from SQL varbinary field
<p>We have a db table that stores files as varbinary(MAX). When we run the following script:</p> <pre><code>SELECT SUM(LEN(Content)) FROM dbo.File </code></pre> <p>The result is: </p> <blockquote> <p>35398663</p> </blockquote> <p>I want to convert this number into megabytes? Is this possible?</p>
12,428,729
1
0
null
2012-09-14 16:40:51.95 UTC
7
2022-05-20 15:14:30.513 UTC
2012-09-17 21:14:06.02 UTC
null
947,386
null
947,386
null
1
32
sql-server-2008
54,822
<p>Use <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql" rel="nofollow noreferrer"><code>DATALENGTH</code></a> to retrieve the number of bytes and then convert, like this:</p> <p><a href="http://sqlfiddle.com/#!18/6df92/291" rel="nofollow noreferrer">SQL Fiddle</a></p> <p><strong>MS SQL Server 2017 Schema Setup</strong>:</p> <pre><code>CREATE TABLE supportContacts ( id int identity primary key, type varchar(20), details varchar(30) ); INSERT INTO supportContacts (type, details) VALUES ('Email', '[email protected]'), ('Twitter', '@sqlfiddle'); </code></pre> <p><strong>Query 1</strong>:</p> <pre><code>select *, gigabytes / 1024.0 as terabytes from ( select *, megabytes / 1024.0 as gigabytes from ( select *, kilobytes / 1024.0 as megabytes from ( select *, bytes / 1024.0 as kilobytes from ( select sum(datalength(details)) as bytes from supportContacts ) a ) b ) c ) d </code></pre> <p><strong><a href="http://sqlfiddle.com/#!18/6df92/291/0" rel="nofollow noreferrer">Results</a></strong>:</p> <pre><code>| bytes | kilobytes | megabytes | gigabytes | terabytes | |-------|-----------|---------------|----------------|-------------------| | 29 | 0.02832 | 0.00002765625 | 2.700805664e-8 | 2.63750553125e-11 | </code></pre>
12,482,637
BigQuery converting to a different timezone
<p>I am storing data in unixtimestamp on google big query. However, when the user will ask for a report, she will need the filtering and grouping of data by her local timezone.</p> <p>The data is stored in GMT. The user may wish to see the data in EST. The report may ask the data to be grouped by date. </p> <p>I don't see the timezone conversion function <a href="https://developers.google.com/bigquery/docs/query-reference#timestampfunctions">here</a>: </p> <p>Does anyone know how I can do this in bigquery? i.e. how do i group by after converting the timestamp to a different timezone?</p>
12,482,905
7
0
null
2012-09-18 18:12:55.537 UTC
11
2021-10-05 23:13:34.55 UTC
2012-09-26 09:59:40.673 UTC
null
744,859
null
1,681,125
null
1
34
datetime|timezone|google-bigquery
120,766
<p><strong>2016 update</strong>: <em>Look answers below, BigQuery now provides timestamp and timezone methods</em>.</p> <hr> <p>You are right - BigQuery doesn't provide any timestamp conversion methods.</p> <p>In this case, I suggest that you run your GROUP BY based on dimensions of the GMT/UTC timestamp field, and then convert and display the result in the local timezone in your code.</p>
12,065,885
Filter dataframe rows if value in column is in a set list of values
<p>I have a Python pandas DataFrame <code>rpt</code>:</p> <pre><code>rpt &lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null values sales 47518 non-null values </code></pre> <p>I can filter the rows whose stock id is <code>'600809'</code> like this: <code>rpt[rpt['STK_ID'] == '600809']</code></p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: 25 entries, ('600809', '20120331') to ('600809', '20060331') Data columns: STK_ID 25 non-null values STK_Name 25 non-null values RPT_Date 25 non-null values sales 25 non-null values </code></pre> <p>and I want to get all the rows of some stocks together, such as <code>['600809','600141','600329']</code>. That means I want a syntax like this: </p> <pre><code>stk_list = ['600809','600141','600329'] rst = rpt[rpt['STK_ID'] in stk_list] # this does not works in pandas </code></pre> <p>Since pandas not accept above command, how to achieve the target? </p>
12,065,904
7
1
null
2012-08-22 03:16:56.393 UTC
174
2020-12-26 10:54:14.937 UTC
2017-04-27 13:28:09.233 UTC
null
3,730,397
null
1,072,888
null
1
555
python|pandas|dataframe
479,702
<p>Use the <code>isin</code> method: </p> <p><code>rpt[rpt['STK_ID'].isin(stk_list)]</code></p>
24,372,942
SSL Error: unable to get local issuer certificate
<p>I'm having trouble configuring SSL on a Debian 6.0 32bit server. I'm relatively new with SSL so please bear with me. I'm including as much information as I can.<br> <em>Note: The true domain name has been changed to protect the identity and integrity of the server.</em></p> <h3>Configuration</h3> <p>The server is running using nginx. It is configured as follows:</p> <pre><code>ssl_certificate /usr/local/nginx/priv/mysite.ca.chained.crt; ssl_certificate_key /usr/local/nginx/priv/mysite.ca.key; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ssl_verify_depth 2; </code></pre> <p>I chained my certificate using the method described <a href="http://nginx.org/en/docs/http/configuring_https_servers.html" rel="noreferrer">here</a></p> <pre><code>cat mysite.ca.crt bundle.crt &gt; mysite.ca.chained.crt </code></pre> <p>where <code>mysite.ca.crt</code> is the certificate given to me by the signing authority, and the <code>bundle.crt</code> is the CA certificate also sent to me by my signing authority. The problem is that I did not purchase the SSL certificate directly from GlobalSign, but instead through my hosting provider, Singlehop.</p> <h3>Testing</h3> <p>The certificate validates properly on Safari and Chrome, but not on Firefox. Initial searching revealed that it may be a problem with the CA. </p> <p>I explored the answer to a <a href="https://stackoverflow.com/questions/7587851/openssl-unable-to-verify-the-first-certificate-for-experian-url">similar question</a>, but was unable to find a solution, as I don't really understand what purpose each certificate serves.</p> <p>I used openssl's s_client to test the connection, and received output which seems to indicate the same problem as <a href="https://stackoverflow.com/questions/7587851/openssl-unable-to-verify-the-first-certificate-for-experian-url">the similar question</a>. The error is as follows:</p> <pre><code>depth=0 /OU=Domain Control Validated/CN=*.mysite.ca verify error:num=20:unable to get local issuer certificate verify return:1 depth=0 /OU=Domain Control Validated/CN=*.mysite.ca verify error:num=27:certificate not trusted verify return:1 </code></pre> <p>A full detail of openssl's response (with certificates and unnecessary information truncated) can be found <a href="https://gist.github.com/jamiecounsell/a3988d56965d81d1a4b0" rel="noreferrer">here</a>.</p> <p>I also see the warning:</p> <pre><code>No client certificate CA names sent </code></pre> <p>Is it possible that this is the problem? How can I ensure that nginx sends these CA names?</p> <h3>Attempts to Solve the Problem</h3> <p>I attempted to solve the problem by downloading the root CA directly from GlobalSign, but received the same error. I updated the root CA's on my Debian server using the <code>update-ca-certificates</code> command, but nothing changed. This is likely because the CA sent from my provider was correct, so it led to the certificate being chained twice, which doesn't help.</p> <pre><code>0 s:/OU=Domain Control Validated/CN=*.mysite.ca i:/C=BE/O=GlobalSign nv-sa/CN=AlphaSSL CA - SHA256 - G2 1 s:/O=AlphaSSL/CN=AlphaSSL CA - G2 i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA 2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA </code></pre> <h3>Next Steps</h3> <p>Please let me know if there is anything I can try, or if I just have the whole thing configured incorrectly.</p>
24,454,893
1
6
null
2014-06-23 18:34:09.117 UTC
23
2022-06-02 06:02:29.53 UTC
2017-05-23 11:54:50.79 UTC
null
-1
null
3,768,332
null
1
114
security|ssl|https|openssl|ssl-certificate
451,978
<p>jww is right — you're referencing the wrong intermediate certificate.</p> <p>As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: <a href="http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt">http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt</a></p>
3,498,052
Entity Framework - Is there a way to reorder properties in the EDMX designer?
<p>I'm using Entity Framework's model designer to design the model for a new project.</p> <p>Adding properties is relatively easy, however they're always appended to the entity.</p> <p>Is there a way to reorder the properties once they've been added? This is quite annoying!</p>
11,634,685
3
0
null
2010-08-16 22:53:41.173 UTC
4
2015-01-23 15:47:51.207 UTC
null
null
null
null
24,874
null
1
31
.net|visual-studio|entity-framework|entity-framework-4
5,154
<p>In VS2012 it's much easier: just press <kbd>alt</kbd> + <kbd>up</kbd>/<kbd>down</kbd> with the property selected.</p>
3,859,157
Splitting C++ Strings Onto Multiple Lines (Code Syntax, Not Parsing)
<p>Not to be confused with how to split a string parsing wise, e.g.:<br> <a href="https://stackoverflow.com/questions/236129/how-to-split-a-string">Split a string in C++?</a></p> <p>I am a bit confused as to how to split a string onto multiple lines in c++.</p> <p>This sounds like a simple question, but take the following example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; main() { //Gives error std::string my_val ="Hello world, this is an overly long string to have" + " on just one line"; std::cout &lt;&lt; "My Val is : " &lt;&lt; my_val &lt;&lt; std::endl; //Gives error std::string my_val ="Hello world, this is an overly long string to have" &amp; " on just one line"; std::cout &lt;&lt; "My Val is : " &lt;&lt; my_val &lt;&lt; std::endl; } </code></pre> <p>I realize that I could use the <code>std::string</code> <code>append()</code> method, but I was wondering if there was any shorter/more elegant (e.g. more pythonlike, though obviously triple quotes etc. aren't supported in c++) way to break strings in c++ onto multiple lines for sake of readability.</p> <p>One place where this would be particularly desirable is when you're passing long string literals to a function (for example a sentence).</p>
3,859,167
3
3
null
2010-10-04 21:13:19.477 UTC
10
2010-10-04 22:38:49.703 UTC
2017-05-23 12:17:42.97 UTC
null
-1
null
375,828
null
1
85
c++|string|syntax|coding-style|readability
94,480
<p>Don't put anything between the strings. Part of the C++ lexing stage is to combine adjacent string literals (even over newlines and comments) into a single literal.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; main() { std::string my_val ="Hello world, this is an overly long string to have" " on just one line"; std::cout &lt;&lt; "My Val is : " &lt;&lt; my_val &lt;&lt; std::endl; } </code></pre> <p>Note that if you want a newline in the literal, you will have to add that yourself:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; main() { std::string my_val ="This string gets displayed over\n" "two lines when sent to cout."; std::cout &lt;&lt; "My Val is : " &lt;&lt; my_val &lt;&lt; std::endl; } </code></pre> <p>If you are wanting to mix a <code>#define</code>d integer constant into the literal, you'll have to use some macros:</p> <pre><code>#include &lt;iostream&gt; using namespace std; #define TWO 2 #define XSTRINGIFY(s) #s #define STRINGIFY(s) XSTRINGIFY(s) int main(int argc, char* argv[]) { std::cout &lt;&lt; "abc" // Outputs "abc2DEF" STRINGIFY(TWO) "DEF" &lt;&lt; endl; std::cout &lt;&lt; "abc" // Outputs "abcTWODEF" XSTRINGIFY(TWO) "DEF" &lt;&lt; endl; } </code></pre> <p>There's some weirdness in there due to the way the stringify processor operator works, so you need two levels of macro to get the actual value of <code>TWO</code> to be made into a string literal.</p>
8,378,797
"std::bad_alloc": am I using too much memory?
<p>The message: </p> <pre><code>terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc </code></pre> <p>I looked at the gdb backtrace and this is the lowest level method in there that I implemented myself:</p> <pre><code>/* * get an array of vec3s, which will be used for rendering the image */ vec3 *MarchingCubes::getVertexNormalArray(){ // Used the same array size technique as getVertexArray: we want indices to match up vec3 *array = new vec3[this-&gt;meshPoints.getNumFaces() * 3]; //3 vertices per face int j=0; for (unsigned int i=0; i &lt; (this-&gt;meshPoints.getNumFaces() * 3); i++) { realVec normal = this-&gt;meshPoints.getNormalForVertex(i); // PCReal* iter = normal.begin(); if (normal.size() &gt;= 3) { array[j++] = vec3(normal[0], normal[1], normal[2]); } cout &lt;&lt; i &lt;&lt; " "; } return array; } </code></pre> <p>The cout statement you see above indicates that it terminates after 7000+ iterations. The above function is called only once near the end of my application. I call a very similar function before calling the above, that doesn't cause problems.</p>
8,397,204
2
21
null
2011-12-04 21:40:24.647 UTC
5
2018-03-02 13:47:50.047 UTC
2011-12-04 22:26:38.177 UTC
null
1,042,847
null
1,042,847
null
1
25
c++|bad-alloc
115,670
<p>My problem turned out to be that <code>this-&gt;meshPoints.getNormalForVertex(i)</code> accesses an array (or vector, I can't remember) whose length is less than <code>this-&gt;meshPoints.getNumFaces() * 3</code>. So it was accessing out of bounds.</p>
12,959,237
get point coordinates based on direction and distance (vector)
<p><img src="https://i.stack.imgur.com/TYRMc.png" alt="get point based on direction and distance"></p> <p>I need to find the coordinates of the second point. I know the <em>angle</em> between the points in radians and I also know the <em>length</em> of the vector.</p> <p>I would really appreciate if someone could point me towards the solution.</p>
12,959,361
1
2
null
2012-10-18 16:23:15.473 UTC
7
2015-09-25 09:08:20.12 UTC
2015-09-25 09:08:20.12 UTC
null
1,151,658
null
1,151,658
null
1
28
javascript|math|canvas|vector|polar-coordinates
22,729
<p>Given <strong><em>L</em></strong> as the length of the vector and <strong><em>Ang</em></strong> the angle</p> <pre><code>x2 = x1 + Math.cos(Ang) * L y2 = y1 + Math.sin(Ang) * L </code></pre> <p>Oops... I just noted the top to bottom orientation of the Y axis... Konstantin Levin, you will need adapt slightly because the formulas above assume a typical trigonometric coordinates system. In your case the formulas should be:</p> <pre><code>x2 = x1 + Math.cos(Ang) * L // unchanged y2 = y1 - Math.sin(Ang) * L // minus on the Sin </code></pre> <p>Also (what goes without saying, also goes in one says it...) the reference angle should be such that when y2 == y1 and x2 > x1, Ang should be zero, and it should increase as the second point is moved counter-clockwise around the first one.</p>
12,705,586
Why should i use Drools?
<p>I am no Drools expert. I have some familiarity with it though, by experimenting with it. I am unable to appreciate, why would i need it.</p> <p>My Typical Applications are Business Web Applications. Yes they do have some amount of Rules. But those are implemented using Database Tables, SQL Queries, and a nice UI in for the Business-Users to modify the Rules. Rules are not arbitrary, they are carefully thought-thru before being put in Production.</p> <p>My Business Users would never ever use a (Drools)Scripting Language to modify Anything. Let Alone Modify Rules. They are perfectly happy using UI Screens to modify Rules. Plus they can make a zillion syntax mistakes in a Drools files, if i let them anywhere near it.</p> <p>Again <br> - Why should i use Drools in this scenario?<br> - There are Drools fanatics i have met who insist i should change all my code to make use of Drools.</p> <p>So, is Drools useful? I am not sure.</p>
12,705,670
3
1
null
2012-10-03 09:30:21.07 UTC
9
2019-02-13 22:56:04.22 UTC
null
null
null
null
974,169
null
1
38
java|scripting|drools|rules|rule-engine
27,133
<p>Fanatics of all stripes should be questioned, no matter what topic they rave about.</p> <p>Data-driven decision tables are a perfectly good way to implement complex behavior. On the day it doesn't scale or perform to your requirements, perhaps you'll want to consider something else.</p> <p>I wouldn't want to make a technology swap in working production code unless I had a compelling reason. It would take a lot more than fan boy lobbying.</p> <p>If you're really interested, do a PoC and get some real data. If not, learn how to politely smile and ignore them.</p> <p>I've answered about this before: </p> <p><a href="https://stackoverflow.com/questions/250403/rules-engine-pros-and-cons/398389#398389">Rules Engine - pros and cons</a></p> <p>UPDATE: If it's your boss, and you can't dismiss, then make it interface based and try a Drools implementation in a PoC. If you're using Spring, inject one and then the other, measuring performance under a meaningful production rated load. Get some real data - maybe you'll both learn something.</p>
13,159,337
Why doesn't Dijkstra's algorithm work for negative weight edges?
<p>Can somebody tell me why Dijkstra's algorithm for single source shortest path assumes that the edges must be non-negative. </p> <p>I am talking about only edges not the negative weight cycles.</p>
13,159,425
10
2
null
2012-10-31 13:41:00.337 UTC
62
2022-05-09 06:11:45.757 UTC
2022-05-09 06:11:45.757 UTC
null
4,706,171
null
1,306,402
null
1
184
algorithm|graph-theory|shortest-path|dijkstra|greedy
226,834
<p>Recall that in Dijkstra's algorithm, <strong>once a vertex is marked as "closed" (and out of the open set) - the algorithm found the shortest path to it</strong>, and will never have to develop this node again - it assumes the path developed to this path is the shortest.</p> <p>But with negative weights - it might not be true. For example:</p> <pre><code> A / \ / \ / \ 5 2 / \ B--(-10)--&gt;C V={A,B,C} ; E = {(A,C,2), (A,B,5), (B,C,-10)} </code></pre> <p>Dijkstra from A will first develop C, and will later fail to find <code>A-&gt;B-&gt;C</code></p> <hr> <p><strong>EDIT</strong> a bit deeper explanation:</p> <p>Note that this is important, because in each relaxation step, the algorithm assumes the "cost" to the "closed" nodes is indeed minimal, and thus the node that will next be selected is also minimal.</p> <p>The idea of it is: If we have a vertex in open such that its cost is minimal - by adding any <em>positive number</em> to any vertex - the minimality will never change. <br>Without the constraint on positive numbers - the above assumption is not true.</p> <p>Since we do "know" each vertex which was "closed" is minimal - we can safely do the relaxation step - without "looking back". If we do need to "look back" - <a href="http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm">Bellman-Ford</a> offers a recursive-like (DP) solution of doing so.</p>
37,301,273
Attributes of Python module `this`
<p>Typing <code>import this</code> returns Tim Peters' Zen of Python. But I noticed that there are 4 properties on the module:</p> <pre><code>this.i this.c this.d this.s </code></pre> <p>I can see that the statement</p> <pre><code>print(''.join(this.d.get(el, el) for el in this.s)) </code></pre> <p>uses <code>this.d</code> to decode <code>this.s</code> to print the Zen.</p> <p>But can someone tell me what the attributes <code>this.i</code> and <code>this.c</code> are for? </p> <p>I assume they are there intentionally - answers to <a href="https://stackoverflow.com/q/5855758/115237">this question</a> seem to suggest there are other jokes to be gleaned from the wording of the Zen. I'm wondering if there is a reference I'm missing with these 2 values.</p> <p>I noticed that the values differ between Python versions: </p> <pre><code># In v3.5: this.c Out[2]: 97 this.i Out[3]: 25 # In v2.6 this.c Out[8]: '!' this.i Out[9]: 25 </code></pre>
37,301,341
1
5
null
2016-05-18 13:35:19.327 UTC
8
2016-05-19 10:55:06.577 UTC
2017-05-23 11:46:38.373 UTC
null
-1
null
115,237
null
1
33
python
8,655
<p><code>i</code> and <code>c</code> are simply <em>loop variables</em>, used to build the <code>d</code> dictionary. From <a href="https://hg.python.org/cpython/file/3.5/Lib/this.py" rel="noreferrer">the module source code</a>:</p> <pre><code>d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) </code></pre> <p>This builds a <a href="https://en.wikipedia.org/wiki/ROT13" rel="noreferrer">ROT-13 mapping</a>; each ASCII letter (codepoints 65 through 90 for uppercase, 97 through 122 for lowercase) is mapped to another ASCII letter 13 spots along the alphabet (looping back to A and onwards). So <code>A</code> (ASCII point 65) is mapped to <code>N</code> and vice versa (as well as <code>a</code> mapped to <code>n</code>):</p> <pre><code>&gt;&gt;&gt; c, i = 65, 0 &gt;&gt;&gt; chr(i + c) 'A' &gt;&gt;&gt; chr((i + 13) % 26 + c) 'N' </code></pre> <p>Note that if you wanted to ROT-13 text yourself, there is a simpler method; just encode or decode with the <code>rot13</code> codec:</p> <pre><code>&gt;&gt;&gt; this.s "Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.\nErnqnovyvgl pbhagf.\nFcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\nNygubhtu cenpgvpnyvgl orngf chevgl.\nReebef fubhyq arire cnff fvyragyl.\nHayrff rkcyvpvgyl fvyraprq.\nVa gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\nGurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\nNygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\nAbj vf orggre guna arire.\nNygubhtu arire vf bsgra orggre guna *evtug* abj.\nVs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\nVs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\nAnzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!" &gt;&gt;&gt; import codecs &gt;&gt;&gt; codecs.decode(this.s, 'rot13') "The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!" </code></pre> <p>As for the difference in Python 2.6 (or Python 2.7 for that matter) versus Python 3.5; the same variable name <code>c</code> is also used in the list comprehension in the <code>str.join()</code> call:</p> <pre><code>print "".join([d.get(c, c) for c in s]) </code></pre> <p>In Python 2, list comprehensions do not get their own scope (unlike generator expressions and dict and set comprehensions). In Python 3 they do, and the <code>c</code> value in the list comprehension is no longer part of the module namespace. So the last value assigned to <code>c</code> <em>at the module scope</em> is <code>97</code> in Python 3, and <code>this.s[-1]</code> (so a <code>'!'</code>) in Python 2. See <a href="https://stackoverflow.com/questions/19848082/why-do-list-comprehensions-write-to-the-loop-variable-but-generators-dont">Why do list comprehensions write to the loop variable, but generators don&#39;t?</a></p> <p>There is no joke embedded in these 1-letter variable names. There <em>are</em> jokes in the Zen itself. Like the fact that between the source code for the <code>this</code> module and the text itself you can find violations for just about all the rules!</p>
22,129,717
MODE_MULTI_PROCESS for SharedPreferences isn't working
<p>I have a <code>SyncAdapter</code> running on its own process separately from the main app process.</p> <p>I'm using a static wrapper class around my <code>SharedPreferences</code> that creates a static object on process load (Application's <code>onCreate</code>) like so:</p> <pre><code>myPrefs = context.getSharedPreferences(MY_FILE_NAME, Context.MODE_MULTI_PROCESS | Context.MODE_PRIVATE); </code></pre> <p>The wrapper has get and set methods, like so:</p> <pre><code>public static String getSomeString() { return myPrefs.getString(SOME_KEY, null); } public static void setSomeString(String str) { myPrefs.edit().putString(SOME_KEY, str).commit(); } </code></pre> <p>Both <code>SyncAdapter</code> and app uses this wrapper class to edit and get from the prefs, this works sometimes but a lot of times I see the <code>SyncAdapter</code> getting old/missing prefs on accesses to the prefs, while the main app sees the recent changes properly.</p> <p>According to the docs I think the <code>MODE_MULTI_PROCESS</code> flag should work as I expect it to, allowing both processes to see latest changes, but it doesn't work.</p> <p><strong>Update:</strong></p> <p>Per <code>x90</code>'s suggestion, I've tried refraining from using a static <code>SharedPreferences</code> object and instead calling <code>getSharedPreferences</code> on each get/set method. This caused a new issue, where the prefs file gets deleted (!!!) on multi-process simultaneous access. i.e. I see in the logcat:</p> <pre><code>(process 1): getName =&gt; "Name" (process 2): getName =&gt; null (process 1): getName =&gt; null </code></pre> <p>and from that point all the prefs saved on the <code>SharedPreferences</code> object were deleted.</p> <p>This is probably a result of another warning I see in the log:</p> <pre><code>W/FileUtils(21552): Failed to chmod(/data/data/com.my_company/shared_prefs/prefs_filename.xml): libcore.io.ErrnoException: chmod failed: ENOENT (No such file or directory) </code></pre> <p>P.S this is not a deterministic issue, I saw the above logs after a crash happened, but couldn't recreate yet on the same device, and until now it didn't seem to happen on other devices.</p> <p><strong>ANOTHER UPDATE:</strong></p> <p>I've filed a bug report on this, after writing a small testing method to confirm this is indeed an Android issue, star it at <a href="https://code.google.com/p/android/issues/detail?id=66625" rel="noreferrer">https://code.google.com/p/android/issues/detail?id=66625</a></p>
30,035,705
7
12
null
2014-03-02 15:46:16.653 UTC
14
2022-07-22 21:30:21.4 UTC
2016-10-18 16:38:43.223 UTC
null
2,219,237
null
819,355
null
1
30
android|multiprocessing|sharedpreferences
15,062
<p>Had exactly the same problem and my solution was to write a ContentProvider based replacement for the SharedPreferences. It works 100% multiprocess.</p> <p>I made it a library for all of us. Here is the result: <a href="https://github.com/grandcentrix/tray">https://github.com/grandcentrix/tray</a></p>
16,748,993
iOS SecKeyRef to NSData
<p>I have two keys, public and private, that are both stored in SecKeyRef-variables. For simplicity's sake, let's start with the public one. What I wanna do is export it to an NSData object. For that, there is an almost famous code snippet provide by Apple, which is here:</p> <pre><code>- (NSData *)getPublicKeyBits { OSStatus sanityCheck = noErr; NSData * publicKeyBits = nil; NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; // Set the public key query dictionary. [queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag]; [queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData]; // Get the key bits. sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&amp;publicKeyBits); if (sanityCheck != noErr) { publicKeyBits = nil; } [queryPublicKey release]; return publicKeyBits; } </code></pre> <p>I have Xcode 4.6.2, however, and the code appears erroneous ("__bridge" is added before each conversion to id). The new version looks like this:</p> <pre><code>- (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey { OSStatus sanityCheck = noErr; NSData * publicKeyBits = nil; NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; // Set the public key query dictionary. [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag]; [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnData]; // Get the key bits. sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&amp;publicKeyBits); if (sanityCheck != noErr) { publicKeyBits = nil; } return publicKeyBits; } </code></pre> <p>There are still two errors, though:</p> <ul> <li>use of undeclared identifier 'publicTag'</li> <li>Cast of an indirect pointer to an Objective-C pointer to 'CFTypeRef <em>' (aka 'const void *</em>') is disallowed with ARC</li> </ul> <p>Now, I hope that after your help, the first issue will no longer be a problem, for I do not want to build a query or whatnot to extract the key from the keychain. <strong>I have it in a variable and I wish to extract it from there.</strong> The variable's name is <code>givenPublicKey</code>, and that's the key I wish to convert to NSData.</p> <p>So, how would I go about doing this and solving this ARC-issue?</p> <p>Follow-up: How can I export a <em>private</em> key to NSData, since I've read several time that the function I'm trying to work with only works for public keys.</p>
16,749,925
1
3
null
2013-05-25 11:18:17.33 UTC
9
2018-08-10 07:36:33.437 UTC
null
null
null
null
299,711
null
1
16
ios|objective-c|rsa
13,746
<ul> <li>use of undeclared identifier 'publicTag'</li> </ul> <p>The <code>publicTag</code> is just some unique identifier added to the Keychain items. In the CryptoExercise sample project it is defined as</p> <pre><code>#define kPublicKeyTag "com.apple.sample.publickey" static const uint8_t publicKeyIdentifier[] = kPublicKeyTag; NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)]; </code></pre> <ul> <li>Cast of an indirect pointer to an Objective-C pointer to 'CFTypeRef ' (aka 'const void *') is disallowed with ARC</li> </ul> <p>This can be solved by using a temporary <code>CFTypeRef</code> variable:</p> <pre><code>CFTypeRef result; sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, &amp;result); if (sanityCheck == errSecSuccess) { publicKeyBits = CFBridgingRelease(result); } </code></pre> <ul> <li>I do not want to build a query or whatnot to extract the key from the keychain. I have it in a variable and I wish to extract it from there ...</li> </ul> <p>As far as I know, you have to store the SecKeyRef to the Keychain temporarily. <code>SecItemAdd</code> has the option to return the added item as data. From the documentation:</p> <blockquote> <p>To obtain the data of the added item as an object of type <code>CFDataRef</code>, specify the return type key <code>kSecReturnData</code> with a value of <code>kCFBooleanTrue</code>.</p> </blockquote> <p>Putting all that together, the following code should do what you want:</p> <pre><code>- (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey { static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey"; NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)]; OSStatus sanityCheck = noErr; NSData * publicKeyBits = nil; NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag]; [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; // Temporarily add key to the Keychain, return as data: NSMutableDictionary * attributes = [queryPublicKey mutableCopy]; [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef]; [attributes setObject:@YES forKey:(__bridge id)kSecReturnData]; CFTypeRef result; sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &amp;result); if (sanityCheck == errSecSuccess) { publicKeyBits = CFBridgingRelease(result); // Remove from Keychain again: (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey); } return publicKeyBits; } </code></pre> <p>I hope that this works, I cannot test it at the moment.</p> <ul> <li>Follow-up: How can I export a private key to NSData, since I've read several time that the function I'm trying to work with only works for public keys.</li> </ul> <p>I don't know.</p>
16,891,659
How does concurrency using immutable/persistent types and data structures work?
<p>I've read a lot about functional languages recently. Since those use only immutable structures they claim that concurrency issues are greatly improved/solved. I'm having some serious trouble understanding how this can actually be delivered in a real-life context. Let's assume we have a web server with one thread listening on a port (well, IO is another thing i have difficulty wrapping my head around but let's just ignore that for now); On any connection attempt a socket is created and passed to a newly created thread which does some work with it and, depending on the received communications, may apply changes to a big list/data structure which is global to the server application. So, how does this list access work then in order for all threads having a consistent view of the list (or at least in order to have all changes made by one thread applied to the list as soon as the thread dies in a correct manner)?</p> <p>My problems understanding are:</p> <ul> <li>Obviously any thread can get a unchangeable "snapshot" of the list to work on. However, after "changing" the contents by creating a new version of the list with the changes applied, we are still left with every thread having their own version of the list. How are those merged back together?</li> <li>Another method might consist of using traditional locking mechanisms like mutex/cond or go-like-channels. However, how would you even create such a thing when all variables are immutable?</li> <li>I've heard about STM, however that cannot deal with side effects (i.e. if the list would also transparently backup the data to a file or db)</li> </ul> <p>So how would you model such a thing in a functional language?</p>
17,023,720
1
5
null
2013-06-03 07:11:22.63 UTC
13
2013-06-10 12:20:02.463 UTC
null
null
null
null
1,753,601
null
1
18
functional-programming|immutability
3,162
<p>Immutable values have several applications for which they are well suited. The concurrent/parallel processing is just one of them that got more important recently. The following is really the most basic digest from experience and many books and talks about the subject. You may need to dive into some eventually. </p> <p>The main example you show here is about managing global state, so it cannot be done purely "immutably". However, even here there are very good reasons to use immutable data structures. Some of those from top of my head: </p> <ul> <li>try - catch behaves much better, because you do not modify shared object that may be left modified half-way, with immutable values, it automatically keeps the last consistent state </li> <li>reducing changing state to just multicore safe "compare-and-swap" operations on very limited set of global variables (ideally one), completely eliminates deadlocks </li> <li>free passing of data structures without any defensive copying that is quite often case of mysterious bugs when forgotten (many times defensive copies are created in both calling and called functions, because developers start to incline to "better safe than sorry" after a couple of debugging sessions) </li> <li>much easier unit testing, because many functions operating on immutable values are side-effect free </li> <li>usually easier serialization and more transparent comparison semantics much easier debugging and taking (logging) a current snapshot of the system state even asynchronously </li> </ul> <p>Back to your question though. </p> <p>In the most trivial case the global state in this case is often modelled using one mutable reference at the top holding onto an immutable data structure. </p> <p>The reference is updated only by CAS atomic operation. </p> <p>The immutable data structure is transformed by a side-effect free functions and when all transformations are done the reference is swapped atomically. </p> <p>If two threads/cores want to swap simultaneously new values got from the same old one, the one doing that first wins the other does not succeed (CAS semantics) and needs to repeat the operation (depends on the transformation, either updating the current one with the new value, or transforming the new value from the beginning). This may seem wasteful, but the assumption here is that redoing some work is often cheaper than permanent locking/synchronization overhead. </p> <p>Of course this can be optimized e.g. by partitioning independent parts of immutable data structures to further reduce potential collisions by having several references being updated independently. </p> <p>Access to the data structure is lock-free and very fast and always gives a consistent response. Edge cases like when you send an update and another client receives older data afterwards is to be expected in any system, because of network requests can get out of order too... </p> <p>STM is useful quite rarely and usually you are better of to use atomic swaps of data structure containing all values from references you would use in STM transaction. </p>
16,903,192
What is the difference between the meaning of 0x and \x in Python hex strings?
<p>I'm doing some binary operations which are often shown as hex-es. I have seen both the <code>0x</code> and <code>\x</code> as prefixes.</p> <p>In which case is which used?</p>
16,903,228
2
0
null
2013-06-03 18:17:18.317 UTC
13
2022-07-21 12:46:33.773 UTC
2022-01-10 13:54:36.603 UTC
null
4,621,513
null
1,214,214
null
1
29
python|hex
53,870
<p><code>0x</code> is used for literal numbers. <code>"\x"</code> is used inside strings to represent a character</p> <pre><code>&gt;&gt;&gt; 0x41 65 &gt;&gt;&gt; "\x41" 'A' &gt;&gt;&gt; "\x01" # a non printable character '\x01' </code></pre>
16,989,933
What parts of cordova cli generated projects can be safely versioned in source control?
<p>I'm looking to use <a href="https://github.com/apache/cordova-cli">Cordova CLI</a> instead of a home grown ant solution for command line management of a phonegap/cordova project. I'm wondering what parts of the directory tree, if any, should not be placed under version control?</p>
16,995,798
6
1
null
2013-06-07 17:37:58.777 UTC
5
2019-11-05 04:09:53.67 UTC
null
null
null
null
203,619
null
1
38
version-control|cordova
10,093
<p>It depends on you project and your workflow.</p> <p>For a lot of projects, the <code>./www</code> folder would be sufficient as already mentioned, however there are some other folders that could be good to have depending on what aspects of the cli you are using.</p> <p>Examples:</p> <ul> <li><code>./merges</code> for platform specific HTML/CSS/JS overrides</li> <li><code>./.cordova</code> for cli hooks (like before_build, after_plugin_add, etc)</li> </ul> <p>Plus anything else custom you might want to keep out of <code>./www</code> during development. For example, I have a <code>./src</code> folder and the contents are concatenated and added to <code>./www</code> as part of our build process. Our unit tests are also outside of <code>./www</code>.</p> <p>Instead of including a specific folder, I have a <code>.gitignore</code> that keeps build artefacts like <code>./platforms/*</code> and <code>./plugins/*</code> out of version control.</p>