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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,615,436 | When the soft keyboard appears, it makes my EditText field lose focus | <p>I've got a few EditText fields in a ListView. When I tap on one of the EditText fields, the keyboard slides into view (as it should), but the EditText field I tapped loses focus. I've tried using various InputMethodManager methods to make the keyboard start out in view (in order to get around the problem rather than truly solve it), but that didn't work - the keyboard was not in view when the Activity appeared.</p>
<p>The EditText's type is <code>number</code>, and when the keyboard is sliding in, it is a number keyboard, but when it finishes sliding and the EditText loses focus, it changes to the alphabetical keyboard (which reinforces the idea that the EditText no longer has focus).</p>
<p>My questions are these:</p>
<p>1) How can I make the selection of my EditText field and the subsequent sliding in of the soft keyboard <em>not</em> make my EditText lose focus?</p>
<p>... failing that... </p>
<p>2) How can I make the keyboard start out in view so it never has to slide in (thus avoiding the behavior I find so objectionable)?</p>
<p>My manifest does include <code>android:windowSoftInputMode="stateAlwaysVisible"</code>, but the keyboard does not appear until I tap on an EditText. This ignoring of the 'stateAlwaysVisible' attribute seems to only occur in the emulator - on my provisioned device, it is honored so question number 2 above does work on the device... but not in the emulator. </p>
<p>Thanks for any help you can provide!</p> | 22,470,233 | 11 | 3 | null | 2011-04-10 23:28:26.19 UTC | 29 | 2020-11-15 10:23:59.96 UTC | null | null | null | null | 539,680 | null | 1 | 60 | android|android-emulator|android-edittext | 40,093 | <p>Here is how I did it. The <code>onFocusChangeListener()</code> is called several times when you touch a <code>EditText</code> to type text into it. The sequence is:</p>
<ol>
<li>If focus was on a different view, then that view loses focus</li>
<li>The target gains focus</li>
<li>Soft keyboard pops up.</li>
<li>This causes the target to lose focus</li>
<li>The code detects this situation and calls target.requestFocus()</li>
<li>The leftmost, topmost view gains focus, due to Android nonsense</li>
<li>The leftmost view loses focus, due to requestFocus being called</li>
<li><p>Target finally gains focus</p>
<pre><code>//////////////////////////////////////////////////////////////////
private final int minDelta = 300; // threshold in ms
private long focusTime = 0; // time of last touch
private View focusTarget = null;
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
long t = System.currentTimeMillis();
long delta = t - focusTime;
if (hasFocus) { // gained focus
if (delta > minDelta) {
focusTime = t;
focusTarget = view;
}
}
else { // lost focus
if (delta <= minDelta && view == focusTarget) {
focusTarget.post(new Runnable() { // reset focus to target
public void run() {
focusTarget.requestFocus();
}
});
}
}
}
};
</code></pre></li>
</ol>
<p>The code above works well for the keyboard pop-ups. However, it does not detect the speech-to-text pop-up. </p> |
23,296,282 | What rules does Pandas use to generate a view vs a copy? | <p>I'm confused about the rules Pandas uses when deciding that a selection from a dataframe is a copy of the original dataframe, or a view on the original.</p>
<p>If I have, for example,</p>
<pre><code>df = pd.DataFrame(np.random.randn(8,8), columns=list('ABCDEFGH'), index=range(1,9))
</code></pre>
<p>I understand that a <code>query</code> returns a copy so that something like</p>
<pre><code>foo = df.query('2 < index <= 5')
foo.loc[:,'E'] = 40
</code></pre>
<p>will have no effect on the original dataframe, <code>df</code>. I also understand that scalar or named slices return a view, so that assignments to these, such as </p>
<pre><code>df.iloc[3] = 70
</code></pre>
<p>or </p>
<pre><code>df.ix[1,'B':'E'] = 222
</code></pre>
<p>will change <code>df</code>. But I'm lost when it comes to more complicated cases. For example, </p>
<pre><code>df[df.C <= df.B] = 7654321
</code></pre>
<p>changes <code>df</code>, but</p>
<pre><code>df[df.C <= df.B].ix[:,'B':'E']
</code></pre>
<p>does not.</p>
<p>Is there a simple rule that Pandas is using that I'm just missing? What's going on in these specific cases; and in particular, how do I change all values (or a subset of values) in a dataframe that satisfy a particular query (as I'm attempting to do in the last example above)?</p>
<hr>
<p>Note: This is not the same as <a href="https://stackoverflow.com/q/17960511/656912">this question</a>; and I have read <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#returning-a-view-versus-a-copy" rel="noreferrer">the documentation</a>, but am not enlightened by it. I've also read through the "Related" questions on this topic, but I'm still missing the simple rule Pandas is using, and how I'd apply it to — for example — modify the values (or a subset of values) in a dataframe that satisfy a particular query.</p> | 23,296,545 | 2 | 0 | null | 2014-04-25 14:44:07.503 UTC | 91 | 2021-10-07 06:17:59.407 UTC | 2020-01-30 02:00:32.777 UTC | null | 656,912 | null | 656,912 | null | 1 | 169 | python|pandas|dataframe|indexing|chained-assignment | 56,136 | <p>Here's the rules, subsequent override:</p>
<ul>
<li><p>All operations generate a copy</p></li>
<li><p>If <code>inplace=True</code> is provided, it will modify in-place; only some operations support this</p></li>
<li><p>An indexer that sets, e.g. <code>.loc/.iloc/.iat/.at</code> will set inplace.</p></li>
<li><p>An indexer that gets on a single-dtyped object is almost always a view (depending on the memory layout it may not be that's why this is not reliable). This is mainly for efficiency. (the example from above is for <code>.query</code>; this will <strong>always</strong> return a copy as its evaluated by <code>numexpr</code>)</p></li>
<li><p>An indexer that gets on a multiple-dtyped object is always a copy.</p></li>
</ul>
<p>Your example of <code>chained indexing</code></p>
<pre><code>df[df.C <= df.B].loc[:,'B':'E']
</code></pre>
<p>is not guaranteed to work (and thus you shoulld <strong>never</strong> do this). </p>
<p>Instead do:</p>
<pre><code>df.loc[df.C <= df.B, 'B':'E']
</code></pre>
<p>as this is <em>faster</em> and will always work</p>
<p>The chained indexing is 2 separate python operations and thus cannot be reliably intercepted by pandas (you will oftentimes get a <code>SettingWithCopyWarning</code>, but that is not 100% detectable either). The <a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy" rel="noreferrer">dev docs</a>, which you pointed, offer a much more full explanation.</p> |
30,805,337 | Play's execution contexts vs scala global | <p>How does the execution context from</p>
<pre><code>import scala.concurrent.ExecutionContext.Implicits.global
</code></pre>
<p>differ from Play's execution contexts:</p>
<pre><code>import play.core.Execution.Implicits.{internalContext, defaultContext}
</code></pre> | 30,806,548 | 3 | 0 | null | 2015-06-12 14:20:17.113 UTC | 15 | 2022-04-30 00:59:15.223 UTC | 2017-10-24 17:44:33.057 UTC | null | 1,255,181 | null | 722,180 | null | 1 | 35 | scala|playframework | 9,248 | <p>They are very different.</p>
<p>In Play 2.3.x and prior, <code>play.core.Execution.Implicits.internalContext</code> is a <code>ForkJoinPool</code> with fixed constraints on size, used internally by Play. You should never use it for your application code. From the docs:</p>
<blockquote>
<p>Play Internal Thread Pool - This is used internally by Play. No application code should ever be executed by a thread in this thread pool, and no blocking should ever be done in this thread pool. Its size can be configured by setting internal-threadpool-size in application.conf, and it defaults to the number of available processors.</p>
</blockquote>
<p>Instead, you would use <code>play.api.libs.concurrent.Execution.Implicits.defaultContext</code>, which uses an <code>ActorSystem</code>.</p>
<p>In 2.4.x, they both use the same <code>ActorSystem</code>. This means that Akka will distribute work among its own pool of threads, but in a way that is invisible to you (other than configuration). Several Akka actors can share the same thread.</p>
<p><code>scala.concurrent.ExecutionContext.Implicits.global</code> is an <code>ExecutionContext</code> defined in the Scala standard library. It is a special <code>ForkJoinPool</code> that using the <code>blocking</code> method to handle potentially blocking code in order to spawn new threads in the pool. You really shouldn't use this in a Play application, as Play will have no control over it. It also has the potential to spawn <em>a lot</em> of threads and use a ton of memory, if you're not careful.</p>
<p>I've written more about <code>scala.concurrent.ExecutionContext.Implicits.global</code> in <a href="https://stackoverflow.com/questions/29068064/scala-concurrent-blocking-what-does-it-actually-do/29069021#29069021">this answer</a>.</p> |
35,016,795 | Get root password for Google Cloud Engine VM | <p>I just finished installing cPanel in a CentOS VM in Google Cloud Engine and cPanel said the default username is root and the default password is the server's root password.</p>
<pre><code>2016-01-26 12:02:52 958 ( INFO): 3. Enter the word root in the Username text box
2016-01-26 12:02:52 958 ( INFO):
2016-01-26 12:02:52 958 ( INFO): 4. Enter your root password in the Password text box
2016-01-26 12:02:52 958 ( INFO):
2016-01-26 12:02:52 958 ( INFO): 5. Click the Login button
</code></pre>
<p><strong>How do I get the server's root password?</strong></p> | 35,017,164 | 4 | 0 | null | 2016-01-26 14:55:09.667 UTC | 22 | 2020-12-26 23:40:29.8 UTC | 2018-10-18 10:10:36.32 UTC | null | 5,146,783 | null | 5,146,783 | null | 1 | 74 | google-app-engine|google-cloud-platform | 172,167 | <p>Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using</p>
<blockquote>
<p>sudo passwd</p>
</blockquote>
<p>If you do everything correctly, it should do something like this:</p>
<pre><code>user@server[~]# sudo passwd
Changing password for user root.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
</code></pre> |
32,780,726 | How to access DOM elements in electron? | <p>I am trying to add functionality to a button in <code>index.html</code> file is as follows:
I have a button element in <code>index.html</code></p>
<pre><code><button id="auth-button">Authorize</button>
</code></pre>
<p>In <code>main.js</code> of the app, I have</p>
<pre><code>require('crash-reporter').start();
console.log("oh yaeh!");
var mainWindow = null;
app.on('window-all-closed', function(){
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('ready',function(){
mainWindow = new BrowserWindow({width:800, height : 600});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
var authButton = document.getElementById("auth-button");
authButton.addEventListener("click",function(){alert("clicked!");});
mainWindow.openDevTools();
mainWindow.on('closed',function(){
mainWindow = null;
});
});
</code></pre>
<p>But an error occurs as follows:
<code>Uncaught Exception: ReferenceError: document is not defined</code></p>
<p>Can the DOM objects be accessed while building electron apps? or is there any other alternative way that can give me the required functionality?</p> | 32,781,187 | 4 | 2 | null | 2015-09-25 11:02:09.71 UTC | 19 | 2022-01-27 13:47:16.68 UTC | 2016-04-03 16:19:27.127 UTC | null | 396,043 | null | 3,079,419 | null | 1 | 88 | javascript|dom|electron | 90,128 | <p>DOM can <em>not</em> be accessed in the main process, only in the renderer that it belongs to.</p>
<p>There is an <code>ipc</code> module, available on <a href="http://electron.atom.io/docs/v0.37.8/api/ipc-main/">main process</a> as well as the <a href="http://electron.atom.io/docs/v0.37.8/api/ipc-renderer/">renderer process</a> that allows the communication between these two via sync/async messages.</p>
<p>You also can use the <a href="http://electron.atom.io/docs/v0.37.8/api/remote/">remote</a> module to call main process API from the renderer, but there's nothing that would allow you to do it the other way around.</p>
<p>If you need to run something in the main process as a response to user action, use the <code>ipc</code> module to invoke the function, then you can return a result to the renderer, also using <code>ipc</code>.</p>
<p><em>Code updated to reflect actual (v0.37.8) API, as @Wolfgang suggested in comment, see edit history for deprecated API, if you are stuck with older version of Electron.</em></p>
<p>Example script in <code>index.html</code>:</p>
<pre><code>var ipc = require('electron').ipcRenderer;
var authButton = document.getElementById('auth-button');
authButton.addEventListener('click', function(){
ipc.once('actionReply', function(event, response){
processResponse(response);
})
ipc.send('invokeAction', 'someData');
});
</code></pre>
<p>And in the main process:</p>
<pre><code>var ipc = require('electron').ipcMain;
ipc.on('invokeAction', function(event, data){
var result = processData(data);
event.sender.send('actionReply', result);
});
</code></pre> |
11,087,787 | How do I convert a given number into time format HH:MM:SS in VBA? | <p>I received a list of numbers in Custom format (Type: 000000) that represent military time. It always contain 6 digits, and leading zeros are used when necessary. For example:</p>
<ul>
<li>123456 becomes 12:34:56 (pm) </li>
<li>000321 becomes 00:03:21 (am) </li>
<li>142321 becomes 14:23:21 (pm)</li>
</ul>
<p>How do I convert the integers in Column A into the format in the Column B (hh:mm:ss)? I'd like to use military, 24-hr clock.</p> | 11,088,253 | 3 | 4 | null | 2012-06-18 17:16:33.973 UTC | null | 2015-09-16 18:49:24.023 UTC | 2012-06-18 17:39:45.653 UTC | null | 867,420 | null | 867,420 | null | 1 | 1 | excel|vba|datetime | 80,014 | <p>assuming its a real integer,and not text:</p>
<p><code>=TIME(INT(A1/10000),INT(MOD(A1,10000)/100),MOD(A1,100))</code></p>
<p>if it is text, then use</p>
<p><code>=TIME(VALUE(LEFT(A1,2)),VALUE(MID(A1,3,2)),VALUE(RIGHT(A1,2)))</code></p>
<p>format the result however you want.</p>
<p>As a VBA Function: Integer:</p>
<pre><code>Function RetTime(IntTime As Long) As Date
RetTime = TimeSerial(Int(IntTime / 10000), Int((IntTime Mod 10000) / 100), (IntTime Mod 100))
End Function
</code></pre>
<p>String:</p>
<pre><code>Function RetTimeS(StrTime As String) As Date
RetTimeS = TimeSerial(Val(Left(StrTime, 2)), Val(Mid(StrTime, 3, 2)), Val(Right(StrTime, 2)))
End Function
</code></pre> |
9,581,268 | How can I redirect a php page to another php page? | <blockquote>
<p><strong>Possible Duplicate:</strong><br />
<a href="https://stackoverflow.com/questions/4864522/how-to-redirect-users-to-another-page">How to redirect users to another page?</a></p>
</blockquote>
<p>I'm a beginner in the programming field....I want to redirect a php page to another one..How is it possible in the most easiest way? My concept is just to move,to the home page from the login page after doing the checking of user id and password.</p> | 9,581,301 | 7 | 0 | null | 2012-03-06 09:50:24.027 UTC | 2 | 2020-12-19 19:56:35.707 UTC | 2020-12-19 19:56:35.707 UTC | null | 1,783,163 | null | 1,251,770 | null | 1 | 8 | php | 115,748 | <pre><code><?php
header("Location: your url");
exit;
?>
</code></pre> |
9,303,711 | How do I make ctest run a program with valgrind without dart? | <p>I want to write a CMakeLists.txt so that I can run my tests normally or with valgrind. I have seen much on integrating ctest with valgrind but all with the assumption that you want to set up a server to submit test results to a dart dashboard. I just want to run the tests on my machine and see the results on the command line. </p>
<p>If I have to do a cmake -D VALGRIND=ON thats fine, but I'd rather generate tests named "foo" and "valgrind_foo" if possible. </p> | 9,843,594 | 4 | 0 | null | 2012-02-16 00:15:58.21 UTC | 10 | 2020-02-29 11:51:16.91 UTC | null | null | null | null | 679,354 | null | 1 | 28 | cmake|valgrind | 15,798 | <p>I use valgrind for my memory check. To configure valgrind, I define the following variables in my build system:</p>
<pre><code>find_program( MEMORYCHECK_COMMAND valgrind )
set( MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full" )
</code></pre>
<p>Also, in there is my valgrind suppression file:</p>
<pre><code>set( MEMORYCHECK_SUPPRESSIONS_FILE "${PROJECT_SOURCE_DIR}/valgrind_suppress.txt" )
</code></pre>
<p>After you write your CMakeLists.txt files and configure valgrind correctly in them, you can run the following command:</p>
<pre><code>cmake -G ... (to configure your build)
ctest -D ExperimentalBuild (this will build your code)
ctest -R testName -D ExperimentalTest (just runs the test)
ctest -R testName -D ExperimentalMemCheck (to run the test under valgrind)
</code></pre>
<p>This will trick your build system to run the test automation locally. It expects you to run:</p>
<pre><code>ctest -R testName -D ExperimentalSubmit
</code></pre>
<p>next, to submit to the (default or your) Dashboard, but you don't need to go through this step to run what you want. The results will be stored in the Testing/Temporary/ directory.</p> |
9,547,160 | How to measure time of a statement in scala console? | <p>I'm using Scala to measure performance of regex engine of java. The regexp below executes in around 3 seconds but yet I'm not able to measure it using System.currentTimeMillis. (the last expression returns 0)</p>
<pre><code>scala> val b = System.currentTimeMillis; val v = new Regex("(x+)+y").findAllIn("x"*25); b-System.currentTimeMillis
b: Long = 1330787275629
v: scala.util.matching.Regex.MatchIterator = empty iterator
res18: Long = 0
</code></pre>
<p>Do you now why the last returned value is 0, and not the amount of ms that scala spend on executing the regexp?</p> | 9,547,446 | 6 | 0 | null | 2012-03-03 15:12:34.17 UTC | 16 | 2014-10-10 08:34:29.687 UTC | 2012-03-03 15:46:34.883 UTC | null | 209,605 | null | 80,869 | null | 1 | 32 | regex|scala | 27,389 | <p>The unexplained duration comes from the REPL calling <code>toString</code> on the iterator returned from <code>findAllIn</code>. This in turn calls <a href="https://github.com/scala/scala/blob/master/src/library/scala/util/matching/Regex.scala#L512" rel="noreferrer"><code>Regex.MatchIterator#hasNext</code></a>, which triggers the search.</p>
<pre><code>scala> def time[A](a: => A) = {
| val now = System.nanoTime
| val result = a
| val micros = (System.nanoTime - now) / 1000
| println("%d microseconds".format(micros))
| result
| }
time: [A](a: => A)A
scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'. **
** scala.tools.nsc._ has been imported **
** global._, definitions._ also imported **
** Try :help, :vals, power.<tab> **
scala> :wrap time
Set wrapper to 'time'
scala> new Regex("(x+)+y").findAllIn("x"*25).toString
3000737 microseconds
res19: String = empty iterator
scala> {new Regex("(x+)+y").findAllIn("x"*25); 0}
582 microseconds
res20: Int = 0
</code></pre> |
9,110,478 | How to find the hash of branch in Git? | <p>Given a local / remote branch name, how could I get the hash of the commit that this branch points to?</p> | 9,110,527 | 4 | 0 | null | 2012-02-02 10:12:05.853 UTC | 13 | 2022-05-07 12:17:11.777 UTC | null | null | null | null | 247,243 | null | 1 | 124 | git | 96,506 | <p>The command <a href="https://git-scm.com/docs/git-rev-parse" rel="noreferrer"><code>git rev-parse</code></a> is your friend, e.g.:</p>
<pre><code>$ git rev-parse development
17f2303133734f4b9a9aacfe52209e04ec11aff4
</code></pre>
<p>... or for a remote-tracking branch:</p>
<pre><code>$ git rev-parse origin/master
da1ec1472c108f52d4256049fe1f674af69e785d
</code></pre>
<p>This command is generally very useful, since it can parse any of the ways of specifying branch names in <code>git</code>, such as:</p>
<pre><code>git rev-parse master~3
git rev-parse HEAD@{2.days.ago}
</code></pre>
<p>... etc.</p> |
30,831,037 | Situations where Cell or RefCell is the best choice | <p>When would you be required to use <a href="http://doc.rust-lang.org/std/cell/index.html" rel="noreferrer">Cell or RefCell</a>? It seems like there are many other type choices that would be suitable in place of these, and the documentation warns that using <code>RefCell</code> is a bit of a "last resort".</p>
<p>Is using these types a "<a href="https://en.wikipedia.org/wiki/Code_smell" rel="noreferrer">code smell</a>"? Can anyone show an example where using these types makes more sense than using another type, such as <code>Rc</code> or even <code>Box</code>?</p> | 30,831,983 | 3 | 2 | null | 2015-06-14 15:16:13.313 UTC | 5 | 2018-12-18 17:50:55.79 UTC | 2018-12-18 17:50:55.79 UTC | null | 493,729 | null | 97,964 | null | 1 | 32 | rust|interior-mutability | 11,660 | <p>It is not entirely correct to ask when <code>Cell</code> or <code>RefCell</code> should be used over <code>Box</code> and <code>Rc</code> because these types solve different problems. Indeed, more often than not <code>RefCell</code> is used <em>together</em> with <code>Rc</code> in order to provide mutability with shared ownership. So yes, use cases for <code>Cell</code> and <code>RefCell</code> are entirely dependent on the mutability requirements in your code.</p>
<p>Interior and exterior mutability are very nicely explained in the official Rust book, in the <a href="https://doc.rust-lang.org/book/first-edition/mutability.html" rel="noreferrer">designated chapter on mutability</a>. External mutability is very closely tied to the ownership model, and mostly when we say that something is mutable or immutable we mean exactly the external mutability. Another name for external mutability is <em>inherited</em> mutability, which probably explains the concept more clearly: this kind of mutability is defined by the owner of the data and inherited to everything you can reach from the owner. For example, if your variable of a structural type is mutable, so are all fields of the structure in the variable:</p>
<pre><code>struct Point { x: u32, y: u32 }
// the variable is mutable...
let mut p = Point { x: 10, y: 20 };
// ...and so are fields reachable through this variable
p.x = 11;
p.y = 22;
let q = Point { x: 10, y: 20 };
q.x = 33; // compilation error
</code></pre>
<p>Inherited mutability also defines which kinds of references you can get out of the value:</p>
<pre><code>{
let px: &u32 = &p.x; // okay
}
{
let py: &mut u32 = &mut p.x; // okay, because p is mut
}
{
let qx: &u32 = &q.x; // okay
}
{
let qy: &mut u32 = &mut q.y; // compilation error since q is not mut
}
</code></pre>
<p>Sometimes, however, inherited mutability is not enough. The canonical example is reference-counted pointer, called <code>Rc</code> in Rust. The following code is entirely valid:</p>
<pre><code>{
let x1: Rc<u32> = Rc::new(1);
let x2: Rc<u32> = x1.clone(); // create another reference to the same data
let x3: Rc<u32> = x2.clone(); // even another
} // here all references are destroyed and the memory they were pointing at is deallocated
</code></pre>
<p>At the first glance it is not clear how mutability is related to this, but recall that reference-counted pointers are called so because they contain an internal reference counter which is modified when a reference is duplicated (<code>clone()</code> in Rust) and destroyed (goes out of scope in <code>Rust</code>). Hence <code>Rc</code> <em>has</em> to modify itself even though it is stored inside a non-<code>mut</code> variable.</p>
<p>This is achieved via internal mutability. There are special types in the standard library, the most basic of them being <a href="http://doc.rust-lang.org/std/cell/struct.UnsafeCell.html" rel="noreferrer"><code>UnsafeCell</code></a>, which allow one to work around the rules of external mutability and mutate something even if it is stored (transitively) in a non-<code>mut</code> variable.</p>
<p>Another way to say that something has internal mutability is that this something can be modified through a <code>&</code>-reference - that is, if you have a value of type <code>&T</code> and you can modify the state of <code>T</code> which it points at, then <code>T</code> has internal mutability.</p>
<p>For example, <code>Cell</code> can contain <code>Copy</code> data and it can be mutated even if it is stored in non-<code>mut</code> location:</p>
<pre><code>let c: Cell<u32> = Cell::new(1);
c.set(2);
assert_eq!(c.get(), 2);
</code></pre>
<p><code>RefCell</code> can contain non-<code>Copy</code> data and it can give you <code>&mut</code> pointers to its contained value, and absence of aliasing is checked at runtime. This is all explained in detail on their documentation pages.</p>
<hr>
<p>As it turned out, in overwhelming number of situations you can easily go with external mutability only. Most of existing high-level code in Rust is written that way. Sometimes, however, internal mutability is unavoidable or makes the code much clearer. One example, <code>Rc</code> implementation, is already described above. Another one is when you need shared mutable ownership (that is, you need to access and modify the same value from different parts of your code) - this is usually achieved via <code>Rc<RefCell<T>></code>, because it can't be done with references alone. Even another example is <code>Arc<Mutex<T>></code>, <code>Mutex</code> being another type for internal mutability which is also safe to use across threads.</p>
<p>So, as you can see, <code>Cell</code> and <code>RefCell</code> are not replacements for <code>Rc</code> or <code>Box</code>; they solve the task of providing you mutability somewhere where it is not allowed by default. You can write your code without using them at all; and if you get into a situation when you would need them, you will know it.</p>
<p><code>Cell</code>s and <code>RefCell</code>s are not code smell; the only reason whey they are described as "last resort" is that they move the task of checking mutability and aliasing rules from the compiler to the runtime code, as in case with <code>RefCell</code>: you can't have two <code>&mut</code>s pointing to the same data at the same time, this is statically enforced by the compiler, but with <code>RefCell</code>s you can ask the same <code>RefCell</code> to give you as much <code>&mut</code>s as you like - except that if you do it more than once it will panic at you, enforcing aliasing rules at runtime. Panics are arguably worse than compilation errors because you can only find errors causing them at runtime rather than at compilation time. Sometimes, however, the static analyzer in the compiler is too restrictive, and you indeed do need to "work around" it.</p> |
22,667,104 | How to populate javascript variable with JSON from ViewBag? | <p>I have this Index action:</p>
<pre><code>public ActionResult Index()
{
var repo = (YammerClient) TempData["Repo"];
var msgCol = repo.GetMessages();
ViewBag.User = repo.GetUserInfo();
return View(msgCol.messages);
}
</code></pre>
<p>GetMessages returns a list of POCO messages and GetUserInfo returns a POCO with the info of the user (id, name, etc).</p>
<p>I want to fill a javascript variable with the JSON representation of the user info.</p>
<p>So I would want to do something like this in the view:</p>
<pre><code>...
<script>
var userInfo = "@ViewBag.User.ToJson()"
</script>
...
</code></pre>
<p>I know that doesn't work, but is there a way to do that? I want to avoid having to do an ajax request once the page is loaded just to get the user info.</p> | 22,667,395 | 4 | 1 | null | 2014-03-26 16:18:59.07 UTC | 7 | 2020-08-24 20:45:34.823 UTC | 2015-03-31 20:49:29.183 UTC | null | 209,259 | null | 105,937 | null | 1 | 27 | javascript|asp.net|asp.net-mvc|json|viewbag | 47,713 | <p>In View you can do something like this </p>
<pre><code>@{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.User);
}
</code></pre>
<p>in javascript you can use it as </p>
<pre><code><script>
//use Json.parse to convert string to Json
var userInfo = JSON.parse('@Html.Raw(userInfoJson)');
</script>
</code></pre> |
7,242,226 | Get members of Active Directory Group and check if they are enabled or disabled | <p>What is the fastest way to get a list of all members/users in a given AD group and determine whether or not a user is enabled (or disabled)?</p>
<p>We are potentially talking about 20K users, so I would like to avoid hitting the AD for each individual user.</p> | 7,242,782 | 2 | 1 | null | 2011-08-30 11:08:37.03 UTC | 12 | 2011-08-30 16:30:09.947 UTC | null | null | null | null | 154,991 | null | 1 | 27 | c#|active-directory | 72,861 | <p>If you're on .NET 3.5 and up, you should check out the <code>System.DirectoryServices.AccountManagement</code> (S.DS.AM) namespace. Read all about it here:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc135979.aspx">Managing Directory Security Principals in the .NET Framework 3.5</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx">MSDN docs on System.DirectoryServices.AccountManagement</a></li>
</ul>
<p>Basically, you can define a domain context and easily find users and/or groups in AD:</p>
<pre><code>// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
UserPrincipal theUser = p as UserPrincipal;
if(theUser != null)
{
if(theUser.IsAccountLockedOut())
{
...
}
else
{
...
}
}
}
}
</code></pre>
<p>The new S.DS.AM makes it really easy to play around with users and groups in AD!</p> |
31,265,245 | Extracting 3D coordinates given 2D image points, depth map and camera calibration matrices | <p>I have a set of <code>2D image</code> keypoints that are outputted from the <code>OpenCV FAST</code> corner detection function. Using an <code>Asus Xtion I</code> also have a time-synchronised depth map with all camera calibration parameters known. Using this information I would like to extract a set of <code>3D</code> coordinates (point cloud) in <code>OpenCV.</code></p>
<p>Can anyone give me any pointers regarding how to do so? Thanks in advance!</p> | 31,266,627 | 1 | 4 | null | 2015-07-07 09:49:45.513 UTC | 11 | 2020-07-08 13:25:39.013 UTC | 2015-07-07 09:59:18.433 UTC | null | 648,889 | null | 648,889 | null | 1 | 13 | c++|opencv|3d|asus-xtion | 23,570 | <p>Nicolas Burrus has created a great tutorial for Depth Sensors like Kinect.</p>
<p><a href="http://nicolas.burrus.name/index.php/Research/KinectCalibration" rel="noreferrer">http://nicolas.burrus.name/index.php/Research/KinectCalibration</a></p>
<p>I'll copy & paste the most important parts:</p>
<blockquote>
<p>Mapping depth pixels with color pixels</p>
<p>The first step is to undistort rgb and depth images using the
estimated distortion coefficients. Then, using the depth camera
intrinsics, each pixel (x_d,y_d) of the depth camera can be projected
to metric 3D space using the following formula:</p>
<pre><code>P3D.x = (x_d - cx_d) * depth(x_d,y_d) / fx_d
P3D.y = (y_d - cy_d) * depth(x_d,y_d) / fy_d
P3D.z = depth(x_d,y_d)
</code></pre>
<p>with fx_d, fy_d, cx_d and cy_d the intrinsics of the depth camera.</p>
</blockquote>
<p>If you are further interested in stereo mapping (values for kinect):</p>
<blockquote>
<p>We can then reproject each 3D point on the color image and get its
color:</p>
<pre><code>P3D' = R.P3D + T
P2D_rgb.x = (P3D'.x * fx_rgb / P3D'.z) + cx_rgb
P2D_rgb.y = (P3D'.y * fy_rgb / P3D'.z) + cy_rgb
</code></pre>
<p>with R and T the rotation and translation parameters estimated during
the stereo calibration.</p>
<p>The parameters I could estimate for my Kinect are:</p>
<p>Color</p>
<pre><code>fx_rgb 5.2921508098293293e+02
</code></pre>
</blockquote>
<pre><code>fy_rgb 5.2556393630057437e+02
cx_rgb 3.2894272028759258e+02
cy_rgb 2.6748068171871557e+02
k1_rgb 2.6451622333009589e-01
k2_rgb -8.3990749424620825e-01
p1_rgb -1.9922302173693159e-03
p2_rgb 1.4371995932897616e-03
k3_rgb 9.1192465078713847e-01
</code></pre>
<blockquote>
<p>Depth</p>
<pre><code>fx_d 5.9421434211923247e+02
</code></pre>
</blockquote>
<pre><code>fy_d 5.9104053696870778e+02
cx_d 3.3930780975300314e+02
cy_d 2.4273913761751615e+02
k1_d -2.6386489753128833e-01
k2_d 9.9966832163729757e-01
p1_d -7.6275862143610667e-04
p2_d 5.0350940090814270e-03
k3_d -1.3053628089976321e+00
</code></pre>
<blockquote>
<p>Relative transform between the sensors (in meters)</p>
<pre><code>R [ 9.9984628826577793e-01, 1.2635359098409581e-03, -1.7487233004436643e-02,
</code></pre>
</blockquote>
<pre><code>-1.4779096108364480e-03, 9.9992385683542895e-01, -1.2251380107679535e-02,
</code></pre>
<blockquote>
<pre><code>1.7470421412464927e-02, 1.2275341476520762e-02, 9.9977202419716948e-01 ]
T [ 1.9985242312092553e-02, -7.4423738761617583e-04, -1.0916736334336222e-02 ]
</code></pre>
</blockquote> |
13,730,484 | SELECT multiple rows from single column into single row | <p>I want to write an SQL Server query that will retrieve data from the following example tables:</p>
<pre><code>Table: Person
ID Name
-- ----
1 Bill
2 Bob
3 Jim
Table: Skill
ID SkillName
-- -----
1 Carpentry
2 Telepathy
3 Navigation
4 Opera
5 Karate
Table: SkillLink
ID PersonID SkillID
-- -------- -------
1 1 2
2 3 1
3 1 5
</code></pre>
<p>As you can see, the SkillLink table's purpose is to match various (possibly multiple or none) Skills to individual Persons. The result I'd like to achieve with my query is:</p>
<pre><code>Name Skills
---- ------
Bill Telepathy,Karate
Bob
Jim Carpentry
</code></pre>
<p>So for each individual Person, I want a comma-joined list of all SkillNames pointing to him. This may be multiple Skills or none at all.</p>
<p>This is obviously not the actual data with which I'm working, but the structure is the same.</p>
<p>Please also feel free to suggest a better title for this question as a comment since phrasing it succinctly is part of my problem.</p> | 13,731,188 | 3 | 5 | null | 2012-12-05 18:59:57.023 UTC | 3 | 2013-07-30 09:45:00.843 UTC | 2012-12-05 19:43:49.237 UTC | null | 895,755 | null | 895,755 | null | 1 | 2 | sql|sql-server | 47,506 | <p>You would use <code>FOR XML PATH</code> for this:</p>
<pre><code>select p.name,
Stuff((SELECT ', ' + s.skillName
FROM skilllink l
left join skill s
on l.skillid = s.id
where p.id = l.personid
FOR XML PATH('')),1,1,'') Skills
from person p
</code></pre>
<p>See <a href="http://sqlfiddle.com/#!3/2e1f4/9">SQL Fiddle with Demo</a></p>
<p>Result:</p>
<pre><code>| NAME | SKILLS |
----------------------------
| Bill | Telepathy, Karate |
| Bob | (null) |
| Jim | Carpentry |
</code></pre> |
35,502,450 | lodash _.find all matches | <p>I have simple function to return me object which meets my criteria.</p>
<p>Code looks like:</p>
<pre><code> var res = _.find($state.get(), function(i) {
var match = i.name.match(re);
return match &&
(!i.restrict || i.restrict($rootScope.user));
});
</code></pre>
<p>How can I find all results (not just first) which meets this criteria but all results.</p>
<p>Thanks for any advise.</p> | 35,502,881 | 3 | 1 | null | 2016-02-19 10:02:21.33 UTC | 4 | 2019-06-24 09:06:24.707 UTC | 2019-06-24 09:06:24.707 UTC | null | 2,584,910 | null | 2,584,910 | null | 1 | 63 | javascript|lodash | 79,959 | <p>Just use <code>_.filter</code> - it returns all matched items.</p>
<p><a href="https://lodash.com/docs/4.17.4#filter" rel="noreferrer">_.filter</a></p>
<blockquote>
<p>Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).</p>
</blockquote> |
1,969,049 | C# P/Invoke: Marshalling structures containing function pointers | <p>Sorry for the verbose introduction that follows. I need insight from someone knowing P/Invoke internals better than I do.</p>
<p>Here is how I'm marshalling structures containing function pointers from C to C#. I would like to know whether it's the cleanest and/or most efficient way of doing it.</p>
<p>I'm interfacing with a native DLL coded in C that provides the following entry point:</p>
<pre><code>void* getInterface(int id);
</code></pre>
<p>You have to pass <code>getInterface(int)</code> one of the following enum values:</p>
<pre><code>enum INTERFACES
{
FOO,
BAR
};
</code></pre>
<p>Which returns a pointer to a structure containing function pointers like:</p>
<pre><code>typedef struct IFOO
{
void (*method1)(void* self, int a, float b);
void (*method2)(void* self, int a, float b, int c);
} IFoo;
</code></pre>
<p>And here is how you use it in C:</p>
<pre><code>IFoo* interface = (IFoo*)getInterface(FOO);
interface->method1(obj, 0, 1.0f); // where obj is an instance of an object
// implementing the IFoo interface.
</code></pre>
<p>In C# I have a <code>Library</code> class that maps the <code>getInterface(int)</code> entry point using P/Invoke.</p>
<pre><code>class Library
{
[DllImport("MyDLL"), EntryPoint="getInterface", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr GetInterface(int id);
};
</code></pre>
<p>Then I defined:</p>
<pre><code>struct IFoo
{
public M1 method1;
public M2 method2;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void M1(IntPtr self, int a, float b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void M2(IntPtr self, int a, float b, int c);
}
</code></pre>
<p>And I'm using it this way:</p>
<pre><code>IntPtr address = Library.GetInterface((int)Interfaces.FOO);
IFoo i = (IFoo)Marshal.PtrToStructure(address, typeof(IFoo));
i.method1(obj, 0, 1.0f): // where obj is an instance of an object
// implementing the IFoo interface.
</code></pre>
<p>I have the following questions:</p>
<ol>
<li><p>Is mapping the whole structure less efficient than mapping a single pointer inside the structure using <code>Marshal.GetDelegateForFunctionPointer()</code>?</p>
<p>Since I mostly don't need all the methods exposed by an interface, I can do (tested and works):</p>
<pre><code>unsafe
{
IntPtr address = Library.GetInterface(id);
IntPtr m2address = new IntPtr(((void**)address.toPointer())[1]);
M2 method2 = (M2)Marshal.GetDelegateForFunctionPointer(m2address, typeof(M2));
method2(obj, 0, 1.0f, 1);
}
</code></pre>
</li>
<li><p>When mapping the whole structure at once using <code>Marshal.PtrToStructure()</code>, is there a less verbose way than what I described? I mean less verbose than having to define the delegate types for every methods etc?</p>
</li>
</ol>
<hr />
<p>EDIT: For the sake of clarity and completeness, in the code snippets above, <code>obj</code> is an instance obtained with the <code>void* createObject(int type)</code> entry point.</p>
<hr />
<p>EDIT2: One advantage of method 1) is that <code>Marshal.GetDelegateForFunctionPointer()</code> is only available starting from .NET Framework 2.0. However, <code>Marshal.PrtToStructure()</code> has always been available. That said, I'm not sure it's worth ensuring 1.0 compatibility nowadays.</p>
<hr />
<p>EDIT3: I tried to inspect the generated code using <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a> but it doesn't give much information since all the interesting details are done in helper functions like <code>PtrToStructureHelper</code> and are not exposed. Then, even if I could see what's done in the framework internals, then the runtime has the opportunity to optimize things away and I don't know exactly what, why and when :)</p>
<p>However, I benchmarked the two approaches described in my question. The <code>Marshal.PtrToStructure()</code> approach was slower by a factor around 10% compared to the <code>Marshal.GetDelegateForFunctionPointer()</code> approach; that whith a structure containing <code>IntPtr</code>s for all the functions that are not of interest.</p>
<p>I also compared the <code>Marshal.GetDelegateForFunctionPointer()</code> with my own rolled marshaller: I align a <code>struct</code> representing the call stack, pin it in memory, pass its address to the native side where I use a trampoline coded in asm so that the call function uses the memory area as its parameter stack (this is possible since the <code>cdecl</code> x86 calling convention passes all the function parameters on the stack). Timings were equivalent.</p> | 1,971,454 | 3 | 0 | null | 2009-12-28 11:32:02.017 UTC | 10 | 2010-01-18 18:14:11.48 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 216,063 | null | 1 | 16 | c#|pinvoke|marshalling|structure|function-pointers | 10,819 | <p>I don't know that answer to your question 1. I'd expect that <code>Marshal.PtrToStructure()</code> is implemented in terms of the other Marshal primitives, so it would be more efficient to just use the single <code>Marshal.GetDelegateForFunctionPointer</code>. But that's just a guess - worth what you paid for it.</p>
<p>As for your question 2. No, there is no <em>less</em> verbose way to do this. There is a MORE verbose way. You can use the old style MIDL compiler to build a type library for your dll and the load that type library. But the available marshaling options for MIDL are quite a bit more limited that what you can describe in C#. And the MIDL compler is pretty hard to work with, you would probably end up having to write another unmanaged DLL to do the interop between managed code and your target dll.</p> |
1,998,771 | In oracle, how do I change my session to display UTF8? | <p>I can't figure out Oracle's encryptic syntax for the life of me. This is Oracle 10g</p>
<p>My session's NLS_LANGUAGE is currently defaulting to AMERICAN.
I need to be able to display UTF8 characters.</p>
<p>Below are some of my attempts, all incorrect:</p>
<pre><code>ALTER SESSION SET NLS_LANGUAGE='UTF8'
ALTER SESSION SET NLS_LANGUAGE='AMERICAN_AMERICA.UTF8'
</code></pre>
<p>What's the secret command?</p> | 2,000,243 | 3 | 2 | null | 2010-01-04 10:44:24.44 UTC | 5 | 2015-02-15 22:26:02.717 UTC | 2010-01-06 09:26:22.723 UTC | null | 20,938 | null | 39,529 | null | 1 | 18 | oracle|utf-8 | 120,357 | <p>The character set is part of the locale, which is determined by the value of <code>NLS_LANG</code>. As <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1006330" rel="noreferrer" title="Globalization Support Guide">the documentation makes clear</a> this is <em>an operating system variable</em>:</p>
<blockquote>
<p><code>NLS_LANG</code> is set as an environment
variable on UNIX platforms. <code>NLS_LANG</code>
is set in the registry on Windows
platforms.</p>
</blockquote>
<p>Now we can use <code>ALTER SESSION</code> to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.</p> |
1,450,582 | Classical Vs prototypal inheritance | <p>After reading about both, I just have curiosity, how programming community uses this?
In what situation which?</p> | 1,450,598 | 3 | 0 | null | 2009-09-20 08:21:21.363 UTC | 15 | 2013-11-08 23:13:02.423 UTC | null | null | null | null | 147,695 | null | 1 | 20 | javascript|oop | 8,582 | <p>Prototype-based inheritance is more flexible. Any existing object can become a class from which additional objects will be spawned. This is handy where your objects offer several sets of services and/or they undergo a lot of state transformation before your program arrives at the point where the inheritance is needed.</p>
<p>A broad-spectrum discussion of modeling approaches is available here: <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="noreferrer">http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html</a></p> |
2,013,793 | Web Services vs EJB vs RMI, advantages and disadvantages? | <p>My web server would be overloaded quickly if all the work were done there. I'm going to stand up a second server behind it, to process data.</p>
<p>What's the advantage of EJB over RMI, or vice versa? </p>
<p>What about web services (SOAP, REST)?</p> | 2,293,422 | 3 | 0 | 2010-01-06 15:03:32.197 UTC | 2010-01-06 15:03:32.197 UTC | 48 | 2015-11-28 19:09:22.073 UTC | null | null | null | null | 182,690 | null | 1 | 57 | java|web-services|ejb|distributed|rmi | 71,528 | <p>EJBs are built on top of RMI. Both imply Java clients and beans. If your clients need to be written in something else (e.g., .NET, PHP, etc.) go with web services or something else that speaks a platform-agnostic wire protocol, like HTTP or XML over HTTP or SOAP.</p>
<p>If you choose RMI, you don't need a Java EE EJB app server. You have to keep client and server JVMs in synch; you can't upgrade the client without upgrading the server. You have to write all the services that the EJB app server provides for you (e.g., connection pooling, naming and directory services, pooling, request queuing, transactions, etc.).</p>
<p>RMI is quite low level when you think about it. Why would you drop all the way back to CORBA?</p>
<p>A better choice is EJB 3.0 versus Spring. It depends on whether you like POJO development, want a choice of relational technologies besides ORM and JPA, among other things.</p>
<p>You can pay for a Java EE app server (e.g., WebLogic, WebSphere) or use an open source one (JBOSS, Glassfish and OpenEJB and ActiveMQ), or you can stick to Spring and deploy on Tomcat, Jetty, Resin or any other servlet/JSP engine.</p>
<p>Spring offers a lot of choice by being technology agnostic: persistence (Hibernate, iBatis, JDBC, JDO, JPA, TopLink), remoting (HTTP, Hessian, Burlap, RMI, SOAP web service), etc. </p>
<p>EJB 3.0 is a spec with many vendors; Spring can only be had from Spring Source.</p>
<p>I would recommend <a href="http://www.springsource.org/" rel="noreferrer">Spring</a>. It's very solid, has lots of traction, isn't going anywhere. It leaves all your options open. </p>
<p>Web services are great in theory, but there are some gotchas that you need to watch out for: </p>
<ol>
<li>Latency. Fowler's first law of distributed objects: "Don't!" An architecture consisting of lots of fine-grained distributed SOAP services will be elegant, beautiful, and slow as molasses. Think carefully before distributing.</li>
<li>Marshalling from XML to objects and back consumes CPU cycles that aren't providing any business value besides allowing your clients to speak a platform-agnostic protocol. </li>
<li>SOAP is a standard that is becoming more bloated and complex every day, but it has lots of tool support. Vendors like it because it helps drive sales of ESBs. REST is simple but not as well understood. It's not supported by tools.</li>
</ol>
<p>Spring's web service module is very good, but do be careful about choosing to deploy this way. Write in terms of POJO service interfaces. These will allow you to get the conceptual isolation you want, defer the deployment choice until the last moment, and let you change your mind if the first thought doesn't perform well.</p> |
1,919,982 | RegEx: Smallest possible match or nongreedy match | <p>How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?</p> | 1,919,995 | 3 | 0 | null | 2009-12-17 07:12:16.96 UTC | 25 | 2020-06-09 19:52:21.917 UTC | 2020-02-07 13:01:25.133 UTC | null | 1,243,762 | null | 5,274 | null | 1 | 156 | .net|regex|regex-greedy|non-greedy | 102,741 | <p>For a regular expression like <code>.*</code> or <code>.+</code>, append a question mark (<code>.*?</code> or <code>.+?</code>) to match as few characters as possible. To optionally match a section <code>(?:blah)?</code> but without matching unless absolutely necessary, use something like <code>(?:blah){0,1}?</code>. For a repeating match (either using <code>{n,}</code> or <code>{n,m}</code> syntax) append a question mark to try to match as few as possible (e.g. <code>{3,}?</code> or <code>{5,7}?</code>).</p>
<p>The documentation on <a href="https://msdn.microsoft.com/en-us/library/3206d374(v=vs.110).aspx" rel="noreferrer">regular expression quantifiers</a> may also be helpful.</p> |
8,952,819 | How to choose between Factory method pattern and Abstract factory pattern | <p>I know similar questions were asked before. I've been reading a lot about this during the last couple of days and I think I can now understand the differences in terms of design and code flow. What bothers me it's that it seems like both pattern can solve the very same set of problems without a real reason to choose one or another.
While I was trying to figure this out by myself, I tried to implement a little example (starting from the one I found on "Head First: Design patterns" book).
In this example I tried to solve the same problem twice: one time using only the "Factory method pattern" and the other using the "Abstract Factory pattern". I'll show you the code and then I'll make some comments and the question. </p>
<h3>Common interfaces and classes</h3>
<pre><code>public interface IDough { }
public interface ISauce { }
public class NYDough : IDough { }
public class NYSauce : ISauce { }
public class KNDough : IDough { }
public class KNSauce : ISauce { }
</code></pre>
<h3>Pure Factory method pattern</h3>
<pre><code>// pure Factory method pattern
public abstract class Pizza
{
protected IDough Dough { get; set; }
protected ISauce Sauce { get; set; }
protected abstract IDough CreateDough();
protected abstract ISauce CreateSauce();
public void Prepare()
{
Dough = CreateDough();
Sauce = CreateSauce();
// do stuff with Dough and Sauce
}
public void Bake() { }
public void Cut() { }
public void Box() { }
}
public class NYCheesePizza : Pizza
{
protected override IDough CreateDough()
{
return new NYDough();
}
protected override ISauce CreateSauce()
{
return new NYSauce();
}
}
public class KNCheesePizza : Pizza
{
protected override IDough CreateDough()
{
return new KNDough();
}
protected override ISauce CreateSauce()
{
return new KNSauce();
}
}
public abstract class PizzaStore
{
public void OrderPizza(string type)
{
Pizza pizza = CreatePizza(type);
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
}
public abstract Pizza CreatePizza(string type);
}
public class NYPizzaStore : PizzaStore
{
public override Pizza CreatePizza(string type)
{
switch (type)
{
case "cheese":
return new NYCheesePizza();
default:
return null;
}
}
}
public class KNPizzaStore : PizzaStore
{
public override Pizza CreatePizza(string type)
{
switch (type)
{
case "cheese":
return new KNCheesePizza();
default:
return null;
}
}
}
</code></pre>
<h3>pure Abstract factory pattern</h3>
<pre><code>public interface IIngredientFactory
{
IDough createDough();
ISauce createSauce();
}
public class NYIngredientFactory : IIngredientFactory
{
public IDough createDough()
{
return new NYDough();
}
public ISauce createSauce()
{
return new NYSauce();
}
}
public class KNIngredientFactory : IIngredientFactory
{
public IDough createDough()
{
return new KNDough();
}
public ISauce createSauce()
{
return new KNSauce();
}
}
public class Pizza
{
IDough Dough { get; set; }
ISauce Sauce { get; set; }
IIngredientFactory IngredientFactory { get; set; }
public Pizza(IIngredientFactory ingredientFactory)
{
IngredientFactory = ingredientFactory;
}
public void Prepare()
{
Dough = IngredientFactory.createDough();
Sauce = IngredientFactory.createSauce();
}
public void Bake() { }
public void Cut() { }
public void Box() { }
}
public interface IPizzaFactory
{
Pizza CreatePizza(string type);
}
public class NYPizzaFactory : IPizzaFactory
{
public Pizza CreatePizza(string type)
{
switch (type)
{
case "cheese":
return new Pizza(new NYIngredientFactory());
default:
return null;
}
}
}
public class KNPizzaFactory : IPizzaFactory
{
public Pizza CreatePizza(string type)
{
switch (type)
{
case "cheese":
return new Pizza(new KNIngredientFactory());
default:
return null;
}
}
}
public class PizzaStore
{
IPizzaFactory PizzaFactory { get; set; }
public PizzaStore(IPizzaFactory pizzaFactory)
{
PizzaFactory = pizzaFactory;
}
public void OrderPizza(string type)
{
Pizza pizza = PizzaFactory.CreatePizza(type);
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
}
}
</code></pre>
<p>If I had used the patterns definitions I would have chosen a "Factory Method Pattern" for the <code>PizzaStore</code> (since it only builds one type of object, Pizza) and the "Abstract Factory Pattern" for the <code>IngredientFactory</code>. Anyway, another design principle, states that you should "favor composition over inheritance" which suggests that I should always use the "Abstract Factory Pattern".</p>
<p>My question is: What are the reasons I should choose the "Factory Method Pattern" in the first place?</p>
<h2>EDIT</h2>
<p>Let's take a look at the first implementation, the one that uses the Factory method pattern. Jesse van Assen suggested that this is a Template method pattern instead of a Factory method pattern. I'm not convinced it's right.
We can break down the first implementation in two parts: the first one that deals with <code>Pizza</code> and the second one that deals with <code>PizzaStore</code>.</p>
<p>1) in the first part <code>Pizza</code> is the client that is dependent on some kind of concrete Dough and Sauce. In order to decouple Pizza from concrete objects I used, within the <code>Pizza</code> class, reference to interfaces only (<code>IDough</code> and <code>ISauce</code>) and I let the <code>Pizza</code>'s subclasses decide which concrete <code>Dough</code> and <code>Sauce</code> choose. To me this fits perfectly with the definition of a Factory method pattern: </p>
<blockquote>
<p>Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.</p>
</blockquote>
<p>2) in the second part <code>PizzaStore</code> is the client and it's dependent on concrete <code>Pizza</code>. I applied the same principles discussed above. </p>
<p>So, to express better (I hope) what I don't really get is why is said that:</p>
<blockquote>
<p>Factory Method pattern is responsible of creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products.</p>
</blockquote>
<p>As you see from my examples (provided they are right :-)) you can same stuff with both patterns.</p> | 8,960,529 | 2 | 1 | null | 2012-01-21 12:05:36.103 UTC | 11 | 2013-12-04 08:19:19.26 UTC | 2013-04-18 18:29:24.063 UTC | null | 661,933 | user1047100 | null | null | 1 | 15 | c#|design-patterns|factory-pattern | 5,989 | <p>First, 2 quotes from the GoF design patterns book:</p>
<blockquote>
<p>"Abstract Factory is often implemented with factory methods."</p>
<p>"Factory Methods are often called by template methods."</p>
</blockquote>
<p>So it's not a question of choosing between Factory Methods and Abstract Factories, because the later can be (and usually is) implemented by the former.</p>
<p>The concept of Abstract Factories (as Amir hinted) is to group the creation of several concrete classes that always go together. In your example they should be the the NY varieties of food components as opposed to the KN ones.</p>
<p>But if you want to allow mix & match (what's wrong with a Pizza with KN dough and NY souce?) then Abstract factories are not your answer. In that case, each Pizza subclass should decide which concrete classes it wishes to create.</p>
<p>If you don't want to allow these kinds of mixings, you should go with Abstract Factories.</p> |
19,774,778 | When is it necessary to use the flag -stdlib=libstdc++? | <p>When is it necessary to use use the flag <code>-stdlib=libstdc++</code> for the compiler and linker when compiling with gcc?</p>
<p>Does the compiler automatically use libstdc++? </p>
<p>I am using gcc4.8.2 on Ubuntu 13.10 and I would like to use the c++11 standard. I already pass <code>-std=c++11</code> to the compiler.</p> | 19,774,902 | 3 | 1 | null | 2013-11-04 18:43:51.987 UTC | 25 | 2021-12-07 22:24:54.79 UTC | 2020-01-21 18:47:31.02 UTC | null | 2,565,958 | null | 2,120,821 | null | 1 | 79 | c++|gcc|c++11|std|libstdc++ | 110,590 | <p><strong>On Linux</strong>: In general, all commonly available linux distributions will use libstdc++ by default, and all modern versions of GCC come with a libstdc++ that supports C++11. If you want to compile c++11 code here, use one of:</p>
<ul>
<li><code>g++ -std=c++11 input.cxx -o a.out</code> (usually GNU compiler)</li>
<li><code>g++ -std=gnu++11 input.cxx -o a.out</code></li>
</ul>
<p><strong>On OS X before Mavericks</strong>: <code>g++</code> was actually an alias for <code>clang++</code> and Apple's old version of libstdc++ was the default. You could use libc++ (which included c++11 library support) by passing <code>-stdlib=libc++</code>. If you want to compile c++11 code here, use one of:</p>
<ul>
<li><code>g++ -std=c++11 -stdlib=libc++ input.cxx -o a.out</code> (clang, not GNU compiler!)</li>
<li><code>g++ -std=gnu++11 -stdlib=libc++ input.cxx -o a.out</code> (clang, not GNU compiler!)</li>
<li><code>clang++ -std=c++11 -stdlib=libc++ input.cxx -o a.out</code></li>
<li><code>clang++ -std=gnu++11 -stdlib=libc++ input.cxx -o a.out</code></li>
</ul>
<p><strong>On OS X since Mavericks</strong>: libc++ is the default and you should not pass any <code>-stdlib=<...></code> flag. Since Xcode 10, <a href="https://developer.apple.com/documentation/xcode-release-notes/xcode-10-release-notes#Deprecations" rel="noreferrer">building against libstdc++ is not supported at all anymore</a>. Existing code built against libstdc++ will keep working because <code>libstdc++.6.dylib</code> is still provided, but compiling new code against libstdc++ is not supported.</p>
<ul>
<li><code>clang++ -std=c++11 input.cxx -o a.out</code></li>
<li><code>clang++ -std=gnu++11 input.cxx -o a.out</code></li>
</ul> |
716,748 | Reverse IP Domain Check? | <p>There is a website which you can query with a domain and it will return a list of all the websites hosted on that IP. I remember there being a method in C# that was something like ReturnAddresses or something of that sort. Does anyone have any idea how this is done? Quering a hostname or IP and having returned a list of hostnames aka other websites hosted on the same server?</p>
<p>the website is: <a href="http://www.yougetsignal.com/tools/web-sites-on-web-server/" rel="noreferrer">http://www.yougetsignal.com/tools/web-sites-on-web-server/</a></p> | 716,753 | 4 | 0 | null | 2009-04-04 08:08:43.997 UTC | 10 | 2022-05-07 19:35:29.893 UTC | 2012-07-29 00:34:07.437 UTC | Alnitak | 41,071 | Arnold Boshae | null | null | 1 | 12 | c#|dns | 22,131 | <p>After reading the comments, bobince is definitely right and these 2 should be used in tandem with each other. For best results you should use the reverse DNS lookup here as well as to use the passive DNS replication.</p>
<pre><code>string IpAddressString = "208.5.42.49"; //eggheadcafe
try
{
IPAddress hostIPAddress = IPAddress.Parse(IpAddressString);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
// Get the IP address list that resolves to the host names contained in
// the Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;
Console.WriteLine("Host name : " + hostInfo.HostName);
Console.WriteLine("\nAliases :");
for(int index=0; index < alias.Length; index++) {
Console.WriteLine(alias[index]);
}
Console.WriteLine("\nIP address list : ");
for(int index=0; index < address.Length; index++) {
Console.WriteLine(address[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(FormatException e)
{
Console.WriteLine("FormatException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
</code></pre>
<p>courtesy of <a href="http://www.eggheadcafe.com/community/aspnet/2/83624/system-dns-gethostbyaddre.aspx" rel="noreferrer">http://www.eggheadcafe.com/community/aspnet/2/83624/system-dns-gethostbyaddre.aspx</a></p> |
1,157,814 | How to access original activity's views from spawned background service | <p>I have an activity called A, and on the selection of menu item 0, it spawns service B, which starts a runnable C in a new thread. I have a TextView in activity A, which I want to access in thread C. </p>
<p>I've tried making the TextView a public static field, but that generates the following error:</p>
<pre><code>07-21 07:26:25.723: ERROR/AndroidRuntime(1975): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.view.ViewRoot.checkThread(ViewRoot.java:2440)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.view.ViewRoot.invalidateChild(ViewRoot.java:522)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:540)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2332)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.view.View.invalidate(View.java:4437)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.widget.TextView.updateAfterEdit(TextView.java:4593)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.widget.TextView.handleTextChanged(TextView.java:5932)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6081)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:259)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:28)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.widget.TextView.append(TextView.java:2191)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at android.widget.TextView.append(TextView.java:2178)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at com.android.peekaboo.DoScan$scanBody.run(DoScan.java:36)
07-21 07:26:25.723: ERROR/AndroidRuntime(1975): at java.lang.Thread.run(Thread.java:1058)
</code></pre>
<p>I have also considered trying to pass the View through an intent, but do not know how that would work. What do I need to make this work?</p> | 1,158,269 | 4 | 0 | null | 2009-07-21 07:52:45.863 UTC | 12 | 2012-05-15 21:52:38.613 UTC | null | null | null | null | 122,961 | null | 1 | 29 | android|user-interface|pass-by-reference|textview | 36,531 | <p>You have to update widgets from the GUI thread, aka 'the thread that created the view hierarchy'. The standard way to do this is via <a href="http://developer.android.com/reference/android/os/Handler.html" rel="nofollow noreferrer"><code>Handler</code></a>s and an example of how to use handlers can be found in the <a href="http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog" rel="nofollow noreferrer">ProgressDialog Example</a> (expand 'Example ProgressDialog with a second thread').</p> |
48,128,471 | Insert array values into database in laravel | <p>I have 8 different questions that are coming from the database randomly.</p>
<p>Now I want to insert the <code>question_id</code>, <code>user_id</code> and <code>en_answer</code> into <code>en_answers</code> table. </p>
<p>Data was inserted, but here is some error like - the first one is, it's inserting only one-row value and the second one is, the question id is not correct.</p>
<p>I tried something like bellow. Would someone please help to correct the controller method -</p>
<p>In <strong>index.blade.php</strong> -</p>
<pre><code><form action="{{ url('en-question-answer') }}" method="POST">
{{ csrf_field() }}
<?php
$count=1;
;?>
@foreach($equestions as $equestionType)
@foreach($equestionType as $key => $equestion)
<p>{{ $equestion->question }}</p>
<input type="hidden" name="question_id[{{$count}}]" value="{{ $equestion->id }}">
<label class="radio-inline">
<input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option1 }}">{{ $equestion->option1 }}
</label>
<label class="radio-inline">
<input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option2 }}">{{ $equestion->option2 }}
</label>
<hr>
<?php $count++; ?>
@endforeach
@endforeach
<button type="submit" class="btn btn-primary btn-sm pull-right">Submit</button></form>
</code></pre>
<p>In my controller-</p>
<pre><code> public function store(Request $request, User $user){
$user_id = Sentinel::getUser()->id;
$answer = new EnAnswer;
$answer->user_id = $user_id;
$data = Input::get();
for($i = 1; $i < count($data['en_answer']); $i++) {
$answer->en_answer = $data['en_answer'][$i];
}
for($i = 1; $i < count($data['question_id']); $i++) {
$answer->question_id = $data['question_id'][$i];
}
//dd($answer);
//return $answer;
$answer->save();
return redirect('submitted')->with('status', 'Your answers successfully submitted');
}
</code></pre> | 48,128,541 | 2 | 2 | null | 2018-01-06 14:43:53.44 UTC | 5 | 2021-12-30 09:16:36.04 UTC | 2020-02-16 12:18:02.08 UTC | null | 7,014,431 | null | 7,014,431 | null | 1 | 12 | php|mysql|arrays|laravel|multidimensional-array | 64,590 | <p>You're inserting into DB just one answer, the last one. Also, you can prepare the data and insert all the answers with just one query:</p>
<pre><code>public function store(Request $request)
{
for ($i = 1; $i < count($request->en_answer); $i++) {
$answers[] = [
'user_id' => Sentinel::getUser()->id,
'en_answer' => $request->en_answer[$i],
'question_id' => $request->question_id[$i]
];
}
EnAnswer::insert($answers);
return redirect('submitted')->with('status', 'Your answers successfully submitted');
}
</code></pre> |
30,521,224 | Javascript convert PascalCase to underscore_case/snake_case | <p>How can I convert <code>PascalCase</code> string into <code>underscore_case/snake_case</code> string? I need to convert dots into underscores as well.</p>
<p>eg. convert</p>
<pre><code>TypeOfData.AlphaBeta
</code></pre>
<p>into</p>
<pre><code>type_of_data_alpha_beta
</code></pre> | 30,521,308 | 11 | 1 | null | 2015-05-29 04:37:53.073 UTC | 11 | 2022-07-20 07:46:19.207 UTC | 2021-08-23 05:43:31.657 UTC | null | 4,480,993 | null | 4,646,070 | null | 1 | 85 | javascript|string|case-conversion | 61,407 | <p>You could try the below steps.</p>
<ul>
<li><p>Capture all the uppercase letters and also match the preceding optional dot character.</p></li>
<li><p>Then convert the captured uppercase letters to lowercase and then return back to replace function with an <code>_</code> as preceding character. This will be achieved by using anonymous function in the replacement part.</p></li>
<li><p>This would replace the starting uppercase letter to <code>_</code> + lowercase_letter. </p></li>
<li><p>Finally removing the starting underscore will give you the desired output.</p>
<pre><code>var s = 'TypeOfData.AlphaBeta';
console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
</code></pre></li>
</ul>
<p><strong>OR</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));</code></pre>
</div>
</div>
</p>
<blockquote>
<p>any way to stop it for when a whole word is in uppercase. eg. <code>MotorRPM</code> into <code>motor_rpm</code> instead of <code>motor_r_p_m</code>? or <code>BatteryAAA</code> into <code>battery_aaa</code> instead of <code>battery_a_a_a</code>?</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));</code></pre>
</div>
</div>
</p> |
20,515,554 | Colorize Voronoi Diagram | <p>I'm trying to colorize a Voronoi Diagram created using <a href="http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.Voronoi.html" rel="noreferrer"><code>scipy.spatial.Voronoi</code></a>. Here's my code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
# make up data points
points = np.random.rand(15,2)
# compute Voronoi tesselation
vor = Voronoi(points)
# plot
voronoi_plot_2d(vor)
# colorize
for region in vor.regions:
if not -1 in region:
polygon = [vor.vertices[i] for i in region]
plt.fill(*zip(*polygon))
plt.show()
</code></pre>
<p>The resulting image:</p>
<p><img src="https://i.stack.imgur.com/vmZpK.png" alt="Voronoi Diagram"></p>
<p>As you can see some of the Voronoi regions at the border of the image are not colored. That is because some indices to the Voronoi vertices for these regions are set to <code>-1</code>, i.e., for those vertices outside the Voronoi diagram. According to the docs:</p>
<blockquote>
<p><em>regions:</em> (list of list of ints, shape (nregions, *)) Indices of the Voronoi vertices forming each Voronoi region. <strong>-1 indicates vertex outside the Voronoi diagram.</strong></p>
</blockquote>
<p>In order to colorize these regions as well, I've tried to just remove these "outside" vertices from the polygon, but that didn't work. I think, I need to fill in some points at the border of the image region, but I can't seem to figure out how to achieve this reasonably.</p>
<p>Can anyone help?</p> | 20,678,647 | 3 | 1 | null | 2013-12-11 09:39:56.817 UTC | 40 | 2019-07-17 10:49:00.677 UTC | 2016-06-27 12:45:25.05 UTC | null | -1 | null | 1,025,391 | null | 1 | 68 | python|matplotlib|scipy|visualization|voronoi | 39,695 | <p>The Voronoi data structure contains all the necessary information to construct positions for the "points at infinity". Qhull also reports them simply as <code>-1</code> indices, so Scipy doesn't compute them for you.</p>
<p><a href="https://gist.github.com/pv/8036995">https://gist.github.com/pv/8036995</a></p>
<p><a href="http://nbviewer.ipython.org/gist/pv/8037100">http://nbviewer.ipython.org/gist/pv/8037100</a></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi
def voronoi_finite_polygons_2d(vor, radius=None):
"""
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
Input diagram
radius : float, optional
Distance to 'points at infinity'.
Returns
-------
regions : list of tuples
Indices of vertices in each revised Voronoi regions.
vertices : list of tuples
Coordinates for revised Voronoi vertices. Same as coordinates
of input vertices, with 'points at infinity' appended to the
end.
"""
if vor.points.shape[1] != 2:
raise ValueError("Requires 2D input")
new_regions = []
new_vertices = vor.vertices.tolist()
center = vor.points.mean(axis=0)
if radius is None:
radius = vor.points.ptp().max()
# Construct a map containing all ridges for a given point
all_ridges = {}
for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
all_ridges.setdefault(p1, []).append((p2, v1, v2))
all_ridges.setdefault(p2, []).append((p1, v1, v2))
# Reconstruct infinite regions
for p1, region in enumerate(vor.point_region):
vertices = vor.regions[region]
if all(v >= 0 for v in vertices):
# finite region
new_regions.append(vertices)
continue
# reconstruct a non-finite region
ridges = all_ridges[p1]
new_region = [v for v in vertices if v >= 0]
for p2, v1, v2 in ridges:
if v2 < 0:
v1, v2 = v2, v1
if v1 >= 0:
# finite ridge: already in the region
continue
# Compute the missing endpoint of an infinite ridge
t = vor.points[p2] - vor.points[p1] # tangent
t /= np.linalg.norm(t)
n = np.array([-t[1], t[0]]) # normal
midpoint = vor.points[[p1, p2]].mean(axis=0)
direction = np.sign(np.dot(midpoint - center, n)) * n
far_point = vor.vertices[v2] + direction * radius
new_region.append(len(new_vertices))
new_vertices.append(far_point.tolist())
# sort region counterclockwise
vs = np.asarray([new_vertices[v] for v in new_region])
c = vs.mean(axis=0)
angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0])
new_region = np.array(new_region)[np.argsort(angles)]
# finish
new_regions.append(new_region.tolist())
return new_regions, np.asarray(new_vertices)
# make up data points
np.random.seed(1234)
points = np.random.rand(15, 2)
# compute Voronoi tesselation
vor = Voronoi(points)
# plot
regions, vertices = voronoi_finite_polygons_2d(vor)
print "--"
print regions
print "--"
print vertices
# colorize
for region in regions:
polygon = vertices[region]
plt.fill(*zip(*polygon), alpha=0.4)
plt.plot(points[:,0], points[:,1], 'ko')
plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/Dn3r4.png"><img src="https://i.stack.imgur.com/Dn3r4.png" alt="enter image description here"></a></p> |
20,609,118 | HttpClient with BaseAddress | <p>I have a problem calling a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.webhttpbinding%28v=vs.110%29.aspx" rel="noreferrer">webHttpBinding</a> WCF end point using <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.110%29.aspx" rel="noreferrer">HttpClient</a> and the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.baseaddress%28v=vs.110%29.aspx" rel="noreferrer">BaseAddress</a> property.</p>
<p><strong>HttpClient</strong></p>
<p>I created a <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.110%29.aspx" rel="noreferrer">HttpClient</a> instance specifying the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.baseaddress%28v=vs.110%29.aspx" rel="noreferrer">BaseAddress</a> property as a local host endpoint.</p>
<p><img src="https://i.stack.imgur.com/hEBcu.png" alt="enter image description here"></p>
<p><strong>GetAsync Call</strong></p>
<p>I then call the <a href="http://msdn.microsoft.com/en-us/library/hh158912%28v=vs.110%29.aspx" rel="noreferrer">GetAsync</a> method passing in the additional Uri inforamtion.</p>
<pre><code>HttpResponseMessage response = await client.GetAsync(string.Format("/Layouts/{0}", machineInformation.LocalMachineName()));
</code></pre>
<p><img src="https://i.stack.imgur.com/B9XNQ.png" alt="enter image description here"></p>
<p><strong>Service endpoint</strong></p>
<pre><code>[OperationContract]
[WebGet(UriTemplate = "/Layouts/{machineAssetName}", ResponseFormat = WebMessageFormat.Json)]
List<LayoutsDto> GetLayouts(string machineAssetName);
</code></pre>
<p><strong>Problem</strong></p>
<p>The problem I am having is that the is that <code>/AndonService.svc</code> part of the BaseAddress is being truncated so the resultant call goes to <code>https://localhost:44302/Layouts/1100-00277</code> rather that <code>https://localhost:44302/AndonService.svc/Layouts/1100-00277</code> resulting in a 404 Not Found.</p>
<p>Is there a reason the BaseAddress is being truncated in the GetAsync call? How do I get around this?</p> | 20,609,275 | 1 | 1 | null | 2013-12-16 10:54:23.487 UTC | 2 | 2013-12-26 21:26:37.867 UTC | 2013-12-26 21:26:37.867 UTC | null | 6,819 | null | 713,228 | null | 1 | 40 | c#|.net|wcf|dotnet-httpclient|webhttpbinding | 29,763 | <p>In the <code>BaseAddress</code>, just include the final slash: <code>https://localhost:44302/AndonService.svc/</code>. If you don't, the final part of the path is discarded, because it's not considered to be a "directory".</p>
<p>This sample code illustrates the difference:</p>
<pre><code>// No final slash
var baseUri = new Uri("https://localhost:44302/AndonService.svc");
var uri = new Uri(baseUri, "Layouts/1100-00277");
Console.WriteLine(uri);
// Prints "https://localhost:44302/Layouts/1100-00277"
// With final slash
var baseUri = new Uri("https://localhost:44302/AndonService.svc/");
var uri = new Uri(baseUri, "Layouts/1100-00277");
Console.WriteLine(uri);
// Prints "https://localhost:44302/AndonService.svc/Layouts/1100-00277"
</code></pre> |
46,727,850 | Navigation is blocked error in Chrome 61+ on Android | <p>I'm building a login page that, upon submitting and validation of the user credentials, opens up a native mobile application. Up till last week, I had this working cross mobile OS by using a custom scheme URI, something like:</p>
<pre><code>function onLoginCallback() {
const redirectUri = 'customscheme:/action?param1=val1&param2=val2';
window.location.replace(redirectUri);
}
</code></pre>
<p>The login page is displayed in an IABT, short for In App Browser Tab.</p>
<p>However, since the release of version 61 of Chrome, this is approach is broken on Android. Chrome blocks the redirect because there's no apparent user action related to the redirect (see <a href="https://developer.chrome.com/multidevice/android/intents" rel="noreferrer">here</a> for more information on the matter).</p>
<p>As a consequence, when executing the code above, I'll end up with a warning in the console:</p>
<blockquote>
<p>Navigation is blocked: customscheme:/action?param1=val1&param2=val2</p>
</blockquote>
<p>I've also tried updating the custom scheme url to an intent url but to no avail. Googling about this issue doesn't readily provide a clear solution, so I'm hoping anyone on can help me out.
<hr>
<strong>Edit:</strong> Tried to reproduce the issue with the following scenario (as close as possible to the real life scenario):</p>
<ul>
<li>IABT displays a page with a single button</li>
<li>Clicking the button fires an jsonp call to a mock endpoint</li>
<li>The JSONP callback is executed and fires off a custom event</li>
<li>An event handler for the custom event is triggered and redirects the browser to another mock endpoint</li>
<li>That mock endpoint responds with a 302 to the custom deeplink scheme.</li>
</ul>
<p>Alas, this seems to be working. I would have expected that the inclusion of the jsonp call would cause Chrome to block the final redirect as it would not be able to identify it as a user initiated action.</p>
<p><hr>
<strong>Edit 2:</strong> Managed to get a reproducible scenario. We've set up a dummy endpoint, that upon request simply returns a <code>302</code> with the custom scheme in the Location header. This is blocked on all tries, except for the first one. That fact still boggles the mind. We're using the <a href="https://github.com/openid/AppAuth-Android" rel="noreferrer">AppAuth for Android</a> application to test the setup.</p>
<p>I'm opening a custom tab to the endpoint as shown below. The code is taken from <a href="https://stackoverflow.com/questions/36084681/chrome-custom-tabs-redirect-to-android-app-will-close-the-app">this answer</a>.</p>
<pre class="lang-java prettyprint-override"><code>void launchTab(Context context, Uri uri){
final CustomTabsServiceConnection connection = new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient client) {
final CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
final CustomTabsIntent intent = builder.build();
client.warmup(0L); // This prevents backgrounding after redirection
intent.launchUrl(context, uri);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
CustomTabsClient.bindCustomTabsService(context, "com.android.chrome", connection);
}
</code></pre> | 58,145,987 | 2 | 1 | null | 2017-10-13 10:30:55.8 UTC | 2 | 2020-11-02 15:59:03.44 UTC | 2018-03-13 08:32:47.177 UTC | null | 466,761 | null | 466,761 | null | 1 | 37 | javascript|android|google-chrome|redirect|appauth | 7,138 | <p>We ended up implementing our login and registration forms with a <a href="https://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow noreferrer">classic post-redirect-get</a> pattern.</p>
<p>The server responds with a <code>302</code> to the custom URI scheme. Because in this setup there's no asynchronous execution between the user submitting the form and the browser receiving a redirect, Chrome correctly identifies the chain of actions as trusted and thus will not block the navigation.</p>
<p>I realise this might not be the preferred solution for everyone. A possible alternative to support asynchronous execution flows is the use of <a href="https://developer.apple.com/ios/universal-links/" rel="nofollow noreferrer">universal links</a> as these use regular http(s) schemes, to which redirects were (at the time of posting my question) not considered harmful by Chrome.</p> |
32,233,489 | Does bootstrap have builtin padding and margin classes? | <p>Does Bootstrap have built-in padding and margin classes like <code>pad-10</code>, <code>mar-left-10</code> or I have to add my own custom classes? For example, similar to the ones <a href="http://seantheme.com/color-admin-v1.8/admin/html/helper_css.html" rel="noreferrer">here</a> at padding and margin tabs.</p> | 43,359,968 | 11 | 3 | null | 2015-08-26 17:56:47.997 UTC | 19 | 2022-08-03 09:03:36.577 UTC | 2018-02-09 17:10:38.34 UTC | null | 2,074,605 | null | 1,430,517 | null | 1 | 79 | css|twitter-bootstrap|margin|padding | 261,733 | <p>There are built in classes, namely:</p>
<pre><code>.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }
.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }
.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }
.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }
.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }
.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }
.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }
.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }
.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }
.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }
.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }
.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }
.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }
.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }
</code></pre> |
25,070,176 | Hyperlink changes from # to %20-%20 when clicked in Excel | <p>I've got a hyperlink in an Excel 2013 sheet that links to an internal website. When I right click and select "edit hyperlink", I see this in the address bar (which is correct):</p>
<p><code>https://myserver.company.com/home/default.html#article?id=1203291003</code></p>
<p>However, when I left click, middle click, or right click -> open hyperlink I get the same behavior: IE11 opens and I get a http 404 error because the link (shown below) is not found.</p>
<p><code>https://myserver.company.com/home/default.html%20-%20article?id=1203291003</code></p>
<p>What could be converting the <code>#</code> to <code>%20-%20</code>? This is very odd because <code>%20</code> is a space and there are no spaces in the URL.</p> | 25,070,314 | 15 | 3 | null | 2014-07-31 22:47:30.307 UTC | 3 | 2019-08-06 14:41:03.283 UTC | 2016-08-23 19:33:50.733 UTC | null | 2,370,483 | null | 1,330,428 | null | 1 | 39 | excel | 86,111 | <p>This is a <a href="http://support.microsoft.com/kb/202261" rel="noreferrer">known issue</a> with MS Excel. Basically, the hash/pound (<em><code>#</code></em>) sign is a valid character to use in a file name but is <strong>not accepted in hyperlinks in Office documents</strong>. The conversion to <code>%20-%20</code> appears to be by design.</p>
<p>However, take a look at this question, highlighting the same issue but with Excel 2010:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/17656083/excel-hyperlink-to-web-page-location-with-id-or-named-anchor">Excel hyperlink to web page location with id or named anchor</a></li>
</ul>
<p>which seems to imply it might be a browser issue with IE. If you can set another browser as your default, even temporarily for testing, it might work.</p> |
31,610,869 | Null Conditional Operators | <p>C# 6.0 has just been released and has a new nice little feature that I'd really like to use in JavaScript. They're called <a href="https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#null-conditional-operators">Null-conditional operators</a>. These use a <code>?.</code> or <code>?[]</code> syntax.</p>
<p>What these do is essentially allow you to check that the object you've got isn't <code>null</code>, before trying to access a property. If the object is <code>null</code>, then you'll get <code>null</code> as the result of your property access instead.</p>
<pre><code>int? length = customers?.Length;
</code></pre>
<p>So here <code>int</code> can be null, and will take that value if <code>customers</code> is null. What is even better is that you can chain these:</p>
<pre><code>int? length = customers?.orders?.Length;
</code></pre>
<p>I don't believe we can do this in JavaScript, but I'm wondering what's the neatest way of doing something similar. Generally I find chaining <code>if</code> blocks difficult to read:</p>
<pre><code>var length = null;
if(customers && customers.orders) {
length = customers.orders.length;
}
</code></pre> | 47,538,150 | 4 | 11 | null | 2015-07-24 12:44:46.53 UTC | 6 | 2021-11-17 03:37:36.94 UTC | 2017-11-28 18:38:56.55 UTC | null | 1,159,478 | null | 21,061 | null | 1 | 70 | javascript | 22,841 | <p>Called "<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="nofollow noreferrer">optional chaining</a>", it's currently a <a href="https://github.com/tc39/proposal-optional-chaining" rel="nofollow noreferrer" title="TC39 proposal in Stage 3">TC39 proposal in Stage 4</a>. A <a href="https://github.com/babel/babel/releases/tag/v7.0.0-alpha.15" rel="nofollow noreferrer" title="Babel plugin">Babel plugin</a> however is already available in v7.</p>
<p>Example usage:</p>
<pre><code>const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
</code></pre> |
39,049,188 | How to add Strings on X Axis in iOS-charts? | <p>With the new release i had some troubles to create some graphs the previous code was:</p>
<pre><code>func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")
let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
barChartView.data = chartData
}
</code></pre>
<p>You can pass the values for example an array of months using the line:</p>
<pre><code>let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
</code></pre>
<p>After the new release the code to implement the same graph is:</p>
<pre><code>func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i+2), y:values[i], data: months )
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
}
</code></pre>
<p>I was trying a few hours but i couldn't find a way to modify the X axis values, i hope someone can help me, thanks!!</p> | 39,149,070 | 6 | 4 | null | 2016-08-20 00:00:09.303 UTC | 18 | 2020-02-26 09:26:12.153 UTC | 2016-12-13 12:17:35.353 UTC | null | 5,426,687 | null | 6,736,783 | null | 1 | 28 | ios|swift|ios-charts | 30,855 | <p>I found the solution, maybe another one can solve this problem in a better way, without create a new class, well this is what I found:</p>
<p>First you nedd to create a new class, which will be your formatter class and add the IAxisValueFormater interface, then you use the method stringForValue to customize the new values, it takes two parameters, the first is the actual value (you can see it like the index) and second is the axis where the value is.</p>
<pre><code>import UIKit
import Foundation
import Charts
@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
public func stringForValue(value: Double, axis: AxisBase?) -> String
{
return months[Int(value)]
}
}
</code></pre>
<p>Now in your file at the begining of your setChart() function you have to create two variables one for your formatter class and one for the axis class:</p>
<pre><code>let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()
</code></pre>
<p>Next, go ahead at the end of the for in loop and pass the index and axis to your formatter variable:</p>
<pre><code>formato.stringForValue(Double(i), axis: xaxis)
</code></pre>
<p>After looping add the format to your axis variable:</p>
<pre><code>xaxis.valueFormatter = formato
</code></pre>
<p>The final step is to add the new xaxisformatted to the barChartView:</p>
<pre><code>barChartView.xAxis.valueFormatter = xaxis.valueFormatter
</code></pre>
<p>And that's all the other lines in the setChart() function just keep it where they are, I hope it can help you.</p> |
7,367,449 | Google API : How to authenticate without redirection? | <p>We want to use Google Doc API to generate Document (In our own business account) when our end users do some actions on our site.</p>
<p>The problem is that we've tried to implement the OAuth 2.0 protocol, as suggested in the v3.0 protocol documentation. The apiClient::authentication method do a redirection. This is a major problem because our users doesn't know the access to our own business account.... and we don't want to give them access anyway ;)</p>
<p>(In other word, we're not creating an application that allow our users to edit their own data, but to interact with our data, like a database.)</p>
<p>I've read that the point of OAuth 2.0 was to avoid that we manage the credential of our users. I'm personally O.K. with the concept, but in our case, we don't want to get authenticated in the google account of our users ...</p>
<p>So, what would be the best approach to get a valid authentication without any interaction from the end user ?</p> | 7,477,112 | 3 | 2 | null | 2011-09-09 21:09:01.93 UTC | 9 | 2018-12-14 14:52:10.44 UTC | 2013-12-29 02:12:07.063 UTC | null | 881,229 | null | 613,365 | null | 1 | 14 | oauth|oauth-2.0|google-docs-api | 26,109 | <p>What you describe is not how 3-legged OAuth was designed to be used.</p>
<p>3-legged OAuth is all about <em>delegated</em> authentication where a user (who knows his password) can grant limited and revokable resource access to application. That application never sees the user's password. There is a bunch of work involved to safely allow the application to impersonate the user.</p>
<p>What you probably want is to use the (2-legged) OAuth flow, where the consumer_id/consumer_secret credentials are embedded in your application. Here your application is not impersonating your end user and there would be no browser redirection involved.</p>
<p>Here's some further info on using 2-legged OAuth in Google Apps:
<a href="http://googleappsdeveloper.blogspot.com/2011/07/using-2-legged-oauth-with-google-tasks.html" rel="noreferrer">http://googleappsdeveloper.blogspot.com/2011/07/using-2-legged-oauth-with-google-tasks.html</a></p>
<p>And this is a good description of 3- vs 2- legged OAuth:
<a href="http://cakebaker.42dh.com/2011/01/10/2-legged-vs-3-legged-oauth/" rel="noreferrer">http://cakebaker.42dh.com/2011/01/10/2-legged-vs-3-legged-oauth/</a></p> |
7,374,562 | How do I add a .click() event to an image? | <p>I have a script that places an image based on a mouse click thanks to <a href="https://stackoverflow.com/users/701879/jose-faeti">Jose Faeti</a>. Now I need help adding a .click() event to the code below so that when a user clicks the image it performs the function shown in the script.</p>
<pre><code><img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
</code></pre>
<p>I put the entire code below, in case you want to see it.</p>
<pre><code><html>
<head>
<script language="javascript" type="text/javascript">
<!--
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
// -->
</script>
</head>
<body>
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
</body>
</html>
</code></pre>
<p>Help?</p> | 7,374,620 | 4 | 1 | null | 2011-09-10 20:39:41.943 UTC | 6 | 2022-03-24 17:08:45.353 UTC | 2017-05-23 12:34:29.25 UTC | null | -1 | null | 766,789 | null | 1 | 30 | javascript|events|mouseevent | 252,551 | <p>First of all, this line</p>
<pre><code><img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
</code></pre>
<p>You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the <code>.click()</code> there.</p>
<p>If you read the JavaScript you've got there, <code>document.getElementById('foo')</code> it's looking for an HTML element with an ID of <code>foo</code>. You don't have one. Give your image that ID:</p>
<pre><code><img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</code></pre>
<p>Alternatively, you could throw the JS in a function and put an onclick in your HTML:</p>
<pre><code><img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
</code></pre>
<p>I suggest you do some reading up on JavaScript and HTML though.</p>
<hr>
<p>The others are right about needing to move the <code><img></code> above the JS click binding too.</p> |
7,459,818 | How to get the position of a key within an array | <p>Ok, so I need to grab the position of 'blah' within this array (position will not always be the same). For example:</p>
<pre><code>$array = (
'a' => $some_content,
'b' => $more_content,
'c' => array($content),
'blah' => array($stuff),
'd' => $info,
'e' => $more_info,
);
</code></pre>
<p>So, I would like to be able to return the number of where the 'blah' key is located at within the array. In this scenario, it should return 3. How can I do this quickly? And without affecting the $array array at all.</p> | 7,459,823 | 4 | 0 | null | 2011-09-18 06:15:03.707 UTC | 6 | 2011-09-18 07:40:00.447 UTC | null | null | null | null | 304,853 | null | 1 | 43 | php|arrays|array-key | 62,818 | <pre><code>$i = array_search('blah', array_keys($array));
</code></pre> |
24,108,014 | ASP.NET MVC 5 Form Validation | <p>I am new to ASP.NET MVC and using version 5. I created a form that is in the layout, and I cannot cannot get it to show validation errors on the view. It will post to the action correctly, and if the model is valid, it will execute. If the model is invalid I will get the following error. </p>
<p>I am hoping someone can point me in the right direction. Thank you in advance!</p>
<pre><code>Server Error in '/' Application.
The view 'ContactSubmit' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/ContactSubmit.aspx
~/Views/Home/ContactSubmit.ascx
~/Views/Shared/ContactSubmit.aspx
~/Views/Shared/ContactSubmit.ascx
~/Views/Home/ContactSubmit.cshtml
~/Views/Home/ContactSubmit.vbhtml
~/Views/Shared/ContactSubmit.cshtml
~/Views/Shared/ContactSubmit.vbhtml
</code></pre>
<p>This is my model I am using:</p>
<pre><code>public partial class Lead
{
[Key]
public int LeadId { get; set; }
[Required]
[StringLength(50, MinimumLength=2, ErrorMessage="* A valid first name is required.")]
[Display(Name="First Name")]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength=2, ErrorMessage="* A valid last name is required.")]
[Display(Name="Last Name")]
public string LastName { get; set; }
[Required]
[StringLength(50, MinimumLength=2, ErrorMessage="* A valid company is required.")]
public string Company { get; set; }
[Required]
[StringLength(50)]
[EmailAddress(ErrorMessage="* A valid email address is required.")]
public string Email { get; set; }
[Required]
[StringLength(15, MinimumLength=9, ErrorMessage="* A valid phone nunber is required.")]
[Phone(ErrorMessage="Please enter a valid phone number.")]
public string Phone { get; set; }
}
</code></pre>
<p>This is the code I have in my Home controller:</p>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ContactSubmit(
[Bind(Include = "FirstName, LastName, Company, Email, Phone")]
Lead lead)
{
try
{
if (ModelState.IsValid)
{
lead.Tenant = SessionManager.Get<Tenant>(Constants.SessionTenant);
lead.Refferer = SessionManager.Get<string>(Constants.SessionRefferal);
DataStoreManager.AddLead(lead);
return RedirectToAction("SubmissionConfirmed", lead);
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError("", "Unable to perform action. Please contact us.");
return RedirectToAction("SubmissionFailed", lead);
}
return View(lead);
}
[HttpGet]
public ActionResult ContactSubmit()
{
return View();
}
</code></pre>
<p>This is the form that I have in my layout:</p>
<pre><code> @using (Html.BeginForm("ContactSubmit", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<fieldset>
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.FirstName)
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.LastName)
@Html.ValidationMessageFor(m => m.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Company)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.Company)
@Html.ValidationMessageFor(m => m.Company)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Phone)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.Phone)
@Html.ValidationMessageFor(m => m.Phone)
</div>
<div class="masthead-button-wrapper">
<input class="btn btn-warning" type="submit" value="Submit" />
</div>
</fieldset>
}
</code></pre> | 24,108,304 | 1 | 1 | null | 2014-06-08 16:02:35.933 UTC | 2 | 2014-06-08 17:31:57.093 UTC | null | null | null | null | 53,388 | null | 1 | 8 | c#|asp.net|asp.net-mvc|validation|asp.net-mvc-5 | 44,546 | <p>There is one error in your code, I didn't notice first. In the get method you are using - </p>
<pre><code>return View();
</code></pre>
<p>Which means your view does not allow parameter but when there is an error you are using - </p>
<pre><code>return View(lead);
</code></pre>
<p>In this case MVC is looking for the view with the same name but which also accepts a parameter of <code>Lead</code> type and it fails since there is no view with that option and the only one that is found does not accept parameter as seen from the Get method. When there is no error, you are redirecting to - </p>
<pre><code>return RedirectToAction("SubmissionConfirmed", lead);
</code></pre>
<p>and the View with the parameter is never needed to be searched and thus no error.</p>
<p>So, change the view to accept a parameter of <code>Lead</code> and change your get method accordingly.</p>
<p>May be this would help. - </p>
<pre><code>[HttpGet]
public ActionResult ContactSubmit()
{
var lead = new Lead();
return View(lead);
}
</code></pre>
<p>and in the view add </p>
<pre><code>@model Lead
</code></pre>
<p>at the top</p>
<p><strong>EDIT</strong> : In case since you are redirecting you should know that ModelState gets initialized in each request, so redirecting clears it automatically. You have to use some other means to pass modelstate or better if you use client side validation. </p> |
2,256,012 | Unit testing paperclip uploads with Rspec (Rails) | <p>Total Rspec noob here. Writing my first tests tonight. </p>
<p>I've got a model called Image. Using paperclip I attach a file called photo. Standard stuff. I've run the paperclip generator and everything works fine in production and test modes. </p>
<p>Now I have a spec file called image.rb and it looks like this (it was created by ryanb's nifty_scaffold generator):</p>
<pre><code>require File.dirname(__FILE__) + '/../spec_helper'
describe Image do
it "should be valid" do
Image.new.should be_valid
end
end
</code></pre>
<p>This test fails and I realise that it's because of my model validations (i.e. validates_attachment_presence)</p>
<p>The error that I get is:</p>
<pre><code>Errors: Photo file name must be set., Photo file size file size must be between 0 and 1048576 bytes., Photo content type is not included in the list
</code></pre>
<p>So how do I tell rspec to upload a photo when it runs my test?</p>
<p>I'm guessing that it's got somethign to do with fixtures.... maybe not though. I've tried playing around with them but not having any luck. For the record, I've created a folder called images inside my fixtures folder and the two files I want to use in my tests are called rails.png and grid.png)</p>
<p>I've tried doing the following:</p>
<pre><code>it "should be valid" do
image = Image.new :photo => fixture_file_upload('images/rails.png', 'image/png').should be_valid
# I've also tried adding stuff like this
#image.stub!(:has_attached_file).with(:photo).and_return( true )
#image.stub!(:save_attached_files).and_return true
#image.save.should be_true
end
</code></pre>
<p>But rspec complains about "fixture_file_upload" not being recognised... I am planning to get that Rspec book. And I've trawled around the net for an answer but can't seem to find anything. My test database DOES get populated with some data when I remove the validations from my model so I know that some of it works ok.</p>
<p>Thanks in advance,</p>
<p>EDIT:</p>
<p>images.yml looks like this:</p>
<pre><code>one:
name: MyString
description: MyString
two:
name: MyString
description: MyString
</code></pre> | 2,257,948 | 4 | 0 | null | 2010-02-13 00:35:54.433 UTC | 12 | 2014-07-25 16:33:05.283 UTC | null | null | null | null | 227,863 | null | 1 | 24 | ruby-on-rails|unit-testing|rspec|paperclip | 26,891 | <p>This should work with Rails 2.X:</p>
<pre><code>Image.new :photo => File.new(RAILS_ROOT + '/spec/fixtures/images/rails.png')
</code></pre>
<p>As of Rails 3, <code>RAILS_ROOT</code> is no longer used, instead you should use <code>Rails.root</code>.</p>
<p>This should work with Rails 3:</p>
<pre><code>Image.new :photo => File.new(Rails.root + 'spec/fixtures/images/rails.png')
</code></pre>
<p>Definitely get the RSpec book, it's fantastic.</p> |
1,953,239 | Search an Oracle database for tables with specific column names? | <p>We have a large Oracle database with many tables. Is there a way I can query or search to find if there are any tables with certain column names?</p>
<p>IE show me all tables that have the columns: <code>id, fname, lname, address</code></p>
<p>Detail I forgot to add: I need to be able to search through different schemas. The one I must use to connect doesn't own the tables I need to search through.</p> | 1,953,311 | 4 | 0 | null | 2009-12-23 14:54:43.077 UTC | 48 | 2016-03-15 07:52:29.05 UTC | 2015-09-11 20:27:29.22 UTC | null | 332,936 | null | 168,646 | null | 1 | 122 | sql|oracle | 328,726 | <p>To find all tables with a particular column:</p>
<pre><code>select owner, table_name from all_tab_columns where column_name = 'ID';
</code></pre>
<p>To find tables that have any or all of the 4 columns:</p>
<pre><code>select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');
</code></pre>
<p>To find tables that have all 4 columns (with none missing):</p>
<pre><code>select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;
</code></pre> |
43,022,843 | Nvidia NVML Driver/library version mismatch | <p>When I run <code>nvidia-smi</code>, I get the following message:</p>
<blockquote>
<p>Failed to initialize NVML: Driver/library version mismatch</p>
</blockquote>
<p>An hour ago I received the same message and uninstalled my CUDA library and I was able to run <code>nvidia-smi</code>, getting the following result:</p>
<p><a href="https://i.stack.imgur.com/RyAeQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RyAeQ.png" alt="nvidia-smi-result" /></a></p>
<p>After this I downloaded <code>cuda-repo-ubuntu1604-8-0-local-ga2_8.0.61-1_amd64.deb</code> from <a href="https://developer.nvidia.com/cuda-downloads" rel="noreferrer">the official NVIDIA page</a> and then simply:</p>
<pre class="lang-none prettyprint-override"><code>sudo dpkg -i cuda-repo-ubuntu1604-8-0-local-ga2_8.0.61-1_amd64.deb
sudo apt-get update
sudo apt-get install cuda
export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}
</code></pre>
<p>Now I have CUDA installed, but I get the mentioned mismatch error.</p>
<hr />
<p>Some potentially useful information:</p>
<p>Running <code>cat /proc/driver/nvidia/version</code> I get:</p>
<pre class="lang-none prettyprint-override"><code>NVRM version: NVIDIA UNIX x86_64 Kernel Module 378.13 Tue Feb 7 20:10:06 PST 2017
GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
</code></pre>
<p>I'm running Ubuntu 16.04.2 LTS (Xenial Xerus).</p>
<p>The kernel release is 4.4.0-66-generic.</p> | 43,023,000 | 19 | 6 | null | 2017-03-25 22:47:00.43 UTC | 113 | 2022-04-23 01:03:47.083 UTC | 2022-04-22 23:50:42.163 UTC | null | 63,550 | null | 4,189,580 | null | 1 | 468 | cuda|driver|gpu|nvidia | 522,150 | <p>Surprise surprise, rebooting solved the issue (I thought I had already tried that).</p>
<p>The solution <a href="https://stackoverflow.com/questions/43022843/nvidia-nvml-driver-library-version-mismatch#comment73133147_43022843">Robert Crovella mentioned</a> in the comments may also be useful to someone else, since it's pretty similar to what I did to solve the issue the first time I had it.</p> |
42,769,106 | Can I turn off the Node.js server process associated with Visual Studio 2017? | <p>I'm working on an ASP.NET application in Visual Studio 2017, and I'm noticing a <em>"Node.js: Server-side JavaScript"</em> process running at 1.3 GB to 1.8 GB of memory. My <a href="https://en.wikipedia.org/wiki/Internet_Information_Services" rel="nofollow noreferrer">IIS</a> worker process is the normal size it is in Visual Studio 2015.</p>
<p>My application doesn't include any Node.js libraries. I'm not able to figure out how to turn this Node.js: Server-side JavaScript process off. It's eating up too much memory for something I have no use for.</p>
<p>Is there a way to kill this apart from uninstalling Visual Studio 2017 and switching back to Visual Studio 2015?</p>
<p><a href="https://i.stack.imgur.com/bUumc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bUumc.png" alt="Enter image description here" /></a></p>
<p>Killing the main process in Task Manager doesn't affect anything in Visual Studio. However, if I go to the <em>Details</em> tab and kill the individual running processes, it crashes Visual Studio. I took a video of what happened after I killed the process and ran my local web page (sorry for the quality; Stack Overflow limited image size to 2 MB):</p>
<p><a href="https://i.stack.imgur.com/wLWx7.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wLWx7.gif" alt="Enter image description here" /></a></p> | 42,972,043 | 9 | 15 | null | 2017-03-13 16:49:17.283 UTC | 41 | 2022-09-16 11:40:50.92 UTC | 2022-09-16 11:10:20.423 UTC | null | 63,550 | null | 324,516 | null | 1 | 142 | node.js|asp.net-mvc|visual-studio-2017 | 35,511 | <p>In menu <em>Tools</em> → <em>Options</em> → <em>Text Editor</em> → <em>JavaScript/TypeScript</em> → <em>Language Service...</em>:</p>
<p>Uncheck 'Enable the new JavaScript language service'.</p>
<p>Restart Visual Studio</p>
<p>This appears to prevent the Node.js process from starting.</p> |
10,290,156 | awaiting on an observable | <p>So in the sad days of C# 4.0, I created the following "WorkflowExecutor" class that allowed asynchronous workflows in the GUI thread by hacking into IEnumerable's "yield return" continuations to wait for observables. So the following code would, at button1Click, just start a simple workflow that updates the text, waits for you to click button2, and loops after 1 second.</p>
<pre><code>public sealed partial class Form1 : Form {
readonly Subject<Unit> _button2Subject = new Subject<Unit>();
readonly WorkflowExecutor _workflowExecutor = new WorkflowExecutor();
public Form1() {
InitializeComponent();
}
IEnumerable<IObservable<Unit>> CreateAsyncHandler() {
Text = "Initializing";
var scheduler = new ControlScheduler(this);
while (true) {
yield return scheduler.WaitTimer(1000);
Text = "Waiting for Click";
yield return _button2Subject;
Text = "Click Detected!";
yield return scheduler.WaitTimer(1000);
Text = "Restarting";
}
}
void button1_Click(object sender, EventArgs e) {
_workflowExecutor.Run(CreateAsyncHandler());
}
void button2_Click(object sender, EventArgs e) {
_button2Subject.OnNext(Unit.Default);
}
void button3_Click(object sender, EventArgs e) {
_workflowExecutor.Stop();
}
}
public static class TimerHelper {
public static IObservable<Unit> WaitTimer(this IScheduler scheduler, double ms) {
return Observable.Timer(TimeSpan.FromMilliseconds(ms), scheduler).Select(_ => Unit.Default);
}
}
public sealed class WorkflowExecutor {
IEnumerator<IObservable<Unit>> _observables;
IDisposable _subscription;
public void Run(IEnumerable<IObservable<Unit>> actions) {
_observables = (actions ?? new IObservable<Unit>[0]).GetEnumerator();
Continue();
}
void Continue() {
if (_subscription != null) {
_subscription.Dispose();
}
if (_observables.MoveNext()) {
_subscription = _observables.Current.Subscribe(_ => Continue());
}
}
public void Stop() {
Run(null);
}
}
</code></pre>
<p>The smart part of the idea, using "yield" continuations to do the asynchronous work, was taken from Daniel Earwicker's AsyncIOPipe idea: <a href="http://smellegantcode.wordpress.com/2008/12/05/asynchronous-sockets-with-yield-return-of-lambdas/" rel="noreferrer">http://smellegantcode.wordpress.com/2008/12/05/asynchronous-sockets-with-yield-return-of-lambdas/</a>, then I added the reactive framework on top of it.</p>
<p>Now I'm having trouble rewriting this using the async feature in C# 5.0, but it seems like it should be straightforward thing to do. When I convert the observables to tasks, they only run once and the while loop crashes the 2nd time around. Any help fixing that would be great.</p>
<p>All that said/asked, what does the async/await mechanism give me that the WorkflowExecutor doesn't? Is there anything I can do with async/await that I can't just do (given a similar amount of code) with the WorkflowExecutor?</p> | 10,290,943 | 2 | 2 | null | 2012-04-24 00:24:53.883 UTC | 16 | 2012-05-24 17:08:21.807 UTC | 2012-04-24 00:49:16.297 UTC | null | 171,121 | null | 171,121 | null | 1 | 26 | c#|system.reactive|async-await|.net-4.5|c#-5.0 | 19,652 | <p>As you noticed, Task is very much a one-time use thing, as opposed to Observable's "stream of events". A good way of thinking of this (IMHO) is the 2x2 chart on the <a href="http://blogs.msdn.com/b/rxteam/archive/2012/03/12/reactive-extensions-v2-0-beta-available-now.aspx" rel="noreferrer">Rx team's post about 2.0 Beta</a>:</p>
<p><img src="https://i.stack.imgur.com/y9Nah.png" alt="2x2 chart for task vs observable"></p>
<p>Depending on circumstance (one-time vs. 'stream' of events), keeping Observable might make more sense.</p>
<p>If you can hop up to the Reactive 2.0 Beta, then you can 'await' observables with that. For instance, my own attempt at an 'async/await' (approximate) version of your code would be:</p>
<pre><code>public sealed partial class Form1 : Form
{
readonly Subject<Unit> _button2Subject = new Subject<Unit>();
private bool shouldRun = false;
public Form1()
{
InitializeComponent();
}
async Task CreateAsyncHandler()
{
Text = "Initializing";
while (shouldRun)
{
await Task.Delay(1000);
Text = "Waiting for Click";
await _button2Subject.FirstAsync();
Text = "Click Detected!";
await Task.Delay(1000);
Text = "Restarting";
}
}
async void button1_Click(object sender, EventArgs e)
{
shouldRun = true;
await CreateAsyncHandler();
}
void button2_Click(object sender, EventArgs e)
{
_button2Subject.OnNext(Unit.Default);
}
void button3_Click(object sender, EventArgs e)
{
shouldRun = false;
}
}
</code></pre> |
10,431,579 | Permanently configuring LLDB (in Xcode 4.3.2) not to stop on signals | <p>I'm trying to get LLDB (running in Xcode 4.3.2 with an OS X application) to not stop on certain signals. If I enter</p>
<p><code>process handle SIGUSR2 -n true -p true -s false</code></p>
<p>on the debugging console it works fine and LLDB no longer stops on SIGUSR2.</p>
<p>However, if I put</p>
<p><code>command process handle SIGUSR2 -n true -p true -s false</code></p>
<p>into ~/.lldbinit it seems to be ignored. Other commands in this file (e.g. alias) work fine.</p>
<p>How can I make LLDB never stop on certain signals?</p> | 10,456,557 | 1 | 2 | null | 2012-05-03 12:40:19.013 UTC | 24 | 2020-09-22 11:09:05.89 UTC | 2020-09-22 11:09:05.89 UTC | null | 1,498,329 | null | 407,713 | null | 1 | 44 | xcode|macos|signals|lldb | 12,543 | <p>In case anyone else ever has this question, I finally solved it by adding a breakpoint in <code>NSApplicationMain()</code> (for plain C programs, <code>main()</code> would of course work as well). </p>
<p>I set the breakpoint action to <code>process handle SIGUSR2 -n true -p true -s false</code>, and enabled the "Automatically continue after evaluating" option. </p>
<p><img src="https://i.stack.imgur.com/r34PZ.png" alt="Xcode 4 Breakpoint Screenshot"></p>
<p>If anyone has a more elegant solution, I'd be happy to hear.</p> |
7,057,450 | Why does python use unconventional triple-quotation marks for comments? | <p>Why didn't python just use the traditional style of comments like C/C++/Java uses:</p>
<pre><code>/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
</code></pre>
<p>Is there a specific reason for this or is it just arbitrary?</p> | 7,057,488 | 5 | 6 | null | 2011-08-14 14:44:02.973 UTC | 18 | 2019-10-04 20:57:17.177 UTC | 2017-11-22 00:24:10.827 UTC | null | 475,229 | null | 814,849 | null | 1 | 39 | python|coding-style|comments | 64,937 | <p>Python doesn't use triple quotation marks for comments. Comments use the hash (a.k.a. pound) character:</p>
<pre><code># this is a comment
</code></pre>
<p>The triple quote thing is a <a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">doc string</a>, and, unlike a comment, is actually available as a real string to the program:</p>
<pre class="lang-none prettyprint-override"><code>>>> def bla():
... """Print the answer"""
... print 42
...
>>> bla.__doc__
'Print the answer'
>>> help(bla)
Help on function bla in module __main__:
bla()
Print the answer
</code></pre>
<p>It's not strictly required to use triple quotes, as long as it's a string. Using <code>"""</code> is just a convention (and has the advantage of being multiline).</p> |
13,866,850 | SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format | <p>I have a SQL Server table that has a "Time" column. The table is a log table the houses status messages and timestamps for each message. The log table is inserted into via a batch file. There is an ID column that groups rows together. Each time the batch file runs it initializes the ID and writes records. What I need to do is get the elapsed time from the first record in an ID set to the last record of the same ID set. I started toying with select Max(Time) - Min(Time) from logTable where id = but couldn't figure out how to format it correctly. I need it in HH:MM:SS.</p> | 13,867,489 | 8 | 1 | null | 2012-12-13 19:18:52.033 UTC | 1 | 2017-11-17 09:18:38.603 UTC | null | null | null | null | 368,259 | null | 1 | 18 | sql-server-2008|datetime|elapsedtime | 124,316 | <p>SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine <em>as long as your interval is less than 24 hours</em>. But CONVERT() isn't a good solution for this. </p>
<pre><code>create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
</code></pre>
<p>Values were chosen in such a way that for </p>
<ul>
<li>id = 1, elapsed time is 1 hour</li>
<li>id = 2, elapsed time is 2 hours, and</li>
<li>id = 3, elapsed time is 3 hours.</li>
</ul>
<p>This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.</p>
<pre><code>select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
</code></pre>
<p>Note the misleading "03:00:00" for the 27-hour difference on id number 3.</p>
<p><a href="https://stackoverflow.com/a/11191244/562459">Function to format elapsed time in SQL Server</a> </p> |
13,858,665 | Disable DPI awareness for WPF application | <p>Good day!</p>
<p>I've been working on a WPF app for some time now (as a learning experience and oh boy it was a learning experience) and it's finally ready for release. Release means installing it on my HTPC where it will be used to browse my movie collection.</p>
<p>I designed it on my PC which runs 1920*1080 but at the normal DPI setting, while the HTPC/TV is running at the same resolution but a higher DPI setting for obvious reasons.</p>
<p>The problem is my app goes bonkers on the HTPC, messing up pretty much everything as far as visuals go. I know this is due to bad design (mea culpa), but since it's an application that will only be used by me I'm looking for an quick fix, not a full redesign. I read it would be possible to stop the app from being DPI aware by adding the following to AssemblyInfo.cs:</p>
<pre><code>[assembly: System.Windows.Media.DisableDpiAwareness]
</code></pre>
<p>However, it doesn't seem to have any effect and the behavior of the app remains the same.</p>
<p>Could anyone point me in the right direction?</p>
<p>Thank you,
Johan</p> | 13,858,985 | 9 | 0 | null | 2012-12-13 11:15:09.58 UTC | 12 | 2022-02-09 13:44:06.94 UTC | 2012-12-15 14:39:42.073 UTC | null | 106,224 | null | 1,173,937 | null | 1 | 29 | wpf|scaling|dpi | 34,856 | <h2>DPIAwareness</h2>
<p>Just some ideas (not tried):</p>
<p>Are you running on XP? That option might not work on that platform.</p>
<ul>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/5e60a54d-baf5-46e3-9eac-a959f2a0fba1/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/5e60a54d-baf5-46e3-9eac-a959f2a0fba1/</a></li>
</ul>
<p>What follows are probably just different ways to set the same DpiAwareness option:</p>
<ul>
<li><p>look at the "compatibility mode" settings on your EXE...right click it's properties...and turn on "Disable display scaling"</p>
<p><img src="https://i.stack.imgur.com/67ZLH.png" alt=""></p></li>
<li><p>create a manifest, and say you aren't aware</p>
<pre><code><assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" >
...
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>false</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
...
</assembly>
</code></pre></li>
<li><p>call <code>SetProcessDPIAware</code> (think you have to call this early i.e. before Window is created)<br/><br/><a href="http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633543%28v=vs.85%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633543(v=vs.85).aspx</a></p></li>
</ul>
<p>You can call <code>IsProcessDPIAware</code> to check if your apps process has had the setting applied to it or not.</p>
<h2>Finding out the DPI</h2>
<p>Here's how you find out what DPI you are currently using:</p>
<p>Access <code>CompositionTarget</code> via the <code>PresentationSource</code> of your <code>Window</code> to find out what DPI scaling it's using.....you can then use the values to do some scaling adjustments i.e. scale down your "stuff" (whose sizes/length/etc are specified in Device Independent Units), so that when its scaled up due to a higher DPI being in effect it doesn't explode the physical pixel usage (...this can be done in various ways e.g. <code>ViewBox</code>, or calculations on widths, etc on elements ).</p>
<pre><code>double dpiX, double dpiY;
PresentationSource presentationsource = PresentationSource.FromVisual(mywindow);
if (presentationsource != null) // make sure it's connected
{
dpiX = 96.0 * presentationsource.CompositionTarget.TransformToDevice.M11;
dpiY = 96.0 * presentationsource.CompositionTarget.TransformToDevice.M22;
}
</code></pre>
<ul>
<li><a href="https://stackoverflow.com/questions/3286175/how-do-i-convert-a-wpf-size-to-physical-pixels">How do I convert a WPF size to physical pixels?</a></li>
<li><a href="http://wpftutorial.net/DrawOnPhysicalDevicePixels.html" rel="noreferrer">http://wpftutorial.net/DrawOnPhysicalDevicePixels.html</a></li>
</ul>
<h2>Do Scaling Adjustments</h2>
<ul>
<li><p>use the <code>ViewBox</code> trick<br><br>See this answer I made before that allowed a <code>Canvas</code> to use positions that were interpreted as "native" pixel no matter what the DPI scaling.<br><br> <a href="https://stackoverflow.com/questions/12412092/wpf-for-lcd-screen-full-hd">WPF for LCD screen Full HD</a></p></li>
<li><p>access the <code>TransFormToDevice</code> scaling matrix on the <code>CompositionTarget</code>, and from that calculate a new matrix that just undoes that scaling and use that in <code>LayoutTransform</code> or <code>RenderTransform</code>.</p></li>
<li><p>use a method (maybe even put it in a Converter) that modifies a DIP (Device Independent Position) position/length on an explicit basis....you might do that if you want your Window Size to match a particular pixel size.</p></li>
</ul> |
13,960,556 | Interpreting eclipse .classpath file. What does 'kind="con"' and 'exported="true"' mean? | <p>This is the eclipse <code>.classpath</code> file of the eclipse plugin program that I downloaded. </p>
<p>I think that <code>kind="src"</code> and <code>kind="output"</code> is pretty straight forward, as they means the where the source java files and compiled class files are located. </p>
<p>The <code>kind="lib"</code> seems to indicate the jar files the plugin is referencing, but I have something that I'm not sure about. </p>
<ul>
<li>What does the <code>kind="con"</code> mean? </li>
<li>What is it for the <code>exported="true"</code>? I think in order to use this plugin, all the jar files that the plugin refers to should be exported, but only some of them are exported.</li>
</ul>
<p><img src="https://i.stack.imgur.com/Lyjtu.png" alt="enter image description here"></p> | 13,960,981 | 2 | 0 | null | 2012-12-19 20:22:47.687 UTC | 11 | 2017-12-02 07:37:13.86 UTC | 2015-02-20 14:40:16.583 UTC | null | 342,473 | null | 260,127 | null | 1 | 35 | java|eclipse|eclipse-plugin|classpath | 22,975 | <p>1) In <code>kind="con"</code>, the <code>con</code> stands for container, which is interpreted by eclipse as a <a href="http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/IClasspathContainer.html">classpath container</a>. As described in that link:</p>
<blockquote>
<p>A classpath container provides a way to indirectly reference a set of
classpath entries through a classpath entry of kind CPE_CONTAINER</p>
</blockquote>
<p>In other words, it enables grouping of other classpath entries in any way and re-use it wherever (including the ability of having different entries for different projects).</p>
<p>2) <code>exported</code>:
Say you have Project <code>B</code> that depends on Project <code>C</code>. The dependency is defined as <code>exported=true</code>. Then, another Project <code>A</code> that depends on Project <code>B</code>, will have also Project <code>C</code> present on <code>A</code>'a classpath.</p> |
14,063,327 | How to disable the "Expect: 100 continue" header in HttpWebRequest for a single request? | <p><code>HttpWebRequest</code> automatically appends an <code>Expect: 100-continue</code> header for POST requests. Various sources around the internet suggest that this can be disabled as follows:</p>
<pre><code>System.Net.ServicePointManager.Expect100Continue = false;
</code></pre>
<p>However, I'm writing a library and I cannot disable this for the entire appdomain, in case the application relies on this behaviour. Nor can I assume that it will remain set to this value. How can I disable it for a specific request?</p> | 14,063,329 | 3 | 1 | null | 2012-12-28 01:06:39.633 UTC | 8 | 2022-02-01 21:36:25.137 UTC | 2017-02-24 18:17:49.74 UTC | null | 33,080 | null | 33,080 | null | 1 | 47 | c#|.net|httpwebrequest | 44,482 | <p>The <code>HttpWebRequest</code> class has a property called <code>ServicePoint</code> which can be used to change this setting for a specific request. For example:</p>
<pre><code>var req = (HttpWebRequest) WebRequest.Create(...);
req.ServicePoint.Expect100Continue = false;
</code></pre> |
28,873,323 | Removing attributes of columns in data.frames on multilevel lists in R | <p>How do I remove the attributes of the following columns of data.frames on a nested list in R on the fly? </p>
<pre><code>List of 1
$ 0021400001:List of 19
$ GameSummary :'data.frame': 1 obs. of 13 variables:
$ GAME_DATE_EST : Factor w/ 1 level "2014-11-09T00:00:00": 1
- attr(*, "names")= chr "1"
$ GAME_SEQUENCE : Factor w/ 1 level "2": 1
- attr(*, "names")= chr "2"
$ GAME_ID : Factor w/ 1 level "0021400091": 1
- attr(*, "names")= chr "3"
$ GAME_STATUS_ID : Factor w/ 1 level "3": 1
- attr(*, "names")= chr "4"
$ SeasonSeries :'data.frame': 1 obs. of 7 variables:
$ GAME_ID : Factor w/ 1 level "0021400001": 1
- attr(*, "names")= chr "1"
$ HOME_TEAM_ID : Factor w/ 1 level "1610612740": 1
- attr(*, "names")= chr "2"
$ VISITOR_TEAM_ID : Factor w/ 1 level "1610612753": 1
- attr(*, "names")= chr "3"
</code></pre> | 40,406,334 | 8 | 4 | null | 2015-03-05 08:36:45.11 UTC | 2 | 2021-10-30 05:35:08.213 UTC | null | null | null | null | 1,452,365 | null | 1 | 20 | r|list | 42,085 | <p>This is perhaps too late to answer on this thread, but I wanted to share.</p>
<p>Two solutions :
1. function stripAttributes from merTools package.</p>
<ol start="2">
<li><p>to remove the attribute ATT from variable VAR in your data-frame MyData:</p>
<pre><code>attr(MyData$VAR, "ATT") <- NULL
</code></pre></li>
</ol>
<p>If you want to remove several attributes of all variables :</p>
<pre><code>For (var in colnames(MyData)) {
attr(MyData[,deparse(as.name(var))], "ATT_1") <- NULL
attr(MyData[,deparse(as.name(var))], "ATT_2") <- NULL
}
</code></pre>
<p>I hope This Helps,
Regards</p> |
29,993,599 | How to do git push in Visual Studio Code? | <p>There is a "Push" menu item, but when I click on it, nothing happens except for a subtle progressing bar showing up and never finished. From Visual Studio Code's Docs page, I found this line: "Credential management is not handled by VSCode for now," and that page links to a GitHub page on credential helper, which is too specific for other remote server (in my case, bitbucket) and not specific enough on how to set up for VS Code.</p> | 30,085,424 | 5 | 7 | null | 2015-05-01 19:18:26.257 UTC | 11 | 2019-01-17 20:16:50.893 UTC | 2015-05-01 20:19:40.433 UTC | null | 1,079,354 | null | 272,258 | null | 1 | 44 | git|visual-studio-code | 67,251 | <p>If you are in windows use this line in your git bash:</p>
<blockquote>
<p>git config --global credential.helper wincred</p>
</blockquote>
<p>Next time git will remember your password. Thats all, the VSCode will work fine ;)</p>
<p>Bye Bytes !</p> |
9,080,431 | How execute bash script line by line? | <p>If I enter <a href="http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html" rel="noreferrer">bash -x</a> option, it will show all the line. But the script will execute normaly.</p>
<p>How can I execute line by line? Than I can see if it do the correct thing, or I abort and fix the bug. The same effect is put a <code>read</code> in every line.</p> | 9,080,645 | 5 | 1 | null | 2012-01-31 13:38:29.417 UTC | 48 | 2021-01-08 21:00:22.337 UTC | null | null | null | null | 632,472 | null | 1 | 120 | bash | 99,200 | <p>You don't need to put a read in everyline, just add a trap like the following into your bash script, it has the effect you want, eg.</p>
<pre><code>#!/usr/bin/env bash
set -x
trap read debug
< YOUR CODE HERE >
</code></pre>
<p>Works, just tested it with bash v4.2.8 and v3.2.25.</p>
<hr>
<p><strong>IMPROVED VERSION</strong></p>
<p>If your script is reading content from files, the above listed will not work. A workaround could look like the following example.</p>
<pre><code>#!/usr/bin/env bash
echo "Press CTRL+C to proceed."
trap "pkill -f 'sleep 1h'" INT
trap "set +x ; sleep 1h ; set -x" DEBUG
< YOUR CODE HERE >
</code></pre>
<p>To stop the script you would have to <strong>kill it from another shell</strong> in this case.</p>
<hr>
<p><strong>ALTERNATIVE1</strong></p>
<p>If you simply want to wait a few seconds before proceeding to the next command in your script the following example could work for you.</p>
<pre><code>#!/usr/bin/env bash
trap "set +x; sleep 5; set -x" DEBUG
< YOUR CODE HERE >
</code></pre>
<p>I'm adding set +x and set -x within the trap command to make the output more readable.</p> |
24,798,666 | How to Print the output of a function using console.log (Javascript) | <p>The following code is meant print the namestring with a name. however, it's not correct.</p>
<pre><code>var nameString = function (name) {
return "Hi, I am" + " " + name.
}
nameString("Amir")
console.log(nameString)
</code></pre>
<p>What am I not implementing/doing wrong that stops it from displaying the string as well as a name? thanks.</p> | 24,798,809 | 6 | 3 | null | 2014-07-17 08:37:23.383 UTC | 1 | 2021-10-12 23:00:57.04 UTC | null | null | null | null | 3,848,245 | null | 1 | 4 | javascript | 62,175 | <p>First mistake in your code is in the line</p>
<pre><code> return "Hi, I am" + " " + name.
</code></pre>
<p>remove fullstop or just concatenate it as below</p>
<pre><code> return "Hi, I am" + " " + name+"."
</code></pre>
<p>and then write</p>
<pre><code>console.log(nameString("Amir"));
</code></pre>
<p>check it here <a href="http://jsfiddle.net/rLLp8/" rel="noreferrer">fiddle</a></p> |
34,980,251 | How to print multiple lines of text with Python | <p>If I wanted to print multiple lines of text in Python without typing <code>print('')</code> for every line, is there a way to do that?</p>
<p>I'm using this for ASCII art.</p>
<p>(Python 3.5.1)</p> | 34,980,283 | 5 | 3 | null | 2016-01-24 19:17:53.08 UTC | 23 | 2021-11-11 13:05:38.007 UTC | 2021-02-07 05:37:25.237 UTC | null | 63,550 | null | 5,833,159 | null | 1 | 54 | python|python-3.x | 259,556 | <p>You can use <em>triple</em> quotes (single ' or double "):</p>
<pre><code>a = """
text
text
text
"""
print(a)
</code></pre> |
214,734 | Some x86 ASM Reference/Tutorials? | <p>I'm trying to find some references in regards to x86 Assembly languages. Tutorials/Examples to help my understanding.
-Thanks</p> | 214,737 | 5 | 0 | null | 2008-10-18 08:00:36.747 UTC | 17 | 2015-10-08 19:46:58.77 UTC | 2012-05-02 12:22:28.013 UTC | null | 192,221 | Dacto | 22,582 | null | 1 | 35 | reference|x86|assembly | 27,646 | <ul>
<li><a href="http://download.savannah.gnu.org/releases/pgubook/ProgrammingGroundUp-1-0-booksize.pdf" rel="noreferrer">Programming from the Ground Up</a> (free book, highly recommended)</li>
<li><a href="http://en.wikibooks.org/wiki/X86_Assembly" rel="noreferrer">x86 Assembly</a> (wikibooks.org)</li>
<li><a href="http://learn86.awardspace.co.uk/" rel="noreferrer">Essential Resources for x86 Programmers</a></li>
</ul> |
1,085,083 | Regular expressions in C: examples? | <p>I'm after some simple examples and best practices of how to use regular expressions in ANSI C. <code>man regex.h</code> does not provide that much help.</p> | 1,085,120 | 5 | 2 | null | 2009-07-05 23:38:03.557 UTC | 93 | 2022-05-02 12:43:25.233 UTC | 2012-12-25 06:10:56.94 UTC | null | 739,331 | null | 50,305 | null | 1 | 197 | c|regex | 404,507 | <p>Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on <a href="http://web.archive.org/web/20160308115653/http://peope.net/old/regex.html" rel="noreferrer">this</a>):</p>
<pre><code>#include <regex.h>
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);
</code></pre>
<p>Alternatively, you may want to check out <a href="http://www.pcre.org/" rel="noreferrer">PCRE</a>, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by <code>grep</code>, <code>sed</code>, <code>vi</code>, etc.</p> |
1,031,175 | Rails - Easy way to display all fields in view | <p>OK I'm sure I'm missing something here, but please forgive me I'm new to Rails. </p>
<p>Is there some way in Rails to display all the fields for an object rather than specifying each? </p>
<p>In my show.html template rather than going </p>
<pre><code><p>Name: <%=h @user.full_name %></p>
<p>Email: <%=h @user.email %></p>
</code></pre>
<p>I just want a oneliner to do this without having to type out each of the 15 or so fields I have.
Its an admin page so its fine if all the fields are shown (id, created_at, etc.)
If this was PHP it would take me about 5 secs using foreach, but I've googled (on the wrong things obviously) for an hour with no luck. </p>
<p>Thanks!</p> | 1,031,271 | 6 | 0 | null | 2009-06-23 07:50:25.21 UTC | 13 | 2016-07-13 14:44:04.12 UTC | null | null | null | null | 127,411 | null | 1 | 13 | ruby-on-rails|view | 11,998 | <p>Something like</p>
<pre><code><% for attribute in @user.attributes.keys %>
<p><%= attribute.humanize %> <%= @user.attributes[attribute].to_s %></p>
<% end %>
</code></pre>
<p>could do the trick.</p>
<p>Matt</p> |
961,878 | Moving from Visual Sourcesafe to Mercurial | <p>What's the best way to move a Visual Sourcesafe repository to Mercurial (I'm interested in retaining all history)?</p> | 961,918 | 6 | 0 | null | 2009-06-07 13:22:01.85 UTC | 11 | 2017-06-20 09:40:48.333 UTC | 2012-03-30 12:24:27.683 UTC | null | 110,204 | null | 118,058 | null | 1 | 19 | mercurial|migration|dvcs|visual-sourcesafe | 5,119 | <p>While I haven't made that particular conversion, I have gone from VSS to SVN using (IIRC) <a href="http://www.pumacode.org/projects/vss2svn" rel="noreferrer">this script</a>. You'll probably want to look into tailor and do a search for vss2hg. Also keep in mind that it may make sense to go through an intermediate step like vss2svn + svn2hg or similar.</p>
<p>The primary bit of advice I'd give though is: script the conversion so you can re-run it easily. That will let you run nightly conversions from VSS to Hg and make sure that everything is converting correctly before you pull the trigger on it.</p> |
1,285,986 | Flags enum & bitwise operations vs. “string of bits” | <p>A fellow developer suggested we store a selection of days of the week as 7-character string of 1’s and 0’s, i.e. “1000100” for Monday and Friday. I preferred (and strongly suggested) a solution with a Flags enum and bitwise operations, I think it's a cleaner way of doing this, and it should be easier to understand for other developers.</p>
<pre><code> [Flags()]
public enum Weekdays : int
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
</code></pre>
<p>However, as I started to implement a sample solution, I realized that maybe the simple string approach was easier after all: Certainly the bit-string is more obvious than “17” if you’re just looking at the data. And I find the C# bitwise operations counter-intuitive and extremely verbose:</p>
<pre><code>Weekdays workDays = Weekdays.Monday | Weekdays.Tuesday;
if ((workDays & Weekdays.Monday) == Weekdays.Monday)
{...}
</code></pre>
<p>Of course this could be wrapped nicely into extension methods, but then we suddenly end up with at least the same number of lines of code as with the string-solution, and I can hardly argue the bitwise code is easier to read.</p>
<p>That being said, I still would go with a flags enum and bitwise operations. The key benefits I can think of are </p>
<ul>
<li>Better performance</li>
<li>Less space needed for storage</li>
</ul>
<p>So how do I sell the bitwise solution to my colleagues? Should I? What are the other benefits of using this method over strings? After completing the sample project, I found that the team still opted for the string-based solution. I need some better/stronger arguments.
Why should you use Flags enums rather than simple bit-strings?</p> | 1,286,472 | 6 | 4 | null | 2009-08-17 02:58:11.03 UTC | 21 | 2013-05-06 16:55:08.19 UTC | 2013-03-15 15:28:07.19 UTC | null | 102,441 | null | 10,932 | null | 1 | 36 | c#|bit-manipulation|enum-flags | 42,114 | <p><strong>Benefits of using Flags enum:</strong></p>
<ul>
<li>Standard approach: <a href="http://msdn.microsoft.com/en-us/library/ms229062.aspx" rel="noreferrer">"They are the correct design to use when multiple enumeration values can be specified at the same time."</a></li>
<li>Intent is clear</li>
<li>Maintainable -- new programmers should pick this up easily </li>
<li>Easily extensible -- support for new flag combinations (e.g. weekend)</li>
<li>Fast</li>
</ul>
<p><strong>Negatives of using Flags enum:</strong></p>
<ul>
<li>Data representation for humans hard to understand (e.g. what flags are set for 17?)</li>
</ul>
<p><BR>
<strong>Benefits of using string of bits:</strong></p>
<ul>
<li>Easy for programmers to see which bits are set in string </li>
</ul>
<p><strong>Negatives of using string of bits:</strong></p>
<ul>
<li>Non-standard approach</li>
<li>Harder to understand for programmers unfamiliar with your design</li>
<li>Potentially easier to set "garbage" values (e.g. stringValue = "Sunday")</li>
<li>Needless string creation</li>
<li>Needless string parsing</li>
<li>Additional development work</li>
<li>Reinventing the wheel (but not even a round wheel)</li>
</ul>
<p><BR>
How important is it really to be able to look at the string of bits to see what is set? If it's hard to know that 17 is Monday and Friday, you can always use calculator and convert to binary. Or add some sort of string representation for "display" (or debugging) use. It's not <em>that</em> difficult.</p>
<p><BR> It also seems to me that if you are going to make the string of bits approach solid then you will need to do quite a bit of encapsulation to bring it up to a level of abstraction that the Flags enum already provides. If the approach is to simply manipulate the string of bits directly then that is going to be hard to read (and understand) and probably error prone. </p>
<p>e.g. you may end up seeing this:</p>
<pre><code>days = "1000101"; // fixed bug where days were incorrectly set to "1010001"
</code></pre> |
1,093,020 | Unit testing and checking private variable value | <p>I am writing unit tests with C#, NUnit and Rhino Mocks.
Here are the relevant parts of a class I am testing:</p>
<pre><code>public class ClassToBeTested
{
private IList<object> insertItems = new List<object>();
public bool OnSave(object entity, object id)
{
var auditable = entity as IAuditable;
if (auditable != null) insertItems.Add(entity);
return false;
}
}
</code></pre>
<p>I want to test the values in insertItems after a call to OnSave:</p>
<pre><code>[Test]
public void OnSave_Adds_Object_To_InsertItems_Array()
{
Setup();
myClassToBeTested.OnSave(auditableObject, null);
// Check auditableObject has been added to insertItems array
}
</code></pre>
<p>What is the best practice for this? I have considered adding insertItems as a Property with a public get, or injecting a List into ClassToBeTested, but not sure I should be modifying the code for purposes of testing.</p>
<p>I have read many posts on testing private methods and refactoring, but this is such a simple class I wondered what is the best option.</p> | 1,093,481 | 6 | 2 | null | 2009-07-07 15:29:12.98 UTC | 14 | 2015-09-04 18:39:19.303 UTC | 2011-10-09 07:18:22.81 UTC | null | 11,635 | null | 95,423 | null | 1 | 64 | c#|unit-testing|nunit | 69,946 | <p>The quick answer is that you should never, ever access non-public members from your unit tests. It totally defies the purpose of having a test suite, since it locks you into internal implementation details that you may not want to keep that way.</p>
<p>The longer answer relates to what to do then? In this case, it is important to understand why the implementation is as it is (this is why TDD is so powerful, because we use the tests to <em>specify</em> the expected behavior, but I get the feeling that you are not using TDD).</p>
<p>In your case, the first question that comes to mind is: "Why are the IAuditable objects added to the internal list?" or, put differently, "What is the expected <em>externally visible</em> outcome of this implementation?" Depending on the answer to those questions, <em>that's</em> what you need to test.</p>
<p>If you add the IAuditable objects to your internal list because you later want to write them to an audit log (just a wild guess), then invoke the method that writes the log and verify that the expected data was written.</p>
<p>If you add the IAuditable object to your internal list because you want to amass evidence against some kind of later Constraint, then try to test that.</p>
<p>If you added the code for no measurable reason, then delete it again :)</p>
<p>The important part is that it is very beneficial to test <em>behavior</em> instead of <em>implementation</em>. It is also a more robust and maintainable form of testing.</p>
<p>Don't be afraid to modify your System Under Test (SUT) to be more testable. As long as your additions make sense in your domain and follow object-oriented best practices, there are no problems - <a href="http://blog.ploeh.dk/2009/06/05/TestabilityIsReallyTheOpenClosedPrinciple.aspx" rel="noreferrer">you would just be following the Open/Closed Principle</a>.</p> |
42,301,884 | Safari not setting CORS cookies using JS Fetch API | <p>I am unable to get Safari to successfully apply <code>Set-Cookie</code> from server responses when using the Fetch API (actually, via the <a href="https://github.com/github/fetch" rel="noreferrer">fetch polyfill</a>). The same code works correctly in FF and Chrome (I tested using both native and polyfill <code>fetch</code>).</p>
<ol>
<li>The request is across domains;</li>
<li>yes, I am setting <code>credentials: true</code>;</li>
<li>the server does respond with a <code>Set-Cookie</code> header;</li>
<li>subsequent requests are sent from Chrome and FF with cookie request headers, but Safari does not;</li>
<li>the request uses HTTPS (the cert is self-signed and on a development domain but it seems to be accepted by Safari on regular requests); and</li>
</ol>
<p>Does someone know what the problem might be?</p>
<p>I've read through the documentation and gone through many of the <a href="https://github.com/whatwg/fetch/issues" rel="noreferrer">closed bug reports</a>. Unless I missed something, I think maybe the problem is with the <a href="https://github.com/github/fetch#sending-cookies" rel="noreferrer">'default browser behaviour'</a> dealing with cookies and CORS -- and not with fetch (reading through the polyfill source code, it seems 100% ignorant of cookies). A few bug reports suggest a malformed server response can prevent cookies from being saved.</p>
<p>My code looks like this:</p>
<pre><code>function buildFetch(url, init={}) {
let headers = Object.assign({}, init.headers || {}, {'Content-Type': 'application/json'});
let params = Object.assign({}, init, { credentials: 'include', headers });
return fetch(`${baseUrl}${url}`, params);
}
buildFetch('/remote/connect', {method: 'PUT', body: JSON.stringify({ code })})
.then(response => response.json())
.then(/* complete authentication */)
</code></pre>
<p>The actual authorization request is below. I am using cURL to get the exact request/response data, since Safari makes it hard to copy/paste it.</p>
<pre><code>curl 'https://mydevserver:8443/api/v1/remote/connect' \
-v \
-XPUT \
-H 'Content-Type: application/json' \
-H 'Referer: http://localhost:3002/' \
-H 'Origin: http://localhost:3002' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8' \
--data-binary '{"token":"value"}'
* Trying 127.0.0.1...
* Connected to mydevserver (127.0.0.1) port 8443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: mydevserver
> PUT /api/v1/remote/connect HTTP/1.1
> Host: mydevserver:8443
> Accept: */*
> Content-Type: application/json
> Referer: http://localhost:3002/
> Origin: http://localhost:3002
> User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8
> Content-Length: 15
>
* upload completely sent off: 15 out of 15 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: http://localhost:3002
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Api-Key, Device-Key
< Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
< Access-Control-Expose-Headers: Date
< Content-Type: application/json; charset=utf-8
< Content-Length: 37
< Set-Cookie: express:sess=[SESSIONKEY]=; path=/; expires=Fri, 17 Feb 2017 15:30:01 GMT; secure; httponly
< Set-Cookie: express:sess.sig=[SIGNATURE]; path=/; expires=Fri, 17 Feb 2017 15:30:01 GMT; secure; httponly
< Date: Fri, 17 Feb 2017 14:30:01 GMT
< Connection: keep-alive
<
* Connection #0 to host mydevserver left intact
{"some":"normal","response":"payload"}
</code></pre> | 42,359,630 | 3 | 3 | null | 2017-02-17 15:39:53.617 UTC | 7 | 2022-07-19 20:41:06.23 UTC | 2022-03-15 16:22:58.183 UTC | null | 3,689,450 | null | 279,608 | null | 1 | 29 | javascript|cookies|safari|cross-domain|fetch-api | 13,146 | <p>Answering my own question.</p>
<p>I find it pretty enraging that this is a "working as intended" behaviour of Safari, though I understand their motivation. XHR (and presumably native fetch when it lands natively) does not support the setting of third-party cookies at all. This failure is completely transparent because it is handled by the browser outside of the scripting context, so client-based solutions are not really going to be possible.</p>
<p>One recommended solution you will find here is to open a window or iframe to an HTML page on the API server and set a cookie there. At this point, 3rd party cookies will begin to work. This is pretty fugly and there is no guarantee that Safari won't at some point close that loophole.</p>
<p>My solution is to basically reimplement an authentication system that does what session-cookies do. Namely:</p>
<ol>
<li>Add a new header, <code>X-Auth: [token]</code>, where <code>[token]</code> is a very small, short-lived JWT containing the information you require for your session (ideally only the user id -- something that is unlikely to mutate during the lifetime of your application -- but definitely not something like permissions if permissions can be changed during the session);</li>
<li>Add <code>X-Auth</code> to <code>Access-Control-Allow-Headers</code>;</li>
<li>During sign-in, set the session cookie and the auth token with the payloads you require (both Safari and non-Safari users will get both the cookie and the auth header);</li>
<li>On the client, look for the <code>X-Token</code> response header and echo it back as an <code>X-Token</code> request header any time it sees it (you could achieve persistence by using local storage -- the token expires, so even if the value lives for years, it can't be redeemed after a certain point);</li>
<li>On the server, for all requests for protected resources, check for the cookie and use it if it exists;</li>
<li>Otherwise (if the cookie is absent -- because Safari didn't send it), look for the header token, verify and decode the token payload, update the current session with the provided info and then generate a new auth token and add it to the response headers;</li>
<li>Proceed as normally.</li>
</ol>
<p>Note that JWT (or anything similar) is intended to solve a completely different problem and should really never be used for session management because of the "replay" problem (think what could happen if a user had two windows open with their own header-state). In this case, however, they offer the transience and security you normally need. Bottom line is you should use cookies on browsers that support them, keep the session information as tiny as possible, keep your JWT as short-lived as possible, and build your server app to expect both accidental and malicious replay attacks.</p> |
31,133,301 | Expected response code 250 but got code "", with message "" | <p>I can send my emails in localhost flawlessly. but ever since I uploaded my program into a hosting site I get this error </p>
<blockquote>
<p>Expected response code 250 but got code "", with message ""</p>
</blockquote>
<p>I also updated the <code>.env</code> file.</p>
<pre><code>MAIL_DRIVER=smtp
MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=123456789
</code></pre>
<p>works in localhost but not in the hosting site.</p>
<p>i am using laravel 5</p> | 31,133,964 | 7 | 4 | null | 2015-06-30 08:31:22.73 UTC | 3 | 2022-06-21 11:19:24.957 UTC | 2015-06-30 08:47:14.34 UTC | null | 2,133,785 | null | 2,133,785 | null | 1 | 28 | php|email|laravel|outlook | 91,974 | <p>looks like the smtp was blocked for hostinger free users.</p>
<p><a href="http://www.hostinger.ph/forum/news-and-announcements/229-email-service-updates-1.html" rel="noreferrer">http://www.hostinger.ph/forum/news-and-announcements/229-email-service-updates-1.html</a></p> |
32,567,208 | Best way to verify string is empty or null | <p>i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both. </p>
<p>1) Below does not account for all spaces like in case of empty XML tag</p>
<pre><code>return inputString==null || inputString.length()==0;
</code></pre>
<p>2) Below one takes care but trim can eat some performance + memory </p>
<pre><code>return inputString==null || inputString.trim().length()==0;
</code></pre>
<p>3) Combining one and two can save some performance + memory (As Chris suggested in comments)</p>
<pre><code>return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;
</code></pre>
<p>4) Converted to pattern matcher (invoked only when string is non zero length)</p>
<pre><code>private static final Pattern p = Pattern.compile("\\s+");
return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();
</code></pre>
<p>5) Using libraries like -
Apache Commons (<code>StringUtils.isBlank/isEmpty</code>)
or Spring (<code>StringUtils.isEmpty</code>)
or Guava (<code>Strings.isNullOrEmpty</code>)
or any other option?</p> | 56,202,538 | 14 | 7 | null | 2015-09-14 14:20:17.873 UTC | 6 | 2021-05-14 06:18:13.81 UTC | 2019-09-06 03:55:11.723 UTC | null | 2,131,040 | null | 2,131,040 | null | 1 | 36 | java|regex|string|trim|is-empty | 127,979 | <p>Haven't seen any fully-native solutions, so here's one:</p>
<pre><code>return str == null || str.chars().allMatch(Character::isWhitespace);
</code></pre>
<p>Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):</p>
<pre><code>return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
</code></pre>
<p>Or, to be really optimal (but hecka ugly):</p>
<pre><code>int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
</code></pre>
<p>One thing I like to do:</p>
<pre><code>Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
</code></pre> |
32,414,345 | Aligning multiple div boxes horizontally and vertically | <p>I'm using <a href="https://almsaeedstudio.com/preview" rel="nofollow noreferrer">https://almsaeedstudio.com/preview</a> theme which gives some brilliant boxes layout and social widget boxes layout which I want to use in my project. </p>
<p>Refer to simple box screenshot </p>
<p><a href="https://i.stack.imgur.com/p7H8k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p7H8k.png" alt=""></a> </p>
<p>and social widget box </p>
<p><a href="https://i.stack.imgur.com/VV7fb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VV7fb.png" alt="screenshot"></a>. </p>
<p>I'm trying to arrange multiple simple boxes horizontally where each of the simple box can contain multiple social widget boxes. </p>
<p>Refer to this screenshot for more clarity:</p>
<p><a href="https://i.stack.imgur.com/S4iTn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S4iTn.png" alt="screenshot"></a>. </p>
<p>I tried playing with the exiting simple boxes and social widget boxes code and come up with this snippet.</p>
<p>I have created this plunker, somehow css is not getting loaded properly. </p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="row">
<div class="col-md-12">
<div style="overflow:auto;">
<div class="" style="width:2050px;">
<div class="box" style="display:inline-block;width:1000px;">
<div class="box-header with-border">
<h3 class="box-title">Monthly Recap Report</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<div class="btn-group">
<button class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another action</a>
</li>
<li><a href="#">Something else here</a>
</li>
<li class="divider"></li>
<li><a href="#">Separated link</a>
</li>
</ul>
</div>
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i>
</button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body" style="display: block;">
<div class="">
<div class="box box-widget collapsed-box">
<hr>
<div class="box-header with-border">
<div class="user-block">
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad"><span class="username"><a href="#">Jonathan Burke Jr.</a></span><span class="description">7:30 PM Today</span>
</div>
<!-- /.user-block-->
<div class="box-tools">
<button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools-->
</div>
<!-- /.box-header-->
<div class="box-body" style="display: block;">
<p>I took this photo this morning. What do you guys think?</p>
<button class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Like</button><span class="pull-right text-muted">127 likes - 3 comments</span>
</div>
<!-- /.box-body-->
<div class="box-footer box-comments" style="display: block;">
<div class="box-comment">
<!-- User image-->
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad">
<div class="comment-text"><span class="username">Maria Gonzales<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
<div class="box-comment">
<!-- User image-->
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="alt text">
<div class="comment-text"><span class="username">Luna Stark<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
</div>
<!-- /.box-footer-->
<div class="box-footer" style="display: block;">
<form>
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="alt text">
<div class="img-push">
<input type="text" placeholder="Press enter to post comment" class="form-control input-sm">
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
<div class="box box-widget collapsed-box">
<hr>
<div class="box-header with-border">
<div class="user-block">
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad"><span class="username"><a href="#">Jonathan Burke Jr.</a></span><span class="description">7:30 PM Today</span>
</div>
<!-- /.user-block-->
<div class="box-tools">
<button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools-->
</div>
<!-- /.box-header-->
<div class="box-body" style="display: block;">
<p>I took this photo this morning. What do you guys think?</p>
<button class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Like</button><span class="pull-right text-muted">127 likes - 3 comments</span>
</div>
<!-- /.box-body-->
<div class="box-footer box-comments" style="display: block;">
<div class="box-comment">
<!-- User image-->
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad">
<div class="comment-text"><span class="username">Maria Gonzales<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
<div class="box-comment">
<!-- User image-->
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="alt text">
<div class="comment-text"><span class="username">Luna Stark<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
</div>
<!-- /.box-footer-->
<div class="box-footer" style="display: block;">
<form>
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad">
<div class="img-push">
<input type="text" placeholder="Press enter to post comment" class="form-control input-sm">
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
</div>
<!-- /.row -->
</div>
<!-- ./box-body -->
<div class="box-footer" style="display: block;">
<!-- /.row -->
</div>
<!-- /.box-footer -->
</div>
<!-- /.box -->
<div class="box" style="display:inline-block;width:1000px;">
<div class="box-header with-border">
<h3 class="box-title">Monthly Recap Report</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<div class="btn-group">
<button class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown"><i class="fa fa-wrench"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another action</a>
</li>
<li><a href="#">Something else here</a>
</li>
<li class="divider"></li>
<li><a href="#">Separated link</a>
</li>
</ul>
</div>
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i>
</button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body" style="display: block;">
<div class="">
<div class="box box-widget collapsed-box">
<hr>
<div class="box-header with-border">
<div class="user-block">
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad"><span class="username"><a href="#">Jonathan Burke Jr.</a></span><span class="description">7:30 PM Today</span>
</div>
<!-- /.user-block-->
<div class="box-tools">
<button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools-->
</div>
<!-- /.box-header-->
<div class="box-body" style="display: block;">
<p>I took this photo this morning. What do you guys think?</p>
<button class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Like</button><span class="pull-right text-muted">127 likes - 3 comments</span>
</div>
<!-- /.box-body-->
<div class="box-footer box-comments" style="display: block;">
<div class="box-comment">
<!-- User image-->
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="alt text">
<div class="comment-text"><span class="username">Maria Gonzales<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
<div class="box-comment">
<!-- User image-->
<img src="../dist/img/user4-128x128.jpg" alt="user image" class="img-circle img-sm">
<div class="comment-text"><span class="username">Luna Stark<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
</div>
<!-- /.box-footer-->
<div class="box-footer" style="display: block;">
<form>
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="alt text">
<div class="img-push">
<input type="text" placeholder="Press enter to post comment" class="form-control input-sm">
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
<div class="box box-widget collapsed-box">
<hr>
<div class="box-header with-border">
<div class="user-block">
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad"><span class="username"><a href="#">Jonathan Burke Jr.</a></span><span class="description">7:30 PM Today</span>
</div>
<!-- /.user-block-->
<div class="box-tools">
<button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-plus"></i>
</button>
</div>
<!-- /.box-tools-->
</div>
<!-- /.box-header-->
<div class="box-body" style="display: block;">
<p>I took this photo this morning. What do you guys think?</p>
<button class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Like</button><span class="pull-right text-muted">127 likes - 3 comments</span>
</div>
<!-- /.box-body-->
<div class="box-footer box-comments" style="display: block;">
<div class="box-comment">
<!-- User image-->
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad">
<div class="comment-text"><span class="username">Maria Gonzales<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
<div class="box-comment">
<!-- User image-->
<img src="../dist/img/user4-128x128.jpg" alt="user image" class="img-circle img-sm">
<div class="comment-text"><span class="username">Luna Stark<span class="text-muted pull-right">8:03 PM Today</span></span>
<!-- /.username-->It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
</div>
<!-- /.comment-text-->
</div>
<!-- /.box-comment-->
</div>
<!-- /.box-footer-->
<div class="box-footer" style="display: block;">
<form>
<img src="../dist/img/photo2.png" alt="Photo" class="img-responsive pad">
<div class="img-push">
<input type="text" placeholder="Press enter to post comment" class="form-control input-sm">
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
</div>
<!-- /.row -->
</div>
<!-- ./box-body -->
<div class="box-footer" style="display: block;">
<!-- /.row -->
</div>
<!-- /.box-footer -->
</div>
</div>
<!-- /.col -->
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="http://plnkr.co/edit/slpJLIRVGfMSC8JWG1bT?p=preview" rel="nofollow noreferrer">http://plnkr.co/edit/slpJLIRVGfMSC8JWG1bT?p=preview</a></p>
<p>But its not working. Can anyone please help me how to accomplish this ?</p>
<p>P.S.: I have searched on internet and found similar threads but none is working for me.
<a href="https://stackoverflow.com/questions/24261376/css-horizontally-align-div-without-float">Horizontally align div without float</a></p>
<p>I'm still a beginner in CSS and would really appreciate if I can get some help here. I'm breaking my head on this for a long time.</p>
<p><strong>Update</strong></p>
<p>I think it makes sense to clearly write out the actual issues and try to solve them one by one.</p>
<ol>
<li>Horizontal boxes are not aligned on the same row if the inner social widget box is collapsed/expanded. How can I ensure the height of the horizontal box is fixed irrespective of the inner social widget box height ? Refer to screenshot for same.
<a href="https://i.stack.imgur.com/7hPHm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7hPHm.png" alt="Mis-alignment of horizontal boxes"></a></li>
<li>There are some answers which mention the use of <code>display: float:left;</code> but my issue is the variable width which actually ensures all horizontal boxes on the same row.</li>
</ol>
<blockquote>
<pre><code> <div class="" style="width:2050px;">
</code></pre>
</blockquote>
<p>How do I ensure the <code>width:2050px;</code> to increase dynamically as I will be adding inner boxes on fly. P.S.: I'm using angularjs for ui. Is there any CSS trick which is independent of the <code>width:2050px;</code> That way there will be no dependency on the total width calculation.</p>
<ol start="3">
<li><p>How to fix the height of inner social widget box ? The inner social widget box overflows the actual horizontol container. how can I fix this ?</p></li>
<li><p>Sharing an image of what actually I'm trying to accomplish. <a href="https://i.stack.imgur.com/XQt0N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQt0N.png" alt="Multiple Timelines"></a>. </p></li>
</ol>
<p>In short I want to accomplish point 4 with <a href="https://almsaeedstudio.com/preview" rel="nofollow noreferrer">this</a> theme's existing boxes and social widget boxes. If there is any other better way of doing this, please share the same.</p>
<p>In case anything is not clear, please feel free to mention it in comment. I'll update the question accordingly.</p>
<p>Thanks</p>
<p><strong>Update 2:</strong></p>
<p>I think same height columns is what making this problem more complicated. What I can do is having a scroll bar inside horizontol box which can have multiple social widgets boxes. That way we can have a fixed height for each of the horizontol column.</p>
<p><strong><em>Update 3:</em></strong></p>
<p>While zer00ne@ has provided one solution which is based on Flex. I have read on some forums that it doesn;t work on all browsers. Since my web-page is going to be mobile friendly, I;m more inclined towards achieving my desired results using general CSS techniques.</p>
<p>In path of achieving my result, I created following version <a href="http://plnkr.co/edit/awVmJWJo0AdrQvdbXG2y?p=preview" rel="nofollow noreferrer">http://plnkr.co/edit/awVmJWJo0AdrQvdbXG2y?p=preview</a> using this SO <a href="https://stackoverflow.com/questions/11320323/tw-bootstrap-how-to-overflow-columns">thread</a>. Following is screenshot of same:</p>
<p><a href="https://i.stack.imgur.com/TlfKj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TlfKj.png" alt="enter image description here"></a></p>
<p>Now I'm facing one issue of text getting out of inner social widget box. I need some help on this thing.</p>
<p>In addition to that, can people take a review of these if this solution is any better or not ?</p>
<p>Thanks</p> | 32,486,662 | 5 | 19 | null | 2015-09-05 14:44:19.913 UTC | 5 | 2016-02-20 18:38:19.643 UTC | 2017-05-23 12:32:08.41 UTC | null | -1 | null | 751,223 | null | 1 | 31 | javascript|jquery|html|css|twitter-bootstrap | 5,888 | <h2><strong>>>>>>>>>>>>>>>>>>>>>FLEXBOX SOLUTION<<<<<<<<<<<<<<<<<<<<</strong></h2>
<p>Here is the <strong>REAL SOLUTION</strong> to the <strong>ORIGINAL QUESTION</strong> if anyone is actually interested. </p>
<p>dark_shadow:</p>
<blockquote>
<p>While zer00ne@ has provided one solution which is based on Flex.</p>
</blockquote>
<p>Problem resolved see my demos below, it speaks for itself. I have no idea why starikovs is getting upvotes at all when there is clearly no solution provided.</p>
<p>I had to recreate the page because the extra classless <code><div></code>s you placed inside the markup was confusing. The significant change was adding flexbox to the layout. I used two flexbox containers, one that controlled the two columns <code>.flexRow</code> and another inside of each column to control the widgetboxes, <code>.flexCol</code>. Those classless <code><div></code>s are combined into a <code><section class="colWrap"</code> I added intrinsic measurements so that your layout isn't stuck at a fixed width of 2050px, you'll still need to adjust both <code>.box</code> to an intrinsic measurement, 1000px fixed is going to give grief in the future. The changes will be annotated when I get back. Unless of course this isn't what you wanted?</p>
<p><strong>LAST to the LAST UPDATE</strong></p>
<h1><a href="http://plnkr.co/edit/cHYkMvc5fpVRPl9TIF5C?p=preview" rel="nofollow noreferrer"><strong>>>>>>>>>>>PLUNKER<<<<<<<<<<</strong></a></h1>
<p><strong>EDIT</strong></p>
<p><del>Just add a fixed height to <code>.colWrap</code>, suggest <code>100vh</code> to <code>150vh</code></del></p>
<p>I checked out the height of both columns and they are in fact identical down to the decimal. See the screenshots:</p>
<p><a href="https://i.imgur.com/l7Lefi9.png" rel="nofollow noreferrer">Column 1</a></p>
<p><a href="https://i.imgur.com/sPnGUuU.png" rel="nofollow noreferrer">Column 2</a></p>
<p><hr></p>
<h2>OLD</h2>
<p>You just need everything aligned, correct? Ok, look here please: <a href="http://embed.plnkr.co/MRI69qLoTkiL9F68g54M/preview" rel="nofollow noreferrer">http://embed.plnkr.co/MRI69qLoTkiL9F68g54M/preview</a></p>
<p>I added this to the <code><head></code></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<base href="https://almsaeedstudio.com/themes/AdminLTE/">
<link href="https://almsaeedstudio.com/themes/AdminLTE/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/>
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Added the script as well. It's located before the closing <code></body></code> tag.</p>
<pre><code><script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/app.min.js"></script>
<!-- Sparkline -->
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- SlimScroll 1.3.0 -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- ChartJS 1.0.1 -->
<script src="plugins/chartjs/Chart.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="dist/js/pages/dashboard2.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
</code></pre>
<p>You probably don't need all of them, but the essential ones are:</p>
<ul>
<li>bootstrap.min.css</li>
<li>font-awesome.min.css</li>
<li>jQuery-2.1.4.min.js</li>
<li>bootstrap.min.js</li>
<li>app.min.js</li>
<li>jquery.slimscroll.min.js</li>
</ul>
<p>There's a lot of relative URLs (ex. ../dist/img/photo2.png), so I added the following to the top of the <code><head></code>:</p>
<p><code><base href="https://almsaeedstudio.com/themes/AdminLTE/"></code></p>
<p>The majority of these external files are located at that base url. If the download package didn't properly provide adequate assets, I always go to the source of the site's <a href="http://view-source:https://almsaeedstudio.com/themes/AdminLTE/index2.html" rel="nofollow noreferrer"><strong>demo</strong></a>. Frequently the developer(s) neglect the differences between the dist and the demo.</p>
<p><strong>UPDATE</strong></p>
<p>As I understand the problem is that the layout needs to be properly aligned with widgetboxes or in the absence of widgetboxes. I don't think using <code>display:none</code> on widgetboxes is the way this template was designed. Consider the following annotated excerpts from the file, <code>app.min.js</code> </p>
<p><strong>Excerpts from the AdminLTE script, <code>app.min.js</code></strong></p>
<p>Notes at the bottom.</p>
<pre><code>/*! AdminLTE app.js
* ================
* Main JS application file for AdminLTE v2. This file
* should be included in all pages. It controls some layout
* options and implements exclusive AdminLTE plugins.ᵃ
*
/*...*/†
$.AdminLTE.boxWidget = {
selectors: $.AdminLTE.options.boxWidgetOptions.boxWidgetSelectors,
icons: $.AdminLTE.options.boxWidgetOptions.boxWidgetIcons,
animationSpeed: $.AdminLTE.options.animationSpeed,
activate: function (a) {
var b = this;
a || (a = document), $(a).on("click", b.selectors.collapse,
function (a) {
a.preventDefault(), b.collapse($(this))
}), $(a).on("click", b.selectors.remove, function (a) {
a.preventDefault(), b.remove($(this))
})
},
ᵇcollapse: function (a) {
var b = this,
c = a.parents(".box").first(),
d = c.find(
"> .box-body, > .box-footer, > form >.box-body, > form > .box-footer"
);
c.hasClass("collapsed-box") ? (a.children(":first").removeClass(
b.icons.open).addClass(b.icons.collapse), d.slideDown(
b.animationSpeed,
function () {
c.removeClass("collapsed-box")
})) : (a.children(":first").removeClass(b.icons.collapse)
.addClass(b.icons.open), d.slideUp(b.animationSpeed,
function () {
c.addClass("collapsed-box")
}))
},
ᶜ remove: function (a) {
var b = a.parents(".box").first();
b.slideUp(this.animationSpeed)
}
}
}
if("undefined" == typeof jQuery) throw new Error(
"AdminLTE requires jQuery");
/*...*/†
ᵈ function (a) {
"use strict";
a.fn.boxRefresh = function (b) {
function c(a) {
a.append(f), e.onLoadStart.call(a)
}
function d(a) {
a.find(f).remove(), e.onLoadDone.call(a)
}
var e = a.extend({
trigger: ".refresh-btn",
source: "",
onLoadStart: function (a) {
return a
},
onLoadDone: function (a) {
return a
}
}, b),
f = a(
'<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>'
);
return this.each(function () {
if("" === e.source) return void(window.console &&
window.console.log(
"Please specify a source first - boxRefresh()")
);
var b = a(this),
f = b.find(e.trigger).first();
f.on("click", function (a) {
a.preventDefault(), c(b), b.find(".box-body").load(
e.source,
function () {
d(b)
})
})
})
}
}(jQuery),
function (a) {
"use strict";
a.fn.activateBox = function () {
a.AdminLTE.boxWidget.activate(this)
}
}(jQuery) function (a) {
"use strict";
a.fn.boxRefresh = function (b) {
function c(a) {
a.append(f), e.onLoadStart.call(a)
}
function d(a) {
a.find(f).remove(), e.onLoadDone.call(a)
}
var e = a.extend({
trigger: ".refresh-btn",
source: "",
onLoadStart: function (a) {
return a
},
onLoadDone: function (a) {
return a
}
}, b),
f = a(
'<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>'
);
return this.each(function () {
if("" === e.source) return void(window.console &&
window.console.log(
"Please specify a source first - boxRefresh()")
);
var b = a(this),
f = b.find(e.trigger).first();
f.on("click", function (a) {
a.preventDefault(), c(b), b.find(".box-body").load(
e.source,
function () {
d(b)
})
})
})
}
}(jQuery),
function (a) {
"use strict";
a.fn.activateBox = function () {
a.AdminLTE.boxWidget.activate(this)
}
}(jQuery)
</code></pre>
<p>† This code is skipped over</p>
<p>ᵃ The developer implies that this app is not a complete solution but a complete solution is available to buy.</p>
<p>ᵇ The boxwidgets collapse and height <em>should</em> adjust accordingly.</p>
<p>ᶜ The boxwidgets can be removed and height <em>should</em> be adjusted accordingly.</p>
<p>ᵈ The function <code>boxRefresh()</code> is a public method I believe. It could be used after an addition or subtraction of a widget I suppose.</p>
<p>I'm not the best at interpreting third party plugins, so any extra observations and/or corrections are welcome.</p>
<p><strong>LAST UPDATE</strong></p>
<p>I got it so when any section is collapsed, they will slide up rather than down. As for the 2 main columns, they behave as they should and if the first column is actually removed, then the second column will take the first column's place.</p> |
20,993,947 | Prevent a specific child div from expanding the parent div | <p>I'm currently developping a website and encountered a problem with CSS.</p>
<p>I have a parent <code>div</code> containing 2 or more children: one containing the name of a user that sits on top of the other children, and just below 1 or more side by side <code>div</code>s which display items owned by the user.</p>
<p>At the moment it works fine, but if the user's name (top <code>div</code>) is larger than the total width of the <code>div</code>s below, it will expand the parent <code>div</code>.</p>
<p>I'd like to only allow the bottom <code>div</code>s to expand the parent <code>div</code> and make the title <code>div</code> use the full parent <code>div</code>'s width without being able to make it larger.</p>
<p>I created a fiddle about it: <a href="http://jsfiddle.net/mLxjL/2/" rel="noreferrer">http://jsfiddle.net/mLxjL/2/</a></p>
<p>HTML: </p>
<pre><code><div class="matches">
<div class="match-container">
<div class="user-match-container">
<div class="match-owner user">You</div>
<div class="match">
<div class="thumbnail">
<img class="image-container" src="img-path">
<div class="thumbnail-count">2</div>
</div>
<div class="item-name">The Zeppelin of Consequence (Trading Card)</div>
</div>
</div> <span class="arrow">→</span>
<div class="user-match-container">
<div class="match-owner friend">PfaU- [W] King Arthurs Gold</div>
<div style="clear:both;"></div>
<div class="match">
<div class="thumbnail">
<img class="image-container" src="img-path">
<div class="thumbnail-count">2</div>
</div>
<div class="item-name">The Lost Hobo King</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.match-container:before, .match-container:after {
content:"";
display:table;
}
.match-container:after {
clear:both;
}
.match-container {
border:1px solid #666;
background-image:url('img/stripes.png');
border-radius:5px;
padding:10px;
margin:10px;
float:left;
}
.match {
width:112px;
float:left;
margin: 0 2px;
}
.match .image-container {
width:112px;
height:130px;
display:block;
}
.match .item-name {
line-height:12px;
font-size:10px;
margin-top:4px;
text-align:center;
height:24px;
overflow:hidden;
clear:both;
}
.match-container .arrow {
float:left;
position:relative;
top:70px;
margin:5px;
}
.match-owner {
line-height:14px;
font-size:12px;
margin-top:4px;
text-align:center;
height:14px;
overflow:hidden;
margin-bottom:4px;
border:1px solid #666;
background-image:url('img/stripes.png');
border-radius:5px;
}
.match-owner.user {
background-color:green;
}
.match-owner.friend {
background-color:red;
}
.thumbnail-count {
position:relative;
top:-24px;
margin-bottom:-24px;
font-size:16px;
font-weight:bold;
border-top:1px solid white;
border-right:1px solid white;
border-top-right-radius: 7px;
font-size:18px;
background: rgb(160, 160, 160) transparent;
background: rgba(160, 160, 160, 0.70);
padding: 0 4px;
float:left;
}
.user-match-container {
float:left;
}
</code></pre>
<p>Is it possible to do this without using JavaScript?</p> | 20,994,123 | 2 | 4 | null | 2014-01-08 11:11:59.517 UTC | 5 | 2021-11-18 22:01:43.583 UTC | 2018-12-17 21:55:40.903 UTC | null | 3,345,644 | null | 3,172,899 | null | 1 | 60 | css | 61,276 | <p>You can use <strong>Absolute positioning</strong></p>
<p><strong><a href="http://jsfiddle.net/chadocat/mLxjL/15/" rel="noreferrer">FIDDLE</a></strong></p>
<pre><code>position:absolute;
top:0;
left:0;
width:100%;
</code></pre>
<p>and on the container div :</p>
<pre><code>padding-top: /*the height of the absolutly positioned child*/ ;
position:relative;
</code></pre> |
21,078,445 | Find connected components in a graph | <p>If I have an undirected graph (implemented as a list of vertices), how can I find its connected components? How can I use quick-union?</p> | 21,078,752 | 2 | 5 | null | 2014-01-12 18:15:11.073 UTC | 15 | 2016-12-21 03:42:13.653 UTC | 2016-12-21 03:42:13.653 UTC | null | 880,772 | null | 3,187,921 | null | 1 | 45 | algorithm|graph | 55,798 | <p>Use depth-first search (DFS) to mark all individual connected components as visited:</p>
<pre><code>dfs(node u)
for each node v connected to u :
if v is not visited :
visited[v] = true
dfs(v)
for each node u:
if u is not visited :
visited[u] = true
connected_component += 1
dfs(u)
</code></pre>
<p>The best way is to use this straightforward method which is linear time O(n).<br>
Since you asked about the union-find algorithm:</p>
<pre><code>for each node parent[node] = node
for each node u :
for each node v connected to u :
if findset(u)!=findset(v) :
union(u,v)
**I assume you know about how findset and union works **
for each node if (parent[node] == node)
connected_component += 1
</code></pre> |
33,412,974 | How to uninstall a package installed with pip install --user | <p>There is a <code>--user</code> option for pip which can install a Python package per user:</p>
<pre><code>pip install --user [python-package-name]
</code></pre>
<p>I used this option to install a package on a server for which I do not have root access. What I need now is to uninstall the installed package on the current user. I tried to execute this command:</p>
<pre><code>pip uninstall --user [python-package-name]
</code></pre>
<p>But I got:</p>
<pre><code>no such option: --user
</code></pre>
<p>How can I uninstall a package that I installed with <code>pip install --user</code>, other than manually finding and deleting the package?</p>
<p>I've found this article </p>
<p><a href="https://stackoverflow.com/questions/33412974/uninstall-python-package-per-user">pip cannot uninstall from per-user site-packages directory</a></p>
<p>which describes that uninstalling packages from user directory does not supported. According to the article if it was implemented correctly then with</p>
<pre><code>pip uninstall [package-name]
</code></pre>
<p>the package that was installed will be also searched in user directories. But a problem still remains for me. What if the same package was installed both system-wide and per-user?
What if someone needs to target a specific user directory?</p> | 35,524,522 | 7 | 5 | null | 2015-10-29 11:27:43.79 UTC | 67 | 2021-06-11 17:33:53.48 UTC | 2019-07-09 08:34:33.76 UTC | null | 2,303,761 | null | 546,822 | null | 1 | 279 | python|python-3.x|pip|virtualenv | 489,505 | <p>Having tested this using Python 3.5 and pip 7.1.2 on Linux, the situation appears to be this:</p>
<ul>
<li><p><code>pip install --user somepackage</code> installs to <code>$HOME/.local</code>, and uninstalling it does work using <code>pip uninstall somepackage</code>.</p></li>
<li><p>This is true whether or not <code>somepackage</code> is also installed system-wide at the same time.</p></li>
<li><p>If the package is installed at both places, only the local one will be uninstalled. To uninstall the package system-wide using <code>pip</code>, first uninstall it locally, then run the same uninstall command again, with <code>root</code> privileges.</p></li>
<li><p>In addition to the predefined user install directory, <code>pip install --target somedir somepackage</code> will install the package into <code>somedir</code>. There is no way to uninstall a package from such a place using <code>pip</code>. (But there is a somewhat old unmerged pull request on Github that implements <code>pip uninstall --target</code>.)</p></li>
<li><p>Since the only places <code>pip</code> will ever uninstall from are system-wide and predefined user-local, you need to run <code>pip uninstall</code> as the respective user to uninstall from a given user's local install directory.</p></li>
</ul> |
1,664,402 | How can I specify per-face colors when using indexed vertex arrays in OpenGL 3.x? | <p>I'm trying to render a cube using an array of 8 vertices and an index-array of 24 (4<code>*</code>6) indices into the vertex array. But how can I specify <em>per-face</em> variables, like colors and normals without using deprecated functions? For this I need a separate set of indices, but when I specify two index-arrays (<code>GL_ELEMENT_ARRAY_BUFFERs</code>) and point them to different shader-variables (with two calls to glVertexAttribPointer) something goes wrong, and it doesn't render anything (but doesn't report any errors either - checked with glGetError). Do I have to use different calls to glDrawElements for each face, with color and normal loaded into uniform variables? </p>
<p>To clarify, the problem arises when each of the 8 vertices are part of different faces and need different values for color and normal.</p> | 1,666,059 | 5 | 0 | null | 2009-11-02 23:39:43.113 UTC | 15 | 2020-08-16 07:24:12.613 UTC | null | null | null | null | 178,419 | null | 1 | 28 | opengl | 17,946 | <p>The actual answer first:<br>
See Goz's answer. Keep 24 separate vertices.</p>
<p>Some nomenclature second:<br>
A Vertex is a set of vertex attributes. Please keep that distinction in mind when reading the following:</p>
<p>You have a misconception that using deprecated APIs would help you solve the issue. This is not the case. OpenGL handles (and has always handled) each vertex as a unique set of attributes. If you read the original spec carefully, you'll notice that when doing:</p>
<pre><code>glNormal()
glVertex()
glVertex()
glVertex()
</code></pre>
<p>The specification clearly states that <code>glNormal</code> sets the <code>current normal state</code>, and that <code>glVertex</code> <strong>provokes</strong> a new vertex, copying in passing all the <code>current state</code>, including the <code>current normal state</code>. That is, even though you passed only one Normal, the GL still sees 3.</p>
<p>The GL, therefore, does not have "per-face" attributes. </p>
<p>Also, you're mixing index arrays <code>GL_ELEMENT_ARRAY_BUFFER</code>, that are used from <code>glDrawElements(..., pointer)</code>, where <code>pointer</code> is an offset inside the index array, and vertex attribute arrays <code>GL_ARRAY_BUFFER</code>, that are used from <code>glVertexAttribPointer</code> (and all the deprecated <code>glVertexPointer/glNormalPointer</code>...</p>
<p>Each index that is in the index buffer will be used as an index into each of the attributes, but you can only specify a single index for each vertex. So, setting <code>GL_ELEMENT_ARRAY_BUFFER</code> and then calling <code>glVertexAttribPointer</code>, does not do at all what you think it does. It either uses the last array you set to <code>GL_ARRAY_BUFFER</code> for defining vertex attributes, or if you did not keep one bound, is interpreting your offset as a <strong>pointer</strong> (and will likely crash).</p>
<p>What you were trying to do, setting an index array for each vertex attribute, is not supported by GL. Let me restate this: <strong>you only have 1 index array per draw</strong>.</p>
<p>Some additional tidbits for the history enclined:</p>
<p>glVertex is a bit of a misnomer. It specifies only the Vertex <em>position</em>. But, and this is what it gets its name from, it also provokes a vertex to be passed to the GL. For the API to be completely clean, you could have imagined having to do 2 calls: </p>
<pre><code>// not valid code
glPosition(1,2,3); // specifies the current vertex position
glProvoke(); // pass the current vertex to GL
</code></pre>
<p>However, when GL was first specified, Position was always required, so fusing those 2 to provoke a vertex made sense (if only to reduce the API call count).</p>
<p>Fast forward to <a href="http://oss.sgi.com/projects/ogl-sample/registry/ARB/vertex_program.txt" rel="noreferrer"><code>vertex_program_arb</code></a>: Trying to get away from the fixed-function model while still remaining compatible meant that the special nature of glVertex had to be carried forward. This was achieved by making the <code>vertex attribute 0</code> provoking, and a synonym to glVertex.</p>
<p>Fast forward to GL3.2: the Begin/End model is gone, and all this specification of what provokes a vertex can <em>finally</em> go away, along with the management of the <code>current state</code>. So can all the semantic APIs (the glVertex*, glNormal*...), since all inputs are just vertex attributes now.</p> |
2,309,708 | Delegate: Method name expected error | <p>I'm trying to get the following simple Delegate example working. According to a book I've taken it from it should be ok, but I get a <code>Method name expected</code> error.</p>
<pre><code>namespace TestConsoleApp
{
class Program
{
private delegate string D();
static void Main(string[] args)
{
int x = 1;
D code = new D(x.ToString());
}
}
}
</code></pre>
<p>Any help?</p> | 2,309,714 | 6 | 0 | null | 2010-02-22 08:41:35.27 UTC | 1 | 2016-04-08 16:54:08.37 UTC | null | null | null | null | 42,636 | null | 1 | 15 | c#|delegates | 40,793 | <p>Remove the ():</p>
<pre><code>D code = new D(x.ToString);
</code></pre>
<p>You want to <strong>specify</strong> the method, not <strong>execute</strong> it.</p> |
1,523,482 | .vimrc configuration for Python | <p>My current .vimrc configuration is below:</p>
<pre><code>set nohlsearch
set ai
set bg=dark
set showmatch
highlight SpecialKey ctermfg=DarkGray
set listchars=tab:>-,trail:~
set list
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set smartindent
syntax on
set listchars=tab:>-
set listchars+=trail:.
set ignorecase
set smartcase
map <C-t><up> :tabr<cr>
map <C-t><down> :tabl<cr>
map <C-t><left> :tabp<cr>
map <C-t><right> :tabn<cr>
</code></pre>
<p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p> | 1,523,512 | 6 | 0 | null | 2009-10-06 03:45:54.82 UTC | 14 | 2019-04-18 14:58:09.1 UTC | 2009-10-28 19:22:31.607 UTC | null | 41,718 | null | 179,736 | null | 1 | 19 | python|vim | 32,201 | <p>The short answer is that your autocmd is missing the BufEnter trigger, so it isn't being fired when you create a new file. Try this instead:</p>
<pre><code> au BufEnter,BufRead *.py setlocal smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
</code></pre>
<p>Note that I also changed the <code>set</code> to <code>setlocal</code>. This'll prevent these options from stomping on your other buffers' options.</p>
<p>The "right" way to do what you're trying to do is to add <code>filetype indent on</code> to your .vimrc. This'll turn on the built-in filetype based indentation. Vim comes with Python indentation support. See <code>:help filetype-indent-on</code> for more info.</p> |
1,619,737 | Migrate project from RCS to git? | <p>I have a <a href="http://www.cs.tufts.edu/~nr/noweb/" rel="noreferrer">20-year-old project</a> that I would like to migrate from RCS to git, without losing the history. All web pages suggest that the One True Path is through CVS. But after an hour of Googling and trying different scripts, I have yet to find anything that <em>successfully</em> converts my RCS project tree to CVS. I'm hoping the good people at Stackoverflow will know what actually works, as opposed to what is claimed to work and doesn't.</p>
<p>(I searched Stackoverflow using both the native SO search and a Google search, but if there's a helpful answer in the database, I missed it.)</p>
<p><strong>UPDATE</strong>: The <code>rcs-fast-export</code> tool at <a href="http://git.oblomov.eu/rcs-fast-export" rel="noreferrer">http://git.oblomov.eu/rcs-fast-export</a> was repaired on 14 April 2009, and this version seems to work for me. This tool converts <em>straight</em> to git with no intermediate CVS. Thanks Giuseppe and Jakub!!!</p>
<hr>
<p>Things that did not work that I still remember:</p>
<ul>
<li><p>The <code>rcs-to-cvs</code> script that ships in the <code>contrib</code> directory of the CVS sources</p></li>
<li><p>The <code>rcs-fast-export</code> tool at <a href="http://git.oblomov.eu/rcs-fast-export" rel="noreferrer">http://git.oblomov.eu/rcs-fast-export</a> in versions before 13 April 2010</p></li>
<li><p>The <code>rcs2cvs</code> script found in a document called "CVS-RCS- HOW-TO Document for Linux"</p></li>
</ul> | 1,620,677 | 6 | 7 | null | 2009-10-25 02:01:08.393 UTC | 15 | 2022-08-29 02:08:51.157 UTC | 2012-02-03 09:12:38.25 UTC | null | 714,965 | null | 41,661 | null | 1 | 46 | git|migration|cvs|rcs | 12,648 | <p>See <a href="https://git.wiki.kernel.org/index.php/Interfaces,_frontends,_and_tools" rel="nofollow noreferrer">Interfaces, frontends, and tools</a> page on Git Wiki, in "Tools", "Interaction with other Revision Control Systems", "Other". There you would find a description and a link to <strong>rcs-fast-export</strong> (<a href="http://git.oblomov.eu/rcs-fast-export" rel="nofollow noreferrer">gitweb</a>) Ruby script by Giuseppe "Oblomov" Bilotta.</p>
<p><em>(Web search would find also Ohloh page and announcement for mentioned project)</em>.</p> |
1,525,928 | What Add-Ons / Utilities are available for TFS? | <p>I'm interested in knowing what high quality and useful add-ons or utilities are available for TFS. They can be commercial or open source. Of particular interest are any tools allowing visualisation of branches and tracking changesets as they are merged across branches (yes I know that the next version of TFS will be better in this area). A lot of the lists of TFS add-ins I found via google are quite dated and link to non-existent / abandoned projects.</p>
<p>I'll start the ball rolling with two we've found very useful:</p>
<ul>
<li><a href="http://www.codeplex.com/TFSBranchHistory" rel="noreferrer">TFS Branch History</a> is an add-in for Visual Studio allows you to view the history of an item going back before the last branch</li>
<li><a href="http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx" rel="noreferrer">TFS Power Tools</a> is a collection of TFS utilities from Microsoft including a command line tool that provides several useful features</li>
</ul> | 1,541,549 | 7 | 0 | null | 2009-10-06 14:27:15.913 UTC | 23 | 2013-12-10 07:33:47.52 UTC | 2013-12-10 07:33:47.52 UTC | null | 881,229 | null | 7,532 | null | 1 | 24 | tfs | 16,027 | <ul>
<li><a href="http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx" rel="nofollow noreferrer">TFS Power Tools</a> - collection of MS utilities has grown too large and too powerful to summarize here. Don't leave home without it!</li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=FAEB7636-644E-451A-90D4-7947217DA0E7&displaylang=en" rel="nofollow noreferrer">MSSCCI plugin</a> (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=87E1FFBD-A484-4C3A-8776-D560AB1E6198&displaylang=en" rel="nofollow noreferrer">2005 link</a>) - lets TFS work in a wide variety of IDEs that support the older MSSCCI [aka SourceSafe] standard, such as VB6, FoxPro, PowerBuilder, SQL Management Studio, etc</li>
<li><a href="http://www.teamprise.com/" rel="nofollow noreferrer">TeamPrise</a> ($$) - suite of TFS clients for Eclipse, Mac, Linux, mainframes (!), just about everything else that MS doesn't support natively</li>
<li><a href="http://www.attrice.info/cm/tfs/index.htm" rel="nofollow noreferrer">TFS Sidekicks</a> - suite of utilities was one of the very first 3rd party tools and continues to add features. Now supports UI queries on history, status, workspace, labels, shelvesets, permissions, team builds, and more -- much of it now integrated directly into VS.</li>
<li><a href="http://tfsadmin.codeplex.com/" rel="nofollow noreferrer">TFS Administration Tool</a> - easily synchronize permissions between core TFS services, Sharepoint, and SQL Reporting Services</li>
<li><a href="http://migrationsynctoolkit.codeplex.com/" rel="nofollow noreferrer">Migration & Synchronization Toolkit</a> - framework for migrating from other ALM systems to TFS, including support for ongoing 2-way synchronization</li>
<li><a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=SvnBridge" rel="nofollow noreferrer">SvnBridge</a> - lets you use a SVN client against a TFS server, to appease the folks who just don't get it ;-)</li>
<li><a href="http://kdiff3.sourceforge.net/" rel="nofollow noreferrer">KDiff3</a> - best merge tool anywhere. See below for more options & instructions.</li>
<li><a href="http://www.codeplex.com/TFSCodeReviewFlow" rel="nofollow noreferrer">TFS Code Review Workflow</a> - just what it sounds like; uses shelvesets + work items + a checkin policy to formalize the code review process</li>
<li><a href="http://www.scrumforteamsystem.com/en/default.aspx" rel="nofollow noreferrer">Conchango SCRUM template & task board</a> - probably the most popular 3rd party Process Template, plus a ($$) dashboard product</li>
<li><a href="http://jelle.druyts.net/2007/12/09/SettingUpSourceServerForTFSBuilds.aspx" rel="nofollow noreferrer">Source Server for TFS</a> - get full source code indexing from your symbol server; now baked into the main WinDBG download, this link goes to a setup guide</li>
<li><a href="http://www.teamsystemsolutions.com/teamlook/teamlook-features.aspx" rel="nofollow noreferrer">TeamLook</a> ($$) - deep integration between Outlook and TFS work item tracking. Think JIRA on steroids, if you've ever used that product.</li>
<li><a href="http://www.telerik.com/products/tfsmanager-and-tfsdashboard.aspx" rel="nofollow noreferrer">TFS Work Item Manager and Dashboard</a> - very slick WPF replacement for the work item features of Team Explorer, plus a dashboard that comes with lots of reports aimed at replacing the canned ones on the stock Team Project Portal. Still in beta but demos look promising</li>
<li><a href="http://blogs.msdn.com/buckh/archive/2006/09/09/tfs-reporting.aspx" rel="nofollow noreferrer">Reporting Services Sample Pack</a> - large collection of reports to run against the stock process template, or use as an example for writing custom ones</li>
<li><a href="http://blogs.msdn.com/granth/archive/2009/02/03/announcing-tfs-performance-report-pack.aspx" rel="nofollow noreferrer">Performance Report Pack</a> - another report package, this time aimed at studying TFS performance</li>
<li><a href="http://msbuildextensionpack.codeplex.com/" rel="nofollow noreferrer">MSBuild Extension Pack</a> - make customizing your Team Builds somewhat less frustrating</li>
<li><a href="http://msbuildtasks.tigris.org/" rel="nofollow noreferrer">MSBuild Community Tasks</a> - ditto</li>
<li><a href="http://www.attrice.info/msbuild/index.htm" rel="nofollow noreferrer">MSBuild SideKick</a> ($$) - IDE and debugger for Team Build scripts</li>
</ul>
<p>Even more complete (but old) list: <a href="http://blogs.msdn.com/davidmcg/archive/2007/03/09/team-foundation-server-tools.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/davidmcg/archive/2007/03/09/team-foundation-server-tools.aspx</a></p>
<p>List of merge tools + settings: <a href="http://blogs.msdn.com/jmanning/articles/535573.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jmanning/articles/535573.aspx</a></p>
<p>Some frequently requested checkin policies: </p>
<ul>
<li>"Custom Path", "Changeset Comments", "Forbidden Patterns", and "Work Item Query" policies are all part of the <a href="http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx" rel="nofollow noreferrer">official Power Tools</a> now</li>
<li><a href="http://logsubstpol.codeplex.com/" rel="nofollow noreferrer">Keyword expansion</a></li>
<li><a href="http://leon.mvps.org/Tfs/MergeOnlyPolicy.html" rel="nofollow noreferrer">Branch/Merge only</a></li>
<li><a href="http://teamfoundation.blogspot.com/2008/05/source-analysis-for-c-checkin-policy.html" rel="nofollow noreferrer">Source Analysis</a></li>
<li><a href="http://blogs.msdn.com/csell/archive/2006/10/27/build-status-tfs-policy-part-ii.aspx" rel="nofollow noreferrer">Build Status</a></li>
<li><a href="http://www.codeplex.com/timethattask" rel="nofollow noreferrer">Time That Task</a></li>
</ul> |
1,572,934 | Where to store an application log file on Windows | <p>Where would be the best "standard" place to put an application's debug log file in a Windows user environment?</p>
<p>In this particular case, it is an application that is run once and could go wrong. It will be run by system administrator types who may need to inspect the log after the application is run. Everytime the application is run, a new log file is created.</p>
<p>Options that have been floated so far include:</p>
<ol>
<li>The program directory</li>
<li>The user's desktop</li>
<li>The user's local Application Data directory.</li>
</ol>
<p>I have my favourite, but I wondered what the SO consensus was.</p>
<p>Note: this is similar to <a href="https://stackoverflow.com/questions/465785/best-location-for-exception-log-files-windows">this question</a>, but we're dealing with an application that's only likely to be run once by one user. </p> | 1,573,094 | 7 | 3 | null | 2009-10-15 14:57:21.773 UTC | 6 | 2019-03-03 23:30:29.383 UTC | 2017-05-23 12:10:08.02 UTC | null | -1 | null | 5,062 | null | 1 | 39 | windows|logging | 32,672 | <p>The Application Data directory would seem to be the perfect place, but it's an area that is nearly invisible. You need to give your users an easy way to get to it.</p>
<p>Have your installation script create a Log folder in the Application Data area for your program, and include a link to the folder in your Start menu.</p> |
2,298,165 | Is there a module for balanced binary tree in Python's standard library? | <p>Is there a module for an <a href="https://en.wikipedia.org/wiki/AVL_tree" rel="noreferrer">AVL tree</a> or a <a href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="noreferrer">red–black tree</a> or some other type of a balanced binary tree in the standard library of Python?</p> | 2,298,316 | 7 | 5 | null | 2010-02-19 17:06:42.147 UTC | 20 | 2020-06-24 19:32:26.937 UTC | 2020-03-31 08:25:46.933 UTC | null | 562,769 | null | 160,992 | null | 1 | 97 | python|tree|standard-library | 53,932 | <p>No, there is not a balanced binary tree in the stdlib. However, from your comments, it sounds like you may have some other options:</p>
<ul>
<li>You say that you want a BST instead of a list for <code>O(log n)</code> searches. If searching is all you need and your data are already sorted, the <code>bisect</code> module provides a binary search algorithm for lists.</li>
<li>Mike DeSimone recommended sets and dicts and you explained why lists are too algorithmically slow. Sets and dicts are implemented as hash tables, which have O(1) lookup. The solution to most problems in Python really is "use a dict".</li>
</ul>
<p>If neither solution works well for you, you'll have to go to a third party module or implement your own.</p> |
1,409,543 | Using SAS Macro to pipe a list of filenames from a Windows directory | <p>I am trying to amend the macro below to accept a macro parameter as the 'location' argument for a dir command. However I cannot get it to resolve correctly due to the nested quotes issue. Using %str(%') does not work, neither do quoting functions for some reason.</p>
<p>The macro will work fine when the filepath has <strong>no spaces</strong> (eg C:\temp\withnospace) as the middle quotes aren't needed. However I need this macro to work for filepaths <strong>with spaces</strong> (eg 'C:\temp\with space\').</p>
<p>Please help! </p>
<pre><code>%macro get_filenames(location)
filename pipedir pipe "dir &location. /b " lrecl=32767;
data filenames;
infile pipedir truncover;
input line $char1000.;
run;
%mend;
%get_filenames(C:\temp\) /* works */
%get_filenames('C:\temp\with space') /* doesnt work */
</code></pre> | 1,412,947 | 8 | 0 | null | 2009-09-11 07:49:12.58 UTC | 4 | 2012-01-24 18:37:26.58 UTC | 2009-09-11 12:04:07.373 UTC | null | 66,696 | null | 66,696 | null | 1 | 7 | sas|pipe|sas-macro|dir|file-io | 43,102 | <p>Here's another way of achieving the same result without needing to use a PIPE. </p>
<pre><code>%macro get_filenames(location);
filename _dir_ "%bquote(&location.)";
data filenames(keep=memname);
handle=dopen( '_dir_' );
if handle > 0 then do;
count=dnum(handle);
do i=1 to count;
memname=dread(handle,i);
output filenames;
end;
end;
rc=dclose(handle);
run;
filename _dir_ clear;
%mend;
%get_filenames(C:\temp\);
%get_filenames(C:\temp\with space);
%get_filenames(%bquote(C:\temp\with'singlequote));
</code></pre> |
2,230,286 | Unit Testing or Functional Testing? | <p>I have recently heard of Functional Testing over Unit Testing.</p>
<p>I understand that Unit Testing tests each of the possibilities of a given piece of code from its most atomic form. But what about Functional Testing?</p>
<p>This sounds to me like only testing if the code works, but is it as reliable as Unit Testing?</p>
<p>I've been told there was two school of thoughts for the matter. Certains would prefer Unit Testing, others Functional Testing.</p>
<p>Is there any good resources, links, books, any references or one of you all who can explain and elighten my path on the subject?</p>
<p>Thanks!</p> | 2,230,616 | 8 | 3 | null | 2010-02-09 15:44:40.487 UTC | 17 | 2012-11-30 05:15:15.323 UTC | null | null | null | null | 162,167 | null | 1 | 28 | .net|unit-testing|functional-testing|testdrivendesign | 6,546 | <p>Jason's answer is correct. Different types of tests have different purposes, and can be layered for best results (good design, meeting specifications, reduced defects).</p>
<ul>
<li>Unit testing = drives design (with <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">Test-Driven Development</a>, or TDD)</li>
<li>Integration testing = do all the pieces work together</li>
<li>Customer acceptance testing = does it meet the customer's requirements</li>
<li>Manual testing = often covers the UI; dedicated testers can find what automation misses</li>
<li>Load testing = how well does the system perform with realistic amounts of data</li>
</ul>
<p>There is some overlap between these categories; unit tests can specify behavior, for instance.</p>
<p>And there are others; for more than most people care to know, see <a href="http://en.wikipedia.org/wiki/Software_testing" rel="noreferrer">Software Testing</a>.</p>
<p>One point people missed is that unit testing is testing pieces of code <strong>in isolation</strong>. Good unit tests don't hit the database, for instance. This has two advantages: it makes the tests run fast so you'll run them more often, and it forces you to write loosely coupled classes (better design).</p>
<p>You asked for resources; I recommend Roy Osherove's book <a href="http://www.manning.com/osherove/" rel="noreferrer">The Art of Unit Testing with Examples in .NET</a>. While no book is perfect, this one gives many excellent pointers on writing good tests.</p>
<p>EDIT: And for writing tests against existing software, nothing beats Michael Feathers' book <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="noreferrer" rel="nofollow noreferrer">Working Effectively with Legacy Code</a>.</p> |
1,528,525 | Alternatives to System.Drawing for use with ASP.NET? | <p>After several days of tracking down bizarre GDI+ errors, I've stumbled across this little gem on <a href="http://msdn.microsoft.com/en-us/library/system.drawing.aspx" rel="nofollow noreferrer">MSDN</a>:</p>
<blockquote>
<p>Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions.</p>
</blockquote>
<p>I don't know whether "ASP.NET service" means "web application" in this context, but "diminished service performance" certainly seems to cover the random assortment of "A generic error occurred in GDI+" and "Out of memory" errors that my app is throwing - intermittent, non-reproducible errors reading and writing JPEG images that - in many cases - were actually created by System.Drawing.Imaging in the first place.</p>
<p><strong>So - if GDI+ can't read and write JPEG files reliably in a Web app, what should I be using instead?</strong> </p>
<p>I want users to be able to upload images (JPEG required, other formats nice-to-have), resample them <em>reliably</em>, and display useful error messages if anything goes wrong. Any ideas? Are the System.Media namespaces from WPF worth considering?</p>
<p><strong>EDIT:</strong> Yeah, I know GDI+ works "most of the time". That's not good enough, because when it fails, it does so in a way that's impossible to isolate or recover from gracefully. I am not interested in examples of GDI+ code that works for you: I am looking for <strong>alternative libraries to use for image processing.</strong></p> | 11,991,193 | 8 | 2 | null | 2009-10-06 22:56:26.103 UTC | 20 | 2020-11-07 07:09:44.12 UTC | 2018-12-24 08:29:45.153 UTC | null | 107,625 | null | 5,017 | null | 1 | 34 | c#|asp.net|gdi+|system.drawing|system.drawing.imaging | 18,917 | <p>There is an excellent blog post including C# code about using the <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick graphics library</a> through Interop over at <a href="http://www.toptensoftware.com/Articles/17/High-Quality-Image-Resampling-in-Mono-Linux" rel="nofollow noreferrer">TopTen Software Blog</a>. This post deals specifically with running ASP.net on linux under mono; however, the C# code should be perfectly copy-paste-able, the only thing you'll need to change is the Interop attributes if you are running under windows referencing a window binary (DLL).</p>
<blockquote>
<p>ImageMagick® is a software suite to create, edit, compose, or convert
bitmap images. It can read and write images in a variety of formats
(over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD,
PNG, Postscript, SVG, and TIFF. Use ImageMagick to resize, flip,
mirror, rotate, distort, shear and transform images, adjust image
colors, apply various special effects, or draw text, lines, polygons,
ellipses and Bézier curves.</p>
</blockquote>
<p>There is also an <a href="http://imagemagick.codeplex.com/" rel="nofollow noreferrer">ImageMagick .Net development project</a> on codeplex that wraps up everything for you. But it doesn't show active development since 2009, so it may be lagging behind the current ImageMagick library version. For a small trivial resizing routine, I'd probably stick with the interop. You just need to watch your implementation carefully for your own memory leak or unreleased resources (the library itself is well tested and vetted by the community).</p>
<p>The library is free and open source. The Apache 2 license appears to be compatible with both personal and commercial purposes. See <a href="http://www.imagemagick.org/script/license.php" rel="nofollow noreferrer">ImageMagick License Page</a>.</p>
<p>The library is totally cross platform and implements many powerful image handling and transformation routines that are not found in GDI+ (or not implemented under mono) and has a good reputation as an alternative for ASP.net image processing.</p>
<p>Update: Looks like there is an updated version of a .NET wrapper here: <a href="http://magick.codeplex.com/" rel="nofollow noreferrer">http://magick.codeplex.com/</a></p> |
1,674,742 | Intersection of multiple lists with IEnumerable.Intersect() | <p>I have a list of lists which I want to find the intersection for like this:</p>
<pre><code>var list1 = new List<int>() { 1, 2, 3 };
var list2 = new List<int>() { 2, 3, 4 };
var list3 = new List<int>() { 3, 4, 5 };
var listOfLists = new List<List<int>>() { list1, list2, list3 };
// expected intersection is List<int>() { 3 };
</code></pre>
<p>Is there some way to do this with IEnumerable.Intersect()?</p>
<p>EDIT:
I should have been more clear on this: I really have a list of lists, I don't know how many there will be, the three lists above was just an example, what I have is actually an <code>IEnumerable<IEnumerable<SomeClass>></code></p>
<h2>SOLUTION</h2>
<p>Thanks for all great answers. It turned out there were four options for solving this: <strong>List+aggregate</strong> (@Marcel Gosselin), <strong>List+foreach</strong> (@JaredPar, @Gabe Moothart), <strong>HashSet+aggregate</strong> (@jesperll) and <strong>HashSet+foreach</strong> (@Tony the Pony). I did some performance testing on these solutions (varying <strong>number of lists</strong>, <strong>number of elements</strong> in each list and <strong>random number max</strong> size.</p>
<p>It turns out that for most situations the HashSet performs better than the List (except with large lists and small random number size, because of the nature of HashSet I guess.)
I couldn't find any real difference between the foreach method and the aggregate method (the foreach method performs <em>slightly</em> better.)</p>
<p>To me, the aggregate method is really appealing (and I'm going with that as the accepted answer) but I wouldn't say it's the most readable solution.. Thanks again all!</p> | 1,676,684 | 8 | 0 | null | 2009-11-04 15:56:16.797 UTC | 28 | 2017-10-12 15:14:14.007 UTC | 2009-11-05 08:52:55.64 UTC | null | 83,111 | null | 83,111 | null | 1 | 97 | c#|.net|linq | 41,220 | <p>How about:</p>
<pre><code>var intersection = listOfLists
.Skip(1)
.Aggregate(
new HashSet<T>(listOfLists.First()),
(h, e) => { h.IntersectWith(e); return h; }
);
</code></pre>
<p>That way it's optimized by using the same HashSet throughout and still in a single statement. Just make sure that the listOfLists always contains at least one list.</p> |
1,739,706 | How to insert an item at the beginning of an array in PHP? | <p>I know how to insert it to the end by:</p>
<pre><code>$arr[] = $item;
</code></pre>
<p>But how to insert it to the beginning?</p> | 1,739,717 | 8 | 3 | null | 2009-11-16 02:17:18.157 UTC | 19 | 2022-09-14 16:34:56.647 UTC | 2018-05-16 00:20:58.833 UTC | null | 4,974,784 | null | 211,732 | null | 1 | 249 | php|arrays | 218,336 | <p>Use <a href="http://php.net/manual/en/function.array-unshift.php" rel="noreferrer">array_unshift($array, $item);</a></p>
<pre><code>$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);
</code></pre>
<p>will give you</p>
<pre><code>Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
</code></pre> |
1,832,290 | Android id naming convention: lower case with underscore vs. camel case | <p>I'm currently programming an application for the Android. Now what I found out is that you cannot place resource objects, say, an image in the drawable folder and name it like "myTestImage.jpg". This will give you a compiler error since camel case syntax is not allowed, so you'd have to rename it like "my_test_image.jpg".</p>
<p>But what about ids you define in the XML file. Say you have the following definition</p>
<pre><code><TextView android:id="@+id/myTextViewFirstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Firstname" />
</code></pre>
<p>This is a valid definition, compiles and works just fine on my Android emulator although - as you see - I'm specifying the id in camel case syntax.</p>
<p>Now, the Android samples always use lower case and underscore. Is this just a naming convention to use lower case with underscore for the id's or may it cause problems on the real device?</p>
<p>Thx</p> | 1,833,639 | 9 | 1 | null | 2009-12-02 11:17:37.583 UTC | 23 | 2022-03-10 05:47:25.963 UTC | 2013-03-16 03:14:18.63 UTC | null | 918,414 | null | 50,109 | null | 1 | 97 | android|mobile | 49,027 | <p>The device will not complain if you use camel-case id names. For my first application I wrote all the ids in camel-case because I think it appears better in the Java code that way, and it works just fine.</p>
<p>I am slowly changing my mind on camel-case, though, because you end up with two different naming conventions - for example:</p>
<pre><code>// This must be undescored due to naming constrictions
setContentView(R.layout.my_long_layout_name);
// Now this looks a little out of place
findViewById(R.id.myLongSpecificId);
</code></pre>
<p>I, too, wonder about the standards here. Google is inconsistent in their examples; sometimes they use all lowercase, sometimes they insert underscores, and sometimes they use camel-case.</p> |
2,213,627 | When you exit a C application, is the malloc-ed memory automatically freed? | <p>Let's say I have the following C code:</p>
<pre><code>int main () {
int *p = malloc(10 * sizeof *p);
*p = 42;
return 0; //Exiting without freeing the allocated memory
}
</code></pre>
<p>When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates? </p> | 2,213,644 | 9 | 2 | null | 2010-02-06 15:37:21.79 UTC | 34 | 2015-10-13 17:27:53.17 UTC | null | null | null | null | 44,084 | null | 1 | 111 | c|memory-management | 42,578 | <p>It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.</p>
<p>Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.<br>
Relying on a feature of an operating system also makes the code less portable.</p> |
2,110,732 | How to get name of calling function/method in PHP? | <p>I am aware of function <code>debug_backtrace</code>, but I am looking for some ready to use implementation of function like <code>GetCallingMethodName()</code>? It would be perfect if it gave method's class too (if it is indeed a method).</p> | 2,110,758 | 10 | 1 | null | 2010-01-21 16:10:17.39 UTC | 66 | 2022-03-28 10:24:14.31 UTC | 2020-01-30 13:49:23.477 UTC | null | 2,753,501 | null | 239,129 | null | 1 | 273 | php|debugging|backtrace|method-call | 278,889 | <p>The <code>debug_backtrace()</code> function is the only way to know this, if you're lazy it's one more reason you should code the <code>GetCallingMethodName()</code> yourself. <strong>Fight the laziness! :D</strong></p> |
1,361,437 | JavaScript equivalent of PHP’s die | <p>Is there something like "die" in JavaScript? I've tried with "break", but doesn't work :)</p> | 1,365,521 | 14 | 7 | null | 2009-09-01 09:18:03.927 UTC | 26 | 2022-01-07 12:16:04.883 UTC | null | null | null | null | 115,201 | null | 1 | 125 | javascript | 157,904 | <p>You can only <code>break</code> a block scope if you label it. For example:</p>
<pre><code>myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
</code></pre>
<p>You cannot break a block scope from within a function in the scope. This means you can't do stuff like:</p>
<pre><code>foo: { // this doesn't work
(function() {
break foo;
}());
}
</code></pre>
<p>You can do something similar though with functions:</p>
<pre><code>function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
</code></pre> |
33,700,580 | Laravel 5 Application Key | <p>I am new to Laravel. I just started it tonight. Actually, I have the following code: </p>
<pre><code>'key' => env('APP_KEY', 'SomeRandomString'),
</code></pre>
<p>In <em>xampp/htdocs/laravel/blog/config/app.php</em>.<br>
I want to change this key to 32-bit by cmd as:</p>
<pre><code>xampp\htdocs\laravel/blog>php artisan key:generate
</code></pre>
<p>It generates the key but could not replace/update in <em>xampp/htdocs/laravel/blog/config/app.php</em>.</p> | 33,701,687 | 5 | 3 | null | 2015-11-13 19:40:06.467 UTC | 16 | 2020-04-05 08:31:52.527 UTC | 2019-03-23 08:42:59.57 UTC | null | 9,331,166 | null | 3,528,332 | null | 1 | 90 | php|laravel|laravel-5.1 | 276,992 | <p>This line in your <code>app.php</code>, <code>'key' => env('APP_KEY', 'SomeRandomString'),</code>, is saying that the key for your application can be found in your <code>.env</code> file on the line <code>APP_KEY</code>.</p>
<p>Basically it tells Laravel to look for the key in the <code>.env</code> file first and if there isn't one there then to use <code>'SomeRandomString'</code>.</p>
<p>When you use the <code>php artisan key:generate</code> it will generate the new key to your <code>.env</code> file and not the <code>app.php</code> file.</p>
<p><em>As kotapeter said, your <code>.env</code> will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog</em></p> |
8,428,422 | Detect an MSISDN (mobile number) with the browser | <p>Are there any HTTP headers one can use to detect a mobile users number other than this X-header <code>x-up-calling-line-id</code> ?</p>
<p>I want to detect from all browsers as much as possible to cover all platform mobiles.</p> | 11,152,022 | 3 | 2 | null | 2011-12-08 08:53:59.3 UTC | 11 | 2019-11-14 19:29:59.29 UTC | 2012-09-10 07:09:10.397 UTC | null | 618,172 | null | 751,689 | null | 1 | 13 | mobile|phone-number|msisdn | 54,156 | <p>I will give you the exact same answer I gave to a very similar question as it should provide some insight into what you are trying to achieve.</p>
<p>The ability to get the MSISDN of the user visiting the WAP site depends on a number of things.</p>
<p>Firstly, the user has to be on Mobile Data. If the user is on WiFi then you will not receive this information.</p>
<p>Secondly, the users mobile network has to support the passing of the MSISDN in the HTTP headers.</p>
<p>Some mobile networks send headers on all requests. Others only send if going through a specific APN. Some only send this header to specific IP addresses/blocks. I have even come across networks that send the MSISDN as a $_GET variable. You will need to check with each network that you intend to support.</p>
<p>For example, a particular network in South Africa used to send MSISDNs in headers until around 6 months ago, and in order to receive the MSISDN in the headers now your server address needs to be whitelisted with them.</p>
<p>Also remember that headers are very easy to spoof, and shouldn't be relied on unless you are guaranteed that you are the originator of the HTTP request, such as in instances where you are using Web Views inside of Android Applications - you would need to put sufficient measures in place yourself.</p>
<p>With all of that in mind, here is what you should be looking for:</p>
<p>Look through your headers for any of the following. This is not a comprehensive list of MSISDN headers at all, they are only the ones I have come across in my adventures in mobile development.</p>
<ul>
<li>X-MSISDN</li>
<li>X_MSISDN</li>
<li>HTTP_X_MSISDN</li>
<li>X-UP-CALLING-LINE-ID</li>
<li>X_UP_CALLING_LINE_ID</li>
<li>HTTP_X_UP_CALLING_LINE_ID</li>
<li>X_WAP_NETWORK_CLIENT_MSISDN</li>
</ul>
<p>What I do is run through the headers looking for any matches. If I don't find any matches I run through the headers again using a country-specific MSISDN regex against the values to see if there are any potential MSISDNs in the headers on keys that I do not know about. If I find a potential match I add the key and data to a list that I can go through later in order to add to my list of known MSISDN headers.</p>
<p>I hope this has bought some clarity. What is most important to remember is that this is not a reliable method for getting an MSISDN.</p> |
18,065,807 | Regular expression for removing whitespaces | <p>I have some text which looks like this - </p>
<pre><code>" tushar is a good boy "
</code></pre>
<p>Using javascript I want to remove all the extra white spaces in a string. </p>
<p>The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this - </p>
<pre><code>"tushar is a good boy"
</code></pre>
<p>I am using the following code at the moment- </p>
<pre><code>str.replace(/(\s\s\s*)/g, ' ')
</code></pre>
<p>This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.</p> | 18,066,013 | 7 | 6 | null | 2013-08-05 19:07:45.327 UTC | 9 | 2021-07-04 18:55:40.283 UTC | null | null | null | null | 1,040,006 | null | 1 | 22 | javascript|regex | 81,532 | <p>This can be done in a single <code>String#replace</code> call:</p>
<pre><code>var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
</code></pre> |
6,533,610 | Android Gmail app-Mail Attachment URI issue | <p>I have to open attachment file from gmail app thru my app.</p>
<p>I get link in pattern like <em>content://gmail-ls/messages/mailid%40gmail.com/4/attachments/0.1/BEST/false</em></p>
<p>My problem is the link is not unique for each file in the mail client..
One or more file has same <em>Uri</em>.</p>
<p>Is there any way to get the file name or email sent date so that I can come over this issue.</p>
<p>Thanks in advance.</p> | 6,936,224 | 4 | 0 | null | 2011-06-30 10:49:47.44 UTC | 1 | 2019-03-26 08:24:04.827 UTC | 2011-06-30 10:58:17.497 UTC | null | 390,177 | null | 286,831 | null | 1 | 5 | android|gmail | 44,282 | <p>I resolved this issue in an indirect way.</p>
<p>I identified the uniqueness using the file size.</p>
<p>In-case if you need the code here it is</p>
<pre><code>InputStream is = getContentResolver().openInputStream(uri);
FILE_SIZE=is.available();
</code></pre> |
23,461,713 | Obtaining values used in boxplot, using python and matplotlib | <p>I can draw a boxplot from data:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(100)
plt.boxplot(data)
</code></pre>
<p>Then, the box will range from the 25th-percentile to 75th-percentile, and the whisker will range from the smallest value to the largest value between (<code>25th-percentile - 1.5*IQR, 75th-percentile + 1.5*IQR</code>), where the IQR denotes the inter-quartile range. (Of course, the value 1.5 is customizable).</p>
<p>Now I want to know the values used in the boxplot, i.e. the median, upper and lower quartile, the upper whisker end point and the lower whisker end point. While the former three are easy to obtain by using <code>np.median()</code> and <code>np.percentile()</code>, the end point of the whiskers will require some verbose coding:</p>
<pre><code>median = np.median(data)
upper_quartile = np.percentile(data, 75)
lower_quartile = np.percentile(data, 25)
iqr = upper_quartile - lower_quartile
upper_whisker = data[data<=upper_quartile+1.5*iqr].max()
lower_whisker = data[data>=lower_quartile-1.5*iqr].min()
</code></pre>
<p>I was wondering, while this is acceptable, would there be a neater way to do this? It seems that the values should be ready to pull-out from the boxplot, as it's already drawn.</p> | 23,462,659 | 3 | 2 | null | 2014-05-04 21:21:16.977 UTC | 10 | 2022-01-06 20:13:50.433 UTC | 2020-06-11 19:48:40.627 UTC | null | 7,758,804 | null | 2,203,311 | null | 1 | 28 | python|numpy|matplotlib|scipy | 50,077 | <p>Why do you want to do so? what you are doing is already pretty direct.</p>
<p>Yeah, if you want to fetch them for the plot, when the plot is already made, simply use the <code>get_ydata()</code> method.</p>
<pre><code>B = plt.boxplot(data)
[item.get_ydata() for item in B['whiskers']]
</code></pre>
<p>It returns an array of the shape (2,) for each whiskers, the second element is the value we want:</p>
<pre><code>[item.get_ydata()[1] for item in B['whiskers']]
</code></pre> |
18,800,727 | MS Access call SQL Server stored procedure | <p>I have an MS Access application that contains all tables linked to SQL Server, so in MS Access VBA code or query I work with those tables very simple, I access them via name, like <code>[Customers]</code>.</p>
<p>Also I have a stored procedure in SQL Server called <code>sp_CopyData</code> which I need to call from my VBA code. How can I do that without creating new connection to SQL Server (I already have it somewhere!? because I have access to tables)?</p>
<p>Or it's impossible? Appreciate any help. Thanks!</p> | 19,213,929 | 4 | 2 | null | 2013-09-14 10:24:12.163 UTC | 6 | 2022-04-07 07:29:37.167 UTC | 2013-09-14 10:49:00.443 UTC | null | 13,302 | null | 206,330 | null | 1 | 18 | sql-server|vba|ms-access|stored-procedures|ms-access-2007 | 76,257 | <p>The right answer found out, it should be like:</p>
<pre><code>Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("")
qdef.Connect = CurrentDb.TableDefs("[ANY LINKED TABLE TO MS SQL SERVER]").Connect
qdef.SQL = "EXEC sp_CopyData"
qdef.ReturnsRecords = False ''avoid 3065 error
qdef.Execute
</code></pre> |
5,595,956 | replace innerHTML in contenteditable div | <p>i need to implement highlight for numbers( in future im add more complex rules ) in the contenteditable div. The problem is When im insert new content with javascript replace, DOM changes and contenteditable div lost focus. What i need is keep focus on div with caret on the current position, so users can just type without any issues and my function simple highlighting numbers. Googling around i decide that <a href="http://code.google.com/p/rangy/" rel="noreferrer">Rangy</a> library is the best solution. I have following code:</p>
<pre><code>function formatText() {
var savedSel = rangy.saveSelection();
el = document.getElementById('pad');
el.innerHTML = el.innerHTML.replace(/(<([^>]+)>)/ig,"");
el.innerHTML = el.innerHTML.replace(/([0-9])/ig,"<font color='red'>$1</font>");
rangy.restoreSelection(savedSel);
}
<div contenteditable="true" id="pad" onkeyup="formatText();"></div>
</code></pre>
<p>The problem is after function end work focus is coming back to the div, but caret always point at the div begin and i can type anywhere, execept div begin. Also console.log types following <code>Rangy warning: Module SaveRestore: Marker element has been removed. Cannot restore selection.</code>
Please help me to implement this functional. Im open for another solutiona, not only rangy library. Thanks!</p>
<p><a href="http://jsfiddle.net/2rTA5/" rel="noreferrer">http://jsfiddle.net/2rTA5/</a> This is jsfiddle, but it dont work properly(nothing happens when i typed numbers into my div), dunno maybe it me (first time post code via jsfiddle) or resource doesnt support contenteditable.
UPD* Im read similar problems on stackoverflow, but solutions doesnt suit to my case :(</p> | 5,596,688 | 2 | 3 | null | 2011-04-08 13:41:41.797 UTC | 13 | 2017-06-27 20:28:00.683 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 595,701 | null | 1 | 10 | javascript|html|range|contenteditable|rangy | 15,266 | <p>The problem is that Rangy's save/restore selection module works by inserting invisible marker elements into the DOM where the selection boundaries are and then your code strips out all HTML tags, including Rangy's marker elements (as the error message suggests). You have two options:</p>
<ol>
<li>Move to a DOM traversal solution for colouring the numbers rather than <code>innerHTML</code>. This will be more reliable but more involved.</li>
<li>Implement an alternative character index-based selection save and restore. This would be generally fragile but will do what you want in this case.</li>
</ol>
<p><strong>UPDATE</strong></p>
<p>I've knocked up a character index-based selection save/restore for Rangy (option 2 above). It's a little rough, but it does the job for this case. It works by traversing text nodes. I may add this into Rangy in some form. (<strong>UPDATE 5 June 2012:</strong> <a href="https://github.com/timdown/rangy/blob/master/demos/textrange.html" rel="noreferrer">I've now implemented this, in a more reliable way, for Rangy.</a>)</p>
<p>jsFiddle: <a href="http://jsfiddle.net/2rTA5/2/" rel="noreferrer">http://jsfiddle.net/2rTA5/2/</a></p>
<p>Code:</p>
<pre><code>function saveSelection(containerEl) {
var charIndex = 0, start = 0, end = 0, foundStart = false, stop = {};
var sel = rangy.getSelection(), range;
function traverseTextNodes(node, range) {
if (node.nodeType == 3) {
if (!foundStart && node == range.startContainer) {
start = charIndex + range.startOffset;
foundStart = true;
}
if (foundStart && node == range.endContainer) {
end = charIndex + range.endOffset;
throw stop;
}
charIndex += node.length;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i], range);
}
}
}
if (sel.rangeCount) {
try {
traverseTextNodes(containerEl, sel.getRangeAt(0));
} catch (ex) {
if (ex != stop) {
throw ex;
}
}
}
return {
start: start,
end: end
};
}
function restoreSelection(containerEl, savedSel) {
var charIndex = 0, range = rangy.createRange(), foundStart = false, stop = {};
range.collapseToPoint(containerEl, 0);
function traverseTextNodes(node) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
throw stop;
}
charIndex = nextCharIndex;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i]);
}
}
}
try {
traverseTextNodes(containerEl);
} catch (ex) {
if (ex == stop) {
rangy.getSelection().setSingleRange(range);
} else {
throw ex;
}
}
}
function formatText() {
var el = document.getElementById('pad');
var savedSel = saveSelection(el);
el.innerHTML = el.innerHTML.replace(/(<([^>]+)>)/ig,"");
el.innerHTML = el.innerHTML.replace(/([0-9])/ig,"<font color='red'>$1</font>");
// Restore the original selection
restoreSelection(el, savedSel);
}
</code></pre> |
370,055 | Programmatically Switching Views in Cocoa Touch | <p>How would one change the view on the screen programmatically in an iPhone app?</p>
<p>I've been able to create navigation view's and programmatically push/pop them to produce this behaviour, but if I wanted to simply change the current view (not using a UINavigation controller object), what is the neatest way to achieve this?</p>
<p>A simple example, imagine an application with a single button, when pressed will display a new view, or possibly one of multiple views depending on some internal state variable.</p>
<p>I have yet to see any examples that attempt to do this, and I don't seem to understand enough about the relationships and initialisation procedure between UIViewController/UIView objects to achieve this programmatically.</p> | 370,390 | 7 | 1 | null | 2008-12-15 23:23:43.177 UTC | 10 | 2019-01-21 11:57:10.607 UTC | 2019-01-21 11:57:10.607 UTC | Akusete | 1,033,581 | Akusete | 40,175 | null | 1 | 7 | ios|objective-c|iphone|cocoa-touch | 6,537 | <p>I use <code>presentModalViewController:animated:</code> to bring up a settings view from my main window's <code>UIViewController</code> and then when the user presses "done" in the settings view I call <code>dismissModalViewControllerAnimated:</code> from the settings view (reaching back to the parent view) like this:</p>
<pre><code>[[self parentViewController] dismissModalViewControllerAnimated:YES];
</code></pre> |
710,675 | Is it possible to set the position of an UIImageView's image? | <p>I have a <code>UIImageView</code> that displays a bigger image. It appears to be centered, but I would like to move that image inside that <code>UIImageView</code>. I looked at the <a href="https://developer.apple.com/LIBRARY/IOS/samplecode/MoveMe/Introduction/Intro.html" rel="noreferrer">MoveMe</a> sample from Apple, but I couldn't figure out how they do it. It seems that they don't even have an UIImageView for that. Any ideas?</p> | 711,210 | 7 | 0 | null | 2009-04-02 17:09:57.52 UTC | 2 | 2021-04-12 07:43:28.973 UTC | 2013-11-01 08:53:19.547 UTC | null | 1,752,200 | Unknown Individual | 62,553 | null | 1 | 18 | iphone|image|uiimageview | 44,784 | <p>Original Answer has been superseded by CoreAnimation in iOS4.</p>
<p>So as Gold Thumb says: you can do this by accessing the UIView's CALayer. Specifically its contentRect:</p>
<p>From the <a href="https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html" rel="noreferrer">Apple Docs</a>: The rectangle, in the unit coordinate space, that defines the portion of the layer’s contents that should be used. Animatable.</p> |
1,016,409 | fastest way to use css for html table without affecting another html table | <p>My css is located at <a href="http://sillybean.net/css/seaglass.css" rel="nofollow noreferrer">http://sillybean.net/css/seaglass.css</a> and i want to use this css for only one of html table, On the same page i have multiple html tables so i do not want to affect other html tables. What is the fastest way to do it with less modification on <a href="http://sillybean.net/css/seaglass.css" rel="nofollow noreferrer">http://sillybean.net/css/seaglass.css</a> ?</p> | 1,016,414 | 8 | 0 | null | 2009-06-19 05:05:01.183 UTC | 4 | 2017-04-12 20:38:04.61 UTC | 2017-01-27 08:00:53.47 UTC | null | 6,637,668 | null | 108,869 | null | 1 | 8 | html|css | 52,752 | <p>Can you just apply a class to the table you want to affect, then use that class in your CSS?</p>
<p>In your HTML, you can put:</p>
<pre><code><table class="mytable">
... CONTENT OF THE TABLE, AS NORMAL ...
</table>
</code></pre>
<p>And then, add the class selector to your CSS:</p>
<pre class="lang-css prettyprint-override"><code>table.mytable { border-collapse: collapse; border: 1px solid #839E99;
background: #f1f8ee; font: .9em/1.2em Georgia, "Times New Roman", Times, serif; color: #033; }
.mytable caption { font-size: 1.3em; font-weight: bold; text-align: left; padding: 1em 4px; }
.mytable td,
.mytable th { padding: 3px 3px .75em 3px; line-height: 1.3em; }
.mytable th { background: #839E99; color: #fff; font-weight: bold; text-align: left; padding-right: .5em; vertical-align: top; }
.mytable thead th { background: #2C5755; text-align: center; }
.mytable .odd td { background: #DBE6DD; }
.mytable .odd th { background: #6E8D88; }
.mytable td a,
.mytable td a:link { color: #325C91; }
.mytable td a:visited { color: #466C8E; }
.mytable td a:hover,
.mytable td a:focus { color: #1E4C94; }
.mytable th a,
.mytable td a:active { color: #fff; }
.mytable tfoot th,
.mytable tfoot td { background: #2C5755; color: #fff; }
.mytable th + td { padding-left: .5em; }
</code></pre> |
1,281,353 | Use Java FFmpeg wrapper, or simply use Java runtime to execute FFmpeg? | <p>I'm pretty new to Java, need to write a program that listen to video conversion instructions and convert the video once an new instruction arrives. (Instructions are stored in Amazon SQS, but it's irrelevant to my question)</p>
<p>I'm facing a choice, either use Java runtime to exec FFmpeg conversion (like from command line), or I can use a FFmpeg wrapper written in Java.</p>
<p><a href="http://fmj-sf.net/ffmpeg-java/getting_started.php" rel="nofollow noreferrer">http://fmj-sf.net/ffmpeg-java/getting_started.php</a></p>
<p>I'd much prefer using Java runtime to exec FFmpeg directly, and avoid using java-ffmpeg wrapper as I have to learn the library.</p>
<p>So my question is this: Are there any benefits using java-ffmpeg wrapper over exec FFmpeg directly using Runtime?</p>
<p>I don't need FFmpeg to play videos, just convert videos.</p> | 1,281,454 | 8 | 0 | null | 2009-08-15 06:59:23.613 UTC | 28 | 2022-05-20 06:40:56.15 UTC | 2022-05-20 06:40:20.447 UTC | null | 452,775 | null | 156,153 | null | 1 | 53 | java|ffmpeg|runtime.exec | 89,418 | <p>If I'm not mistaken, the "ffmpeg-wrapper" project you linked to is out of date and not maintained. FFmpeg is a very active project, lot's of changes and releases all the time.</p>
<p>You should look at the Xuggler project, this provides a Java API for what you want to do, and they have tight integration with FFmpeg.</p>
<p><a href="http://www.xuggle.com/xuggler/" rel="nofollow noreferrer">http://www.xuggle.com/xuggler/</a></p>
<p>Should you choose to go down the <code>Runtime.exec()</code> path, this Red5 thread should be useful:</p>
<p><a href="http://www.nabble.com/java-call-ffmpeg-ts15886850.html" rel="nofollow noreferrer">http://www.nabble.com/java-call-ffmpeg-ts15886850.html</a></p> |
1,146,624 | How to do static content in Rails? | <p>Looking at different options:</p>
<p>One is to just put the static pages in the public/ folder, but I do want the header from layout/application to be consistent.</p>
<p>I tried this, but I got an error:</p>
<pre><code># in routes.rb:
map.connect '*path', :controller => 'content', :action => 'show'
# in content_controller.rb:
def show
render :action => params[:path].join('/')
end
</code></pre>
<p>All I want is an easy way to put together things like my faq, contact, tos, privacy, and other non-application type pages somewhere easy by just creating an .rhtml. who has done this?</p> | 1,688,840 | 8 | 0 | null | 2009-07-18 03:23:37.643 UTC | 37 | 2020-10-23 07:22:54.703 UTC | 2015-03-11 19:05:37.077 UTC | null | 201,911 | null | 92,679 | null | 1 | 73 | ruby-on-rails|ruby|static-content | 57,692 | <p>thoughtbot has a plugin called high_voltage for displaying static content: <a href="https://github.com/thoughtbot/high_voltage" rel="noreferrer">https://github.com/thoughtbot/high_voltage</a></p> |
998,235 | Does Visual Studio 2010 support iPhone Development? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/22358/how-can-i-develop-for-iphone-using-a-windows-development-machine">How can I develop for iPhone using a Windows development machine?</a> </p>
</blockquote>
<p>Does Visual Studio 2010 support iPhone Development?</p> | 998,264 | 9 | 2 | null | 2009-06-15 20:35:32.893 UTC | 3 | 2019-02-01 07:57:48.917 UTC | 2017-05-23 12:26:44.457 UTC | null | -1 | null | 109,676 | null | 1 | 7 | iphone|visual-studio | 38,504 | <p><a href="https://developer.apple.com/xcode/" rel="nofollow noreferrer">Xcode</a> must be used to develop for the iPhone. It is the only platform for which the iPhone SDK is available.</p> |
217,549 | Which Typesafe Enum in C++ Are You Using? | <p>It is common knowledge that built-in enums in C++ are not typesafe.
I was wondering which classes implementing typesafe enums are used out there...
I myself use the following "bicycle", but it is somewhat verbose and limited:</p>
<p>typesafeenum.h:</p>
<pre><code>struct TypesafeEnum
{
// Construction:
public:
TypesafeEnum(): id (next_id++), name("") {}
TypesafeEnum(const std::string& n): id(next_id++), name(n) {}
// Operations:
public:
bool operator == (const TypesafeEnum& right) const;
bool operator != (const TypesafeEnum& right) const;
bool operator < (const TypesafeEnum& right) const;
std::string to_string() const { return name; }
// Implementation:
private:
static int next_id;
int id;
std::string name;
};
</code></pre>
<p>typesafeenum.cpp:</p>
<pre><code>int TypesafeEnum::next_id = 1;
bool TypesafeEnum::operator== (const TypesafeEnum& right) const
{ return id == right.id; }
bool TypesafeEnum::operator!= (const TypesafeEnum& right) const
{ return !operator== (right); }
bool TypesafeEnum::operator< (const TypesafeEnum& right) const
{ return id < right.id; }
</code></pre>
<p>Usage:</p>
<pre><code>class Dialog
{
...
struct Result: public TypesafeEnum
{
static const Result CANCEL("Cancel");
static const Result OK("Ok");
};
Result doModal();
...
};
const Dialog::Result Dialog::Result::OK;
const Dialog::Result Dialog::Result::CANCEL;
</code></pre>
<p><strong>Addition:</strong>
I think I should have been more specific about the requirements. I'll try to summarize them:</p>
<p>Priority 1: Setting an enum variable to an invalid value should be impossible (a compile-time error) with no exceptions.</p>
<p>Priority 2: Converting an enum value to/from an int should be possible with a single explicit function/method call.</p>
<p>Priority 3: As compact, elegant and convenient declaration and usage as possible</p>
<p>Priority 4: Converting enum values to and from strings.</p>
<p>Priority 5: (Nice to have) Possibility to iterate over enum values.</p> | 439,004 | 11 | 4 | null | 2008-10-20 04:58:33.603 UTC | 33 | 2016-10-06 21:53:47.893 UTC | 2014-06-16 20:37:18.057 UTC | Alex Jenter | 76,722 | Alex Jenter | 22,046 | null | 1 | 45 | design-patterns|enums|enumeration|type-safety|c++03 | 27,413 | <p>I'm currently playing around with the Boost.Enum proposal from the <a href="https://github.com/boost-vault/Miscellaneous" rel="noreferrer">Boost Vault</a> (filename <code>enum_rev4.6.zip</code>). Although it was never officially submitted for inclusion into Boost, it's useable as-is. (Documentation is lacking but is made up for by clear source code and good tests.)</p>
<p>Boost.Enum lets you declare an enum like this:</p>
<pre><code>BOOST_ENUM_VALUES(Level, const char*,
(Abort)("unrecoverable problem")
(Error)("recoverable problem")
(Alert)("unexpected behavior")
(Info) ("expected behavior")
(Trace)("normal flow of execution")
(Debug)("detailed object state listings")
)
</code></pre>
<p>And have it automatically expand to this:</p>
<pre><code>class Level : public boost::detail::enum_base<Level, string>
{
public:
enum domain
{
Abort,
Error,
Alert,
Info,
Trace,
Debug,
};
BOOST_STATIC_CONSTANT(index_type, size = 6);
Level() {}
Level(domain index) : boost::detail::enum_base<Level, string>(index) {}
typedef boost::optional<Level> optional;
static optional get_by_name(const char* str)
{
if(strcmp(str, "Abort") == 0) return optional(Abort);
if(strcmp(str, "Error") == 0) return optional(Error);
if(strcmp(str, "Alert") == 0) return optional(Alert);
if(strcmp(str, "Info") == 0) return optional(Info);
if(strcmp(str, "Trace") == 0) return optional(Trace);
if(strcmp(str, "Debug") == 0) return optional(Debug);
return optional();
}
private:
friend class boost::detail::enum_base<Level, string>;
static const char* names(domain index)
{
switch(index)
{
case Abort: return "Abort";
case Error: return "Error";
case Alert: return "Alert";
case Info: return "Info";
case Trace: return "Trace";
case Debug: return "Debug";
default: return NULL;
}
}
typedef boost::optional<value_type> optional_value;
static optional_value values(domain index)
{
switch(index)
{
case Abort: return optional_value("unrecoverable problem");
case Error: return optional_value("recoverable problem");
case Alert: return optional_value("unexpected behavior");
case Info: return optional_value("expected behavior");
case Trace: return optional_value("normal flow of execution");
case Debug: return optional_value("detailed object state listings");
default: return optional_value();
}
}
};
</code></pre>
<p>It satisfies all five of the priorities which you list.</p> |
626,899 | How do you change the datatype of a column in SQL Server? | <p>I am trying to change a column from a <code>varchar(50)</code> to a <code>nvarchar(200)</code>. What is the SQL command to alter this table? </p> | 626,904 | 11 | 0 | null | 2009-03-09 16:06:41.09 UTC | 45 | 2022-09-18 13:52:29.883 UTC | 2020-10-21 00:19:24 UTC | mwigdahl | 285,795 | Ascalonian | 65,230 | null | 1 | 387 | sql-server|tsql|type-conversion|alter-table | 786,334 | <pre><code>ALTER TABLE TableName
ALTER COLUMN ColumnName NVARCHAR(200) [NULL | NOT NULL]
</code></pre>
<p><strong>EDIT</strong>
As noted NULL/NOT NULL should have been specified, see <a href="https://stackoverflow.com/a/635360/1165522">Rob's answer</a> as well. </p> |
620,993 | Determining binary/text file type in Java? | <p>Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?</p> | 621,003 | 12 | 1 | null | 2009-03-07 00:31:04.477 UTC | 12 | 2022-06-18 22:49:39.437 UTC | 2012-11-23 16:50:32.597 UTC | null | 145,989 | gsmd | 15,187 | null | 1 | 48 | java|file|text|binary | 39,892 | <p>There's no guaranteed way, but here are a couple of possibilities:</p>
<ol>
<li><p>Look for a header on the file. Unfortunately, headers are file-specific, so while you might be able to find out that it's a RAR file, you won't get the more generic answer of whether it's text or binary.</p>
</li>
<li><p>Count the number of character vs. non-character types. Text files will be mostly alphabetical characters while binary files - especially compressed ones like rar, zip, and such - will tend to have bytes more evenly represented.</p>
</li>
<li><p>Look for a regularly repeating pattern of newlines.</p>
</li>
</ol> |
69,913 | Why don't self-closing script elements work? | <p>What is the reason browsers do not correctly recognize:</p>
<pre><code><script src="foobar.js" /> <!-- self-closing script element -->
</code></pre>
<p>Only this is recognized:</p>
<pre><code><script src="foobar.js"></script>
</code></pre>
<p>Does this break the concept of XHTML support?</p>
<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p> | 69,984 | 12 | 14 | null | 2008-09-16 06:52:38.563 UTC | 177 | 2022-02-21 13:21:39.817 UTC | 2019-04-09 03:58:42.973 UTC | JasonBunting | 606,371 | dimarzionist | 10,778 | null | 1 | 1,483 | javascript|html|internet-explorer|xhtml | 155,565 | <p>The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:</p>
<p><a href="http://www.w3.org/TR/xhtml1/#C_3" rel="nofollow noreferrer">С.3. Element Minimization and Empty Element Content</a></p>
<blockquote>
<p>Given an empty instance of an element whose content model is not <code>EMPTY</code> (for example, an empty title or paragraph) do not use the minimized form (e.g. use <code><p> </p></code> and not <code><p /></code>).</p>
</blockquote>
<p><a href="http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict" rel="nofollow noreferrer">XHTML DTD</a> specifies script elements as:</p>
<pre><code><!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.