instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have a vertical menu in my system which is basically made of HTML <code>ul</code>/<code>li</code> with CSS styling (see image below). However I don't want the <code>li</code> items which are wider than the menu to wrap, I would prefer them to overflow with a horizontal scroll bar at the bottom of the menu. How can I do this in CSS?</p>
|
<pre><code>ul {
overflow: auto; // allow li's to overflow w/ scroll bar
// at the bottom of the menu
}
li {
white-space: nowrap; // stop the wrapping in the first place
}
</code></pre>
|
<p>You would also need to give the style the ul:</p>
<pre><code>ul{
width:250px;
overflow:auto;
}
</code></pre>
| 38,028
|
<p>I have a stored procedure that needs to convert hexadecimal numbers to their decimal equivalent. I've read the documentation for the UNHEX() function, but it is returning a binary value. What I'm wanting to do is something like this:</p>
<pre><code>CREATE PROCEDURE foo( hex_val VARCHAR(10) )
BEGIN
DECLARE dec_val INTEGER;
SET dec_val = UNHEX( hex_val );
-- Do something with the decimal value
select dec_val;
END
</code></pre>
<p>What am I missing? How can I convert the UNHEX()'d value to a unsigned integer?</p>
|
<p>You can use the <a href="http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_conv" rel="noreferrer"><code>CONV()</code></a> function to convert between bases.</p>
<pre><code>SET dec_val = CONV(hex_val, 16, 10);
</code></pre>
|
<pre><code>conv(hex_val, 16, 10)
</code></pre>
<p>Will convert a number of base 16 to base 10. The UNHEX function does something completely different, it converts pairs of hex digits to characters.</p>
| 45,661
|
<p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
|
<p>Since <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)" rel="noreferrer">Java 1.5, yes</a>:</p>
<pre><code>Pattern.quote("$5");
</code></pre>
|
<p>^(Negation) symbol is used to match something that is not in the character group.</p>
<p>This is the link to <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference" rel="nofollow noreferrer">Regular Expressions</a></p>
<p>Here is the image info about negation:</p>
<p><img src="https://i.stack.imgur.com/m5cXU.png" alt="Info about negation"></p>
| 8,499
|
<p>For my C# app, I don't want to always prompt for elevation on application start, but if they choose an output path that is UAC protected then I need to request elevation.</p>
<p>So, how do I check if a path is UAC protected and then how do I request elevation mid-execution?</p>
|
<p>The best way to detect if they are unable to perform an action is to attempt it and catch the <code>UnauthorizedAccessException</code>.</p>
<p>However as @<a href="https://stackoverflow.com/users/941/dannysmurf">DannySmurf</a> <a href="https://stackoverflow.com/questions/17533/request-vista-uac-elevation-if-path-is-protected#17544">correctly points out</a> you can only elevate a COM object or separate process.</p>
<p>There is a demonstration application within the Windows SDK Cross Technology Samples called <a href="http://msdn.microsoft.com/en-us/library/aa970890.aspx" rel="nofollow noreferrer" title="MSDN - UAC Sample">UAC Demo</a>. This demonstration application shows a method of executing actions with an elevated process. It also demonstrates how to find out if a user is currently an administrator.</p>
|
<p>If your secondary drive has it's own file permissions, like say you have an other copy of windows installed on it. It will prompt.</p>
<p>It will also prompt if files are in use, which sometimes occurs if you have windows explorer open to the same directory and the file selected with a file previewer displaying the contents... there are some other oddities, but generally you get asked for file permission if the file is in use or it's a sensitive directory. </p>
<p>If you do loop the FolderBrowserDialog , make sure to notify the user why, so they dont get mad at your app. </p>
<p>Note: it does stink there is no .net way of asking for permission, maybe p/invoke the win32 api...?</p>
| 3,816
|
<p>Our project is held in a SourceSafe database. We have an automated build, which runs every evening on a dedicated build machine. As part of our build process, we get the source and associated data for the installation from SourceSafe. This can take quite some time and makes up the bulk of the build process (which is otherwise dominated by the creation of installation files).</p>
<p>Currently, we use the command line tool, <code>ss.exe</code>, to interact with SourceSafe. The commands we use are for a recursive get of the project source and data, checkout of version files, check-in of updated version files, and labeling. However, I know that SourceSafe also supports an object model.</p>
<ul>
<li>Does anyone have any experience with this object model?</li>
<li>Does it provide any advantages over using the command line tool that might be useful in our process?</li>
<li>Are there any disadvantages?</li>
<li>Would we gain any performance increase from using the object model over the command line?</li>
</ul>
|
<p>I should imagine the command line is implemented internally with the same code as you'd find in the object model, so unless there's a large amount of startup required, it shouldn't make much of a difference.</p>
<p>The cost of rewriting to use the object model is probably more than would be saved in just leaving it go as it is. Unless you have a definite problem with the time taken, I doubt this will be much of a solution for you.</p>
<p>You could investigate shadow directories so the latest version is always available, so you don't have to perform a 'getlatest' every time, and you could ensure that you're talking to a local VSS (as all commands are performed directly on the filesystem, so WAN operations are tremendously expensive). </p>
<p>Otherwise, you're stuck unless you'd like to go with a different SCM (and I recommend SVN - there's an <a href="http://www.codeplex.com/VSS2SVN" rel="nofollow noreferrer">excellent converter</a> available on codeplex for it, with example code showing how to use the VSS ans SVN object models)</p>
|
<p>I betting running the Object Model will be slower by at least 2 hours.... ;-)</p>
| 49,512
|
<p>If I need to implement sending and receiving of business documents from system to system (invoices, POs, remittance advice, etc) what standard would you recommend for best interop and why? It could be XML or otherwise.</p>
|
<p>I would look at (in this order):</p>
<ul>
<li>Industry-specific formats. Always your best choice if you have a homogeneous trading group.</li>
<li>cXML or XCBL if you want an XML solution with an established standard.</li>
<li>X12 if you have unlimited time, money, and willing partners.</li>
<li>custom XML only if you have requirements outside a standard or such a small amount of data to transmit that the standard would bloat your documents too much.</li>
</ul>
<p>This, of course, all depends on the problem domain. I would think about these questions:</p>
<ol>
<li>Are you in an industry with specific format or regulatory requirements? For instance, are there details like the chemical composition of a gas that you're ordering? Are there hazardous materials that require special orders or handling?</li>
<li>Does your industry have a specific format already or do you need a generic one? Chem/Gas, Retail, Big Oil, Airlines, Financial Services, and many others already have formats and sometimes networks established.</li>
<li>Do you work with corporate purchasers who have procurement applications? If so, I'd take a look at cXML or XCBL which handles the PunchOut standard which enables purchasing systems to order from online catalogs.</li>
<li>What is the sophistication of your partners? EDI is old and powerful, but really hard to understand. People new to the process are more comfortable with XML-based formats.</li>
<li>What is your position in the market? Can you drive a standard for your partners or will they dictate a format to you? In which case, will you need to adopt several standards? Who will translate between them?</li>
</ol>
|
<p>PDF - everyone has it, its cross platform and it can handle any document type. No good if you want to edit it though.</p>
| 20,132
|
<p>Does anyone know of a way to find out how much memory an instance of an object is taking?</p>
<p>For example, if I have an instance of the following object:</p>
<pre><code>TestClass tc = new TestClass();
</code></pre>
<p>Is there a way to find out how much memory the instance <code>tc</code> is taking?</p>
<p>The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).</p>
<p>There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools. </p>
|
<p>If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.</p>
<p>Download here: <a href="https://github.com/MicrosoftArchive/clrprofiler" rel="nofollow noreferrer">https://github.com/MicrosoftArchive/clrprofiler</a></p>
<p>If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here:
<a href="http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx</a></p>
<p>(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)</p>
|
<p>I have good experiences with <a href="http://memprofiler.com/" rel="nofollow noreferrer">MemProfiler</a>. It gives you stack traces of when the object was created and all the graphs of why the object is still not garbage collected.</p>
| 8,584
|
<p>I have a working excel workbook that has VBA code and macros to help in data input.</p>
<p>I use a calendar to capture dates and read data out of cells. The application works 100% on my machine (application developed in <code>2007</code> but saved as a <code>.XLS – 97/2000</code> for compatibility in the office).
When I give the file to other people, the calendar control and the <code>TRIM()</code> function do not work. </p>
<p>On my machine I can get to the references section but on all other machines in the office the <code>references</code> function is grayed out. Any idea why a common object like the calendar and a common function like <code>trim()</code> do not work on some machines </p>
|
<p>The calendar control has many different versions, you need to build it out of the version they have on their machine.</p>
|
<p>VBA will automatically update references to the newest version. Example: If I reference Office 10.0 and you have Office 12.0 on your machine the reference will automatically be updated from ten to twelve. But it does <em>not</em> downgrade them. So if you have a reference to Office 12.0 and deploy it on a machine that only has Office 10.0 then you code will break.</p>
<p>There are two ways around this. If you want to stay with early binding then you will need to obtain a copy of the oldest version of the library in use. Then reference that file. </p>
<p>The usual alternative would be to go to late binding. However this can be little more challenging with embedded controls. </p>
| 31,168
|
<p>If you have a class member that is <code>static</code> and <code>public</code>. Would you write <code>static public</code> or <code>public static</code>? I know they are the same. But is there some recommendation / best practice for writing this?</p>
|
<p>see <a href="https://stackoverflow.com/questions/191929/is-there-a-convention-to-the-order-of-modifiers-in-c#191944">this question</a></p>
<p>If you download the Microsoft <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">StyleCop</a> Visual Studio addin, it can validate your source code against the rules Microsoft use. It likes the access modifier to come first.</p>
|
<p>I personally would go with public static because it's more important that it's public than that it's static.</p>
<p>And check this: <a href="http://checkstyle.sourceforge.net/config_modifier.html" rel="nofollow noreferrer">http://checkstyle.sourceforge.net/config_modifier.html</a></p>
<p>As well as this: <a href="http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html</a> (These two links are for Java, but the concept is the same)</p>
<p>Short version: "public static" is recommended and is far more common.</p>
| 29,701
|
<p>I get this error when I do a <strong>bulk insert</strong> with <code>select * from [table_name]</code>, and another table name:</p>
<pre><code>the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033'
of the destination column 'PAT_ID_OLD' do not match
</code></pre>
<p>I tried resetting my db collation but this did not help. </p>
<p>Has anyone seen this error?</p>
|
<p>If you are copying less than a full set of fields from one table to another, whether that table is on another domain across the world, or is collocated in the same database, you just have to select them in order. SqlBulkCopyColumnMappings do not work. Yes, I tried. I used all four possible constructors, and I used them both as SqlBulkCopyMapping objects and just by providing the same information to the Add method of SqlBulkCopy.ColumnMappings.Add.</p>
<p>My columns are named the same. If you're using a different name as well as a different order, you may well find that you have to actually rename the columns. Good luck.</p>
|
<p>I would check what your default locale settings are. Also, you'll need to check the locale of both tables using sp_help to verify they are the same. If they aren't you'll need to convert it to the correct locale</p>
| 12,825
|
<p>I've installed Oracle XE with APEX, but forgot to write down the URL to access it. How may I determine the URL?</p>
|
<p>The default is <a href="http://127.0.0.1:8080/apex" rel="noreferrer">http://127.0.0.1:8080/apex</a></p>
<p>If you happen to be on Windows, there will also be an entry in the Start menu (Programs > Oracle XE > Database homepage )</p>
|
<p>For future reference, to get to the Apex Administration Services:</p>
<p><a href="http://127.0.0.1:8080/apex/apex_admin" rel="nofollow noreferrer">http://127.0.0.1:8080/apex/apex_admin</a></p>
| 21,883
|
<p>In the middle of a Perl script, there is a system command I want to execute. I have a string that contains the data that needs to be fed into stdin (the command only accepts input from stdin), and I need to capture the output written to stdout. I've looked at the various methods of executing system commands in Perl, and the <code>open</code> function seems to be what I need, except that it looks like I can only capture stdin or stdout, not both.</p>
<p>At the moment, it seems like my best solution is to use <code>open</code>, redirect stdout into a temporary file, and read from the file after the command finishes. Is there a better solution?</p>
|
<p>IPC::Open2/3 are fine, but I've found that usually all I really need is <a href="http://metacpan.org/pod/IPC::Run3" rel="nofollow noreferrer">IPC::Run3</a>, which handles the simple cases really well with minimal complexity:</p>
<pre><code>use IPC::Run3; # Exports run3() by default
run3( \@cmd, \$in, \$out, \$err );
</code></pre>
<p>The documentation compares IPC::Run3 to other alternatives. It's worth a read even if you don't decide to use it.</p>
|
<p>I always do it this way if I'm only expecting a single line of output or want to split the result on something other than a newline:</p>
<pre><code>my $result = qx( command args 2>&1 );
my $rc=$?;
# $rc >> 8 is the exit code of the called program.
if ($rc != 0 ) {
error();
}
</code></pre>
<p>If you want to deal with a multi-line response, get the result as an array:</p>
<pre><code>my @lines = qx( command args 2>&1 );
foreach ( my $line ) (@lines) {
if ( $line =~ /some pattern/ ) {
do_something();
}
}
</code></pre>
| 10,355
|
<p>I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a <code>BiDictionaryOneToOne<T, S></code> which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...</p>
<p>There is a BiDictionary in the answers to <a href="https://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary">this question</a>, but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)). </p>
<p>Thanks!</p>
|
<p>OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement :</p>
<pre><code>/// <summary>
/// This is a dictionary guaranteed to have only one of each value and key.
/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.
/// </summary>
/// <typeparam name="TFirst">The type of the "key"</typeparam>
/// <typeparam name="TSecond">The type of the "value"</typeparam>
public class BiDictionaryOneToOne<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
#region Exception throwing methods
/// <summary>
/// Tries to add the pair to the dictionary.
/// Throws an exception if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
throw new ArgumentException("Duplicate first or second");
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
/// <summary>
/// Find the TSecond corresponding to the TFirst first
/// Throws an exception if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <returns>the value corresponding to first</returns>
public TSecond GetByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");
return second;
}
/// <summary>
/// Find the TFirst corresponing to the Second second.
/// Throws an exception if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <returns>the value corresponding to second</returns>
public TFirst GetBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");
return first;
}
/// <summary>
/// Remove the record containing first.
/// If first is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="first">the key of the record to delete</param>
public void RemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
throw new ArgumentException("first");
firstToSecond.Remove(first);
secondToFirst.Remove(second);
}
/// <summary>
/// Remove the record containing second.
/// If second is not in the dictionary, throws an Exception.
/// </summary>
/// <param name="second">the key of the record to delete</param>
public void RemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
throw new ArgumentException("second");
secondToFirst.Remove(second);
firstToSecond.Remove(first);
}
#endregion
#region Try methods
/// <summary>
/// Tries to add the pair to the dictionary.
/// Returns false if either element is already in the dictionary
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>true if successfully added, false if either element are already in the dictionary</returns>
public Boolean TryAdd(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
return false;
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
return true;
}
/// <summary>
/// Find the TSecond corresponding to the TFirst first.
/// Returns false if first is not in the dictionary.
/// </summary>
/// <param name="first">the key to search for</param>
/// <param name="second">the corresponding value</param>
/// <returns>true if first is in the dictionary, false otherwise</returns>
public Boolean TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
/// <summary>
/// Find the TFirst corresponding to the TSecond second.
/// Returns false if second is not in the dictionary.
/// </summary>
/// <param name="second">the key to search for</param>
/// <param name="first">the corresponding value</param>
/// <returns>true if second is in the dictionary, false otherwise</returns>
public Boolean TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
/// <summary>
/// Remove the record containing first, if there is one.
/// </summary>
/// <param name="first"></param>
/// <returns> If first is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveByFirst(TFirst first)
{
TSecond second;
if (!firstToSecond.TryGetValue(first, out second))
return false;
firstToSecond.Remove(first);
secondToFirst.Remove(second);
return true;
}
/// <summary>
/// Remove the record containing second, if there is one.
/// </summary>
/// <param name="second"></param>
/// <returns> If second is not in the dictionary, returns false, otherwise true</returns>
public Boolean TryRemoveBySecond(TSecond second)
{
TFirst first;
if (!secondToFirst.TryGetValue(second, out first))
return false;
secondToFirst.Remove(second);
firstToSecond.Remove(first);
return true;
}
#endregion
/// <summary>
/// The number of pairs stored in the dictionary
/// </summary>
public Int32 Count
{
get { return firstToSecond.Count; }
}
/// <summary>
/// Removes all items from the dictionary.
/// </summary>
public void Clear()
{
firstToSecond.Clear();
secondToFirst.Clear();
}
}
</code></pre>
|
<p>A bit late, but here's an implementation I wrote a while back. It handles a few interesting edge cases, such as when the key overrides the equality check to perform partial equality. This results in the main dictionary storing <code>A => 1</code> but the inverse storing <code>1 => A'</code>.</p>
<p>You access the inverse dictionary via the <code>Inverse</code> property.</p>
<pre><code>var map = new BidirectionalDictionary<int, int>();
map.Add(1, 2);
var result = map.Inverse[2]; // result is 1
</code></pre>
<hr>
<pre><code>//
// BidirectionalDictionary.cs
//
// Author:
// Chris Chilvers <chilversc@googlemail.com>
//
// Copyright (c) 2009 Chris Chilvers
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace Cadenza.Collections
{
public class BidirectionalDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly IEqualityComparer<TKey> keyComparer;
private readonly IEqualityComparer<TValue> valueComparer;
private readonly Dictionary<TKey, TValue> keysToValues;
private readonly Dictionary<TValue, TKey> valuesToKeys;
private readonly BidirectionalDictionary<TValue, TKey> inverse;
public BidirectionalDictionary () : this (10, null, null) {}
public BidirectionalDictionary (int capacity) : this (capacity, null, null) {}
public BidirectionalDictionary (IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
: this (10, keyComparer, valueComparer)
{
}
public BidirectionalDictionary (int capacity, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException ("capacity", capacity, "capacity cannot be less than 0");
this.keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;
this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
keysToValues = new Dictionary<TKey, TValue> (capacity, this.keyComparer);
valuesToKeys = new Dictionary<TValue, TKey> (capacity, this.valueComparer);
inverse = new BidirectionalDictionary<TValue, TKey> (this);
}
private BidirectionalDictionary (BidirectionalDictionary<TValue, TKey> inverse)
{
this.inverse = inverse;
keyComparer = inverse.valueComparer;
valueComparer = inverse.keyComparer;
valuesToKeys = inverse.keysToValues;
keysToValues = inverse.valuesToKeys;
}
public BidirectionalDictionary<TValue, TKey> Inverse {
get { return inverse; }
}
public ICollection<TKey> Keys {
get { return keysToValues.Keys; }
}
public ICollection<TValue> Values {
get { return keysToValues.Values; }
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
{
return keysToValues.GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).CopyTo (array, arrayIndex);
}
public bool ContainsKey (TKey key)
{
if (key == null)
throw new ArgumentNullException ("key");
return keysToValues.ContainsKey (key);
}
public bool ContainsValue (TValue value)
{
if (value == null)
throw new ArgumentNullException ("value");
return valuesToKeys.ContainsKey (value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Contains (item);
}
public bool TryGetKey (TValue value, out TKey key)
{
if (value == null)
throw new ArgumentNullException ("value");
return valuesToKeys.TryGetValue (value, out key);
}
public bool TryGetValue (TKey key, out TValue value)
{
if (key == null)
throw new ArgumentNullException ("key");
return keysToValues.TryGetValue (key, out value);
}
public TValue this[TKey key] {
get { return keysToValues [key]; }
set {
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
//foo[5] = "bar"; foo[6] = "bar"; should not be valid
//as it would have to remove foo[5], which is unexpected.
if (ValueBelongsToOtherKey (key, value))
throw new ArgumentException ("Value already exists", "value");
TValue oldValue;
if (keysToValues.TryGetValue (key, out oldValue)) {
// Use the current key for this value to stay consistent
// with Dictionary<TKey, TValue> which does not alter
// the key if it exists.
TKey oldKey = valuesToKeys [oldValue];
keysToValues [oldKey] = value;
valuesToKeys.Remove (oldValue);
valuesToKeys [value] = oldKey;
} else {
keysToValues [key] = value;
valuesToKeys [value] = key;
}
}
}
public int Count {
get { return keysToValues.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get { return false; }
}
public void Add (TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
if (keysToValues.ContainsKey (key))
throw new ArgumentException ("Key already exists", "key");
if (valuesToKeys.ContainsKey (value))
throw new ArgumentException ("Value already exists", "value");
keysToValues.Add (key, value);
valuesToKeys.Add (value, key);
}
public void Replace (TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
// replaces a key value pair, if the key or value already exists those mappings will be replaced.
// e.g. you have; a -> b, b -> a; c -> d, d -> c
// you add the mapping; a -> d, d -> a
// this will remove both of the original mappings
Remove (key);
inverse.Remove (value);
Add (key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> item)
{
Add (item.Key, item.Value);
}
public bool Remove (TKey key)
{
if (key == null)
throw new ArgumentNullException ("key");
TValue value;
if (keysToValues.TryGetValue (key, out value)) {
keysToValues.Remove (key);
valuesToKeys.Remove (value);
return true;
}
else {
return false;
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> item)
{
bool removed = ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Remove (item);
if (removed)
valuesToKeys.Remove (item.Value);
return removed;
}
public void Clear ()
{
keysToValues.Clear ();
valuesToKeys.Clear ();
}
private bool ValueBelongsToOtherKey (TKey key, TValue value)
{
TKey otherKey;
if (valuesToKeys.TryGetValue (value, out otherKey))
// if the keys are not equal the value belongs to another key
return !keyComparer.Equals (key, otherKey);
else
// value doesn't exist in map, thus it cannot belong to another key
return false;
}
}
}
</code></pre>
<p><a href="https://github.com/cadenza/cadenza/blob/master/src/Cadenza/Cadenza.Collections/BidirectionalDictionary.cs" rel="nofollow">Original source</a> and <a href="https://github.com/cadenza/cadenza/blob/master/src/Cadenza/Test/Cadenza.Collections/BidirectionalDictionaryTest.cs" rel="nofollow">tests</a> on github.</p>
| 33,670
|
<p>I have a couple variants of a program that I want to compare on performance. Both perform essentially the same task.</p>
<p>One does it all in C and memory. The other calls an external utility and does file IO.</p>
<p>How do I reliably compare them? </p>
<p>1) Getting "time on CPU" using "time" favors the second variant for calling system() and doing IO. Even if I add "system" time to "user" time, it'll still not count for time spent blocked on wait().</p>
<p>2) I can't just clock them for they run on a server and can be pushed off the CPU any time. Averaging across 1000s of experiments is a soft option, since I have no idea how my server is utilized - it's a VM on a cluster, it's kind of complicated.</p>
<p>3) profilers do not help since they'll give me time spent in the code, which again favors the version that does system()</p>
<p>I need to add up all CPU time that these programs consume, including user, kernel, IO, and children's recursively. </p>
<p>I expected this to be a common problem, but still don't seem to find a solution.</p>
<p>(Solved with times() - see below. Thanks everybody)</p>
|
<p>If I've understood, typing "time myapplication" on a bash command line is not what you are looking for.</p>
<p>If you want accuracy, you must use a profiler... You have the source, yes?</p>
<p>Try something like <a href="http://oprofile.sourceforge.net/news/" rel="nofollow noreferrer">Oprofile</a> or <a href="http://valgrind.org/" rel="nofollow noreferrer">Valgrind</a>, or take a look at <a href="http://en.wikipedia.org/wiki/List_of_performance_analysis_tools" rel="nofollow noreferrer">this</a> for a more extended list.</p>
<p>If you haven't the source, honestly I don't know...</p>
|
<p>I'd probably lean towards adding "time -o somefile" to the front of the system command, and then adding it to the time given by time'ing your main program to get a total. Unless I had to do this lots of times, then I'd find a way to take two time outputs and add them up to the screen (using awk or shell or perl or something).</p>
| 18,058
|
<p>How does one lock the focus of a .net application to a specific control? For example, if I have a form with 5 text boxes, and I want them filled out in a specific order, how can I stop someone who is in box 1 from tabbing/clicking to box 2, or hitting OK or Cancel or anything else? Is there an easy way, or do I have to manually disable/enable each other control at the appropriate time? </p>
<p>The trouble with the obvious solution (Reset Focus when Focus is Lost) is that MSDN says you can lock up your machine that way:</p>
<p>(Source:<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx</a>)</p>
<p>Caution:</p>
<p>Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at <a href="http://msdn.microsoft.com/library" rel="nofollow noreferrer">http://msdn.microsoft.com/library</a>. </p>
|
<p>Handle the Leave event of your textBox1. Inside the event handler, if your conditions are not met, for e.g. if the user has not entered some input, reset the focus back to the control.</p>
<pre><code>private void textBox1_Leave(object sender, EventArgs e)
{
if string.isNullOrEmpty(textBox1.Text)
{
textBox1.focus();
}
}
</code></pre>
<p>Do this for each of your controls or do it more generic like:</p>
<pre><code>private void textBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (string.isNullOrEmpty(textBox.Text)
{
textBox.focus();
}
}
</code></pre>
|
<p>Handle the Leave event of your textBox1. Inside the event handler, if your conditions are not met, for e.g. if the user has not entered some input, reset the focus back to the control.</p>
<pre><code>private void textBox1_Leave(object sender, EventArgs e)
{
if string.isNullOrEmpty(textBox1.Text)
{
textBox1.focus();
}
}
</code></pre>
<p>Do this for each of your controls or do it more generic like:</p>
<pre><code>private void textBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (string.isNullOrEmpty(textBox.Text)
{
textBox.focus();
}
}
</code></pre>
| 35,707
|
<p>Does anyone have some good information on the usage of the .SaveChanges() method?</p>
<p>I am experiencing a variety of issues when attempting to use the .SaveChanges() method on my data context object. I am taking data from an existing data source, creating the appropriate EntityFramework/DataService objects, populating those created objects with data, adding those objects to the context and then saving that data by calling .SaveChanges.</p>
<p>The scenarios I've come up with (and the problems associated with them) are as such ... In each scenario I have a foreach loop that is taking data from rows in a DataTable and generating the objects, attaching them to the context as they go. (note: three objects a "member" and two "addresses" that are attached via a SetLink call) - basically this is a conversion tool to take data from one data store and massage it into a data store that is exposed by Data Services.</p>
<ul>
<li>Call .SaveChanges() without any parameters once at the end of the foreach loop (i.e. outside the loop)
<ul>
<li>OutOfMemory error about 1/3 of the way (30,000 out of 90,000 saves) - not sure how that is happening though as each save item is a seperate SQL call to the database, what is there to run out of memory on?</li>
</ul></li>
<li>Call .SaveChanges() without any parameters once per loop
<ul>
<li>This works, but takes absolutly forever (8 hours for 90,000 saves)</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once at the end of the foreach loop
<ul>
<li>Same OutOfMemory error, but without any saves to the database</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once per loop
<ul>
<li>404 not found error</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once per 10 loops
<ul>
<li>400 Bad Request error (occassionally)</li>
<li>OutOfMemory after a number of itterations</li>
</ul></li>
<li>A number of random attempts to create the context once per loop, or have it as a variable at the start of the loop or have it as a private member variable that is available.
<ul>
<li>Differing results, unable to quantify, none really that good</li>
</ul></li>
</ul>
<p>What is the prefered method of calling .SaveChanges() from a client object when doing a large data load like this? Is there something I'm not getting about how .SaveChanges() works? Can anyone provide more details on how once should be utilizing this function and what (if any) are the limitations to saving data via Data Services? Are there any best practices around the .SaveChanges() method call? Is there any particularly good documentation on the .SaveChanges() method call?</p>
|
<p>I have no big experience in using EntityFramework (just some random experiment), have you tried calling .SaveChanges() every n iterations?</p>
<p>I mean something like this:</p>
<pre><code>int i = 0;
foreach (var item in collection)
{
// do something with your data
if ((i++ % 10) == 0)
context.SaveChanges();
}
context.SaveChanges();
</code></pre>
<p>I know it's ugly, but it's the first possible solution i came up with.</p>
|
<p>I am using EntityFramework on a small project also so I am very interested in the question also.
Two quick questions:
Have you tried to turn of the caching og the data objects in the datacontext?
Have you tried to close the datacontext and created a new one during the loop to free up memory?</p>
<p>Regards</p>
<p>Kenneth</p>
| 23,062
|
<p>I'm trying to use System.Transaction.TransactionScope to create a transaction to call a few stored procedures but it doesn't seem to clean up after itself. Once the transaction is finished (commited or not and the transaction scope object is disposed) subsequent connections to the database open up with the read commit level of serializable instead of read commited like they normally would. </p>
<p>I'm opening and closing a connection for each call (well closing and returning to a pool of connections like normal in .NET), am I missing some way to explicitly reset the connection when I'm done using it for a transaction? I thought the idea behind System.Transaction.TransactionScope was to hide all the complexity.</p>
<p>So the code I have looks like this:</p>
<pre><code> using (var scope = new TransactionScope())
{
... make my 3 stored procedure calls ...
scope.Complete();
return returnCode;
}
</code></pre>
<p>which I guess is the normal way to do it. But then if I look in sqlserver profiler I can see connections being opened with </p>
<pre><code>set transaction isolation level serializable
</code></pre>
<p>which is messing with subsequent non-transaction related database activity and also is apparently not as fast. I can get around this by setting a transaction option to explicity do the transaction with ReadCommited but this is not the ideal behaviour for this operation in my opinion. </p>
<p>I've also tried explicitly creating a Commitabletransaction object, creating explict new transactions instead of using the ambient one and still no luck. </p>
<p>Any ideas on how to fix this would be much appreciated as any calls that use the serializable connection will throw an error if they try to use a readpast locking hint.</p>
|
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionoptions.isolationlevel.aspx" rel="nofollow noreferrer">TransactionOptions.IsolationLevel</a></p>
<p>By <a href="http://msdn.microsoft.com/en-us/library/system.transactions.isolationlevel.aspx" rel="nofollow noreferrer">default, it's serializable</a></p>
<pre><code>TransactionOptions transactionoptions1 = new TransactionOptions();
transactionoptions1.IsolationLevel = IsolationLevel.ReadCommitted;
using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionoptions1))
{
... make my 3 stored procedure calls ...
scope.Complete();
return returnCode;
}
</code></pre>
|
<p>You should also see a reset (<code>sp_reset_connection</code>) between uses of the same connection in the pool; will that not reset the isolation level? Have you tried reproducing a serializable issue (for example, lock escalation deadlocks)</p>
| 44,158
|
<p>I'm having a bit of trouble trying to get class variables to work in javascript. </p>
<p>I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables.</p>
<p>This is why this bit of code confuses me.</p>
<p>What is the correct way to implement class variables?</p>
<pre><code>function classA() {};
classA.prototype.shared = 0;
a = new classA;
//print both values to make sure that they are the same
classA.prototype.shared;
a.shared;
//increment class variable
classA.prototype.shared++;
//Verify that they are each 1 (Works)
classA.prototype.shared;
a.shared;
//now increment the other reference
a.shared++;
//Verify that they are each 2 (Doesn't Work)
classA.prototype.shared;
a.shared;
</code></pre>
<p>UPDATE:
So it seems that everyone is confirming the fact that by incrementing the instance's variable we don't affect the prototype. This is fine, this is what I have documented in my example, but doesn't this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance's var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object. </p>
<p>I also understand that this isn't java/c++/ruby/python, it's a different language. I'm just curious as to why this behavior might be good. </p>
|
<p><strong>Static (class level) variables can be done like this</strong>:</p>
<pre><code>function classA(){
//initialize
}
classA.prototype.method1 = function(){
//accessible from anywhere
classA.static_var = 1;
//accessible only from THIS object
this.instance_var = 2;
}
classA.static_var = 1; //This is the same variable that is accessed in method1()
</code></pre>
<p>Your output seems strange <strong>because of the way javascript handles prototypes</strong>. Calling any method / retreiving a variable of an instantiated object <strong>checks the instance first, THEN the prototype</strong>. i.e.</p>
<pre><code>var a = new classA();
classA.prototype.stat = 1;
// checks a.stat which is undefined, then checks classA.prototype.stat which has a value
alert(a.stat); // (a.stat = undefined, a.prototype.stat = 1)
// after this a.stat will not check the prototype because it is defined in the object.
a.stat = 5; // (a.stat = 5, a.prototype.stat = 1)
// this is essentially a.stat = a.stat + 1;
a.stat++; // (a.stat = 6, a.prototype.stat = 1)
</code></pre>
|
<p>What you are defining is not a class variable, it is a default value for an instance variable.</p>
<p>Class variables should be defined directly in the class, which means directly in the constrctor function.</p>
<pre><code>function ClassA()
{
ClassA.countInstances = (ClassA.countInstances || 0) + 1;
}
var a1 = new ClassA();
alert(ClassA.countInstances);
var a2 = new ClassA();
alert(ClassA.countInstances);
</code></pre>
<p>When you are declaring a variable in the prototype, this variable will be inherited by all instances as instance variables (just like methods) and will ve overriden if you change it in the instance (just like methods).</p>
| 32,655
|
<p>Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql_variant, presumably into object? </p>
<p>The aim is to read data stored as <a href="http://msdn.microsoft.com/en-us/library/ms173829.aspx" rel="nofollow noreferrer">sql_variant type</a> in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql_variant, if possible, would go into such type.</p>
|
<p>If you want to put the data into a variable of type object then (simplified):</p>
<pre><code>object result = null;
result = reader["columnNameGoesHere"];
</code></pre>
<p>Should do the trick.</p>
<p>There's also a good explanation of the various different methods of retrieving the contents of a given columns current record in <a href="http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=454" rel="nofollow noreferrer">this DevHood tutorial</a>. The summary table of data type mappings at the end may come in handy too!</p>
|
<p>Sql_Variant is of type object.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings" rel="nofollow noreferrer">Microsoft Docs</a></p>
| 22,119
|
<p>I have a very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. The jQuery function simply returns empty array. </p>
<p>Any suggestions?</p>
<p>Page is too complex to post it here. Practically any selector, except <code>"#id"</code> selectors, returns a zero element array. The jQuery version is 1.2.3</p>
|
<p>Try upgrading to jQuery 1.2.6, you should be on the latest release of jQuery if you are having problems first ensure you are on the latest and greatest.</p>
|
<p>What version(s) of IE is it failing under? Is it failing for a specific complex selector? I think we need an example.</p>
<p>Edit: Does the problem go away if you upgrade to 1.2.6? 1.2.6 is primarily a bug-fix release according to <a href="http://docs.jquery.com/Release:jQuery_1.2.6" rel="nofollow noreferrer">this page</a>.</p>
<p>Failing that, the best way to find the problem is to create a minimum page that can reproduce the bug. Without that, it's just about impossible to troubleshoot.</p>
| 6,137
|
<p>How do I prevent Visual Studio 2008 from automatically creating the "Mixed Platforms" and "Any CPU" solution configurations? We have "Win32" and "x64" configurations and a developer needs to choose between them. However, as soon as anyone makes any changes to the solution VS automatically creates "Mixed Platforms" and it seems to be the default configuration. This causes a lot of issues, because it turns out some new projects are not selected in this configuration or the wrong project configuration is selected, etc. I just want to stop it doing that and manage the solution configurations myself.</p>
|
<p>We see a similar issue with Visual Studio 2005 projects that we want to build both for a Win32 configuration and for a number of distinct smart device platform/configuration combinations.</p>
<p>At arbitrary times, every configuration gets auto-generated for every platform, whether it's valid or not, exploding the size of each of our ~50 project files and causing a lot of work to fix the issue.</p>
<p>It consistently happens when we open the Configuration Manager dialog, and it sometimes (but not always) happens when changing a project setting for a configuration. In the latter case, it seems to be related to manipulating the platform and configuration drop-downs on the project setting dialog.</p>
<p>We filed it as a Visual Studio issue; MSFT closed it as "won't fix".</p>
|
<p>You could filter your .sln files in a commit hook of your source control. So that if you check it in the .sln file and possibly the project files get fixed. The open source Chromium project has such a filter implemented.</p>
| 25,435
|
<p>I've inherited a piece of code with a snippet which empties the database as follows:</p>
<pre><code>dbmopen (%db,"file.db",0666);
foreach $key (keys %db) {
delete $db{$key};
}
dbmclose (%db);
</code></pre>
<p>This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.</p>
<p>Is there a better way of doing this?</p>
|
<p>You can just delete the file:</p>
<pre><code>unlink $file;
</code></pre>
<p>Since your third argument to <a href="http://perldoc.perl.org/functions/dbmopen.html" rel="nofollow noreferrer">dbmopen</a> is a file mode and not <code>undef</code>, <code>dbmopen</code> will recreate the file the next time it's called:</p>
<pre><code>dbmopen my %db, $file, 0666;
</code></pre>
|
<p>Actually, a workmate has pointed me to a solution. You can apparently do:</p>
<pre><code>dbmopen (%db,"file.db",0666);
%db = ();
dbmclose (%db);
</code></pre>
<p>which clears out the hash before closing the database.</p>
| 23,903
|
<p>I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using <em>IntelliSense</em> or using the classes in a visual designer.</p>
<p>These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about <code>ICustomTypeDescriptor</code> and <code>ICustomPropertyProvider</code>, but I'm pretty certain those can't be used in Silverlight. </p>
<p>It's not as much a functional issue as a usability issue. What should I do?</p>
<p><strong>Update</strong></p>
<p>Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the <code>new</code> operator. (I know, it's ridiculous)</p>
|
<p>Override them like Michael Suggests <a href="https://stackoverflow.com/questions/1528/#1533">above</a> and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:</p>
<pre><code>[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
</code></pre>
<p>If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated.</p>
|
<p>You can use an interface</p>
<pre><code> public static void Main()
{
NoRemoveList<string> testList = ListFactory<string>.NewList();
testList.Add(" this is ok ");
// not ok
//testList.RemoveAt(0);
}
public interface NoRemoveList<T>
{
T this[int index] { get; }
int Count { get; }
void Add(T item);
}
public class ListFactory<T>
{
private class HiddenList: List<T>, NoRemoveList<T>
{
// no access outside
}
public static NoRemoveList<T> NewList()
{
return new HiddenList();
}
}
</code></pre>
| 2,388
|
<p>We are developing a .NET 2.0 winform application. The application needs to access <a href="http://ws.lokad.com/" rel="nofollow noreferrer">Web Services</a>. Yet, we are encountering issues with users behind proxies.</p>
<p>Popular windows backup applications (think <a href="http://mozy.com/" rel="nofollow noreferrer">Mozy</a>) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me.</p>
<p>What are best ways to deal with proxy with .NET client apps?</p>
<p>More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the <em>default proxy behavior</em> of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy.</p>
<p>What should we do to enforce that the user is not prompted for his username and password when launching IE?</p>
|
<p>Put this in your application's config file:</p>
<pre><code><configuration>
<system.net>
<defaultProxy>
<proxy autoDetect="true" />
</defaultProxy>
</system.net>
</configuration>
</code></pre>
<p>and your application will use the proxy settings from IE. If you can see your web service in IE using the proxy server, you should be able to "see" it from your application.</p>
|
<p>The easiest way is to use the proxy settings from IE Explorer.</p>
| 15,483
|
<p>We've got a multiproject we're trying to run Cobertura test coverage reports on as part of our mvn site build. I can get Cobertura to run on the child projects, but it erroneously reports 0% coverage, even though the reports still highlight the lines of code that were hit by the unit tests. </p>
<p>We are using mvn 2.0.8. I have tried running <code>mvn clean site</code>, <code>mvn clean site:stage</code> and <code>mvn clean package site</code>. I know the tests are running, they show up in the surefire reports (both the txt/xml and site reports). Am I missing something in the configuration? Does Cobertura not work right with multiprojects?</p>
<p>This is in the parent .pom:</p>
<pre><code><build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<inherited>true</inherited>
<executions>
<execution>
<id>clean</id>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<inherited>true</inherited>
</plugin>
</plugins>
</reporting>
</code></pre>
<p>I've tried running it with and without the following in the child .poms:</p>
<pre><code> <reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</code></pre>
<p>I get this in the output of the build:</p>
<pre><code>...
[INFO] [cobertura:instrument]
[INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Instrumenting 3 files to C:\workspaces\sandbox\CommonJsf\target\generated-classes\cobertura
Cobertura: Saved information on 3 classes.
Instrument time: 186ms
[INFO] Instrumentation was successful.
...
[INFO] Generating "Cobertura Test Coverage" report.
[INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 3 classes.
Report time: 481ms
[INFO] Cobertura Report generation was successful.
</code></pre>
<p>And the report looks like this:
<img src="https://i.stack.imgur.com/D7yiM.png" alt="cobertura report"></p>
|
<p>From the <a href="http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition" rel="noreferrer">Spring Docs (v 2.5.5 Section 3.2.2.1.)</a>:</p>
<blockquote>
<p>It can often be useful to split up
container definitions into multiple
XML files. One way to then load an
application context which is
configured from all these XML
fragments is to use the application
context constructor which takes
multiple Resource locations. With a
bean factory, a bean definition reader
can be used multiple times to read
definitions from each file in turn.</p>
<p>Generally, the Spring team prefers the
above approach, since it keeps
container configuration files unaware
of the fact that they are being
combined with others. An alternate
approach is to use one or more
occurrences of the element
to load bean definitions from another
file (or files). Let's look at a
sample:</p>
<p></p>
<pre><code><import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</code></pre>
<p></p>
<p>In this example, external bean
definitions are being loaded from 3
files, services.xml,
messageSource.xml, and
themeSource.xml. All location paths
are considered relative to the
definition file doing the importing,
so services.xml in this case must be
in the same directory or classpath
location as the file doing the
importing, while messageSource.xml and
themeSource.xml must be in a resources
location below the location of the
importing file. As you can see, a
leading slash is actually ignored, but
given that these are considered
relative paths, it is probably better
form not to use the slash at all. The
contents of the files being imported
must be valid XML bean definition
files according to the Spring Schema
or DTD, including the top level
element.</p>
</blockquote>
|
<p>Another thing to note is that although you can do this, if you aren't a big fan of XML you can do a lot of stuff in Spring 2.5 with annotations. </p>
| 12,014
|
<p>What should i use to code Classic ASP under Linux. I have really tried to use Emacs and Vim but I don't have the time to learn them.</p>
<p>What i'm looking for is:</p>
<ul>
<li>Syntax highlighting</li>
<li>Code Browser (Ctags)</li>
<li>Preferably som sort of code insight</li>
</ul>
<p>Something like Ultra Edit or E-texteditor.</p>
|
<p>I'm not sure what you're asking here, but if you are simply looking for a text-editor, my recommendations would be:</p>
<p>Console-based:</p>
<ul>
<li>jed (simple, with a DOS Edit-like menubar, supports syntax-highlighing)</li>
<li>nano / pico (even simpler)</li>
</ul>
<p>X-based:</p>
<ul>
<li>Kate (KDE, syntax-highlighing)</li>
<li>Mousepad (like notepad)</li>
<li>SciTE (syntax-highlighing)</li>
</ul>
<p>There are of course likely to be a gazillion other text-editors better than the ones listed above, but these are the ones I tend to use.</p>
|
<p>I played with BlueFish for a while when I was contemplating switching over completely and I liked it better than Kate. But, you will have to add the code to enable ASP highlighting. Its floating around numerous places - I found it in short order with a quick trip to the trusty ole Google. ;)</p>
<p>But that is just my personal preference. Your mileage may vary.</p>
| 4,422
|
<p>Like it says.</p>
|
<p>Using semantic markup means that the (X)HTML code you use in a page contains metadata describing its purpose -- for example, an <code><h2></code> that contains an employee's name might be marked <code>class="employee-name"</code>. Originally there were some people that hoped search engines would use this information, but as the web has evolved semantic markup has been mostly used for providing hooks for CSS.</p>
<p>With CSS and semantic markup, you can keep the visual design of the page separate from the markup. This results in bandwidth savings, because the design only has to be downloaded once, and easier modification of the design because it's not mixed in to the markup.</p>
<hr>
<p>Another point is that the elements used should have a logical relationship to the data contained within them. For example, tables should be used for tabular data, <code><p></code> should be used for textual paragraphs, <code><ul></code> should be used for unordered lists, etc. This is in contrast to early web designs, which often used tables for everything.</p>
|
<p>Besides the already mentioned goal of allowing software to 'understand' the data, there are more practical applications in using it to translate between ontologies, or for mapping between dis-similar representations of data - without having to translate or standardize the data (which can result in a loss of information, and typically prevents you from improving your understanding in the future).</p>
<p>There were at least 2 sessions at OSCon this year related to the use of semantic technologies. One was on BigData (slides are available here: <a href="http://en.oreilly.com/oscon2008/public/schedule/proceedings" rel="nofollow noreferrer">http://en.oreilly.com/oscon2008/public/schedule/proceedings</a>, the other was the guys from <a href="http://www.freebase.com/" rel="nofollow noreferrer">FreeBase</a>.</p>
<p>BigData was using it to map between two dis-similar data models (including the use of query languages which were specifically created for working with semantic data sets). FreeBase is mapping between different data sets and then performing further analysis to derive meaning across those data sets.</p>
<p>Related topics to look into: OWL, OQL, SPARQL, <a href="http://www.franz.com/" rel="nofollow noreferrer">Franz</a> (AllegroGraph, RacerPRO and TopBraid).</p>
| 14,440
|
<p>I have a asp.net web application which has a number of versions deployed on different customer servers inside their networks. One practice that we have is to have clients email screenshots when they have issues.</p>
<p>In the old asp.net 1.1 days, we could grab details of the build DLL, using reflection, and show info about the build date and numbering on the screen in a subtle location.</p>
<p>With .NET 2.0 and higher, the build model changed, and this mechanism no longer works. I have heard of different build systems out there, but I'm really looking for the simplest way, on the 3.5 framework, to do what this functionality did on framework 1.1.</p>
<ol>
<li>Every time a build is performed, update the build date/time, and somehow update the build number</li>
<li>Be able to see the build timestamp and number, to display on the screen</li>
<li>be as simple to implement as possible </li>
</ol>
|
<p>We are using .Net 2.0 and pull the version information out of the assembly. Perhaps not ideal, but we use the description to store the build date.</p>
<pre><code>Assembly assembly = Assembly.GetExecutingAssembly();
string version = assembly.GetName().Version.ToString();
string buildDate = ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
assembly, typeof(AssemblyDescriptionAttribute))).Description;
</code></pre>
<p>The build process uses asminfo nant task to generate the AssemblyInfo.cs file that contains this information.</p>
<pre><code> <asminfo output="Properties\AssemblyInfo.cs" language="CSharp">
<imports>
<import namespace="System" />
<import namespace="System.Reflection" />
<import namespace="System.Runtime.CompilerServices" />
<import namespace="System.Runtime.InteropServices" />
</imports>
<attributes>
<attribute type="AssemblyVersionAttribute" value="${assembly.version}" />
<attribute type="AssemblyInformationalVersionAttribute" value="${assembly.version}" />
<attribute type="AssemblyDescriptionAttribute" value="${datetime::now()}" />
...
</attributes>
</asminfo>
</code></pre>
|
<p>You can get the Assembly Build date through reflection, check this examples:</p>
<ul>
<li><a href="http://blog.codinghorror.com/determining-build-date-the-hard-way/" rel="nofollow noreferrer">Determining Build Date the hard way</a></li>
<li><a href="http://dotnetfreak.co.uk/blog/archive/2004/07/08/determining-the-build-date-of-an-assembly.aspx" rel="nofollow noreferrer">Determining the Build Date of an Assembly</a></li>
</ul>
| 41,990
|
<p>Say I have a site on <a href="http://example.com" rel="noreferrer">http://example.com</a>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words</p>
<p><a href="http://example.com" rel="noreferrer">http://example.com</a> & <a href="http://example.com/" rel="noreferrer">http://example.com/</a> should be allowed, but
<a href="http://example.com/anything" rel="noreferrer">http://example.com/anything</a> and <a href="http://example.com/someendpoint.aspx" rel="noreferrer">http://example.com/someendpoint.aspx</a> should be blocked.</p>
<p>Further it would be great if I can allow certain query strings to passthrough to the home page:
<a href="http://example.com?okparam=true" rel="noreferrer">http://example.com?okparam=true</a> </p>
<p>but not
<a href="http://example.com?anythingbutokparam=true" rel="noreferrer">http://example.com?anythingbutokparam=true</a></p>
|
<p>So after some research, here is what I found - a solution acceptable by the major search providers: <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40367" rel="noreferrer">google</a> , <a href="http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-02.html" rel="noreferrer">yahoo</a> & msn (I could on find a validator here) :</p>
<pre><code>User-Agent: *
Disallow: /*
Allow: /?okparam=
Allow: /$
</code></pre>
<p>The trick is using the $ to mark the end of URL.</p>
|
<p>Basic robots.txt:</p>
<pre><code>Disallow: /subdir/
</code></pre>
<p>I don't think that you can create an expression saying 'everything but the root', you have to fill in all sub directories.</p>
<p>The query string limitation is also not possible from robots.txt. You have to do it in the background code (the processing part), or maybe with server rewrite-rules.</p>
| 6,503
|
<p>Are you aware of any tool that creates diagrams showing the branch/merge activity in a SVN repository?</p>
<p>We've all seen these diagrams in various tutorials. Some good, some not so good. Can they be created automatically (or maybe with a little prodding -- you might have to tell it what if your branching philosophy is dev-test-prod, branch-per-release, etc.)</p>
<p>I'm looking at the TortoiseSVN Revision Graph right now, but it has more detail than I want and the wrong layout.</p>
<hr>
<p>Orion, thanks for the response. I guess since branching and merging are more a convention for managing files in a repository than a "built in feature of SVN, it would be pretty tough. I'll stick with the poorly-drawn diagram at the top of the whiteboard in our team's office.</p>
|
<p>Check this out <a href="http://svnmapper.tigris.org/" rel="noreferrer">SvnMapper from Tigris.org</a></p>
<p><img src="https://i.stack.imgur.com/tlCvQ.png" alt="enter image description here"></p>
|
<p>prior to SVN 1.5 (which has been out all of a month or so), it didn't track merges at all, so the bits where branches 'reconnect' to the trunk are impossible for it to do anyway</p>
| 3,152
|
<p>So here's my current code:</p>
<pre><code>List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value);
bool found = false;
System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
foreach (string group in rowGroups)
{
if (p.IsInRole(group))
{
found = true;
break;
}
}
</code></pre>
<p>This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using.</p>
<p>The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the <code>List<string></code> object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD".</p>
<p>So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned.</p>
<p>Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...</p>
|
<p>Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (<code>Monitor</code> or <code>lock</code> your properties).</p>
<p>However, multiple <em>processes</em> should be in separate AppDomains and therefore each have their own instance.</p>
|
<p>The scope of a static class is limited to the application domain. Each app domain will have its own copy of any static variables you might have. If your "processes" are threads within the same app domain, then they will share the static values. But if they are actual separate Windows processes, then they will have different app domains and hence separate copies. </p>
| 36,098
|
<p>I've seen many website designs with frequent inclusions of 'back to top' links and am just wondering when, if ever, they can really be justified? What use cases demand a 'back top top' link, and what are their effects on usability?</p>
|
<p>I think they can be useful when there is a table of contents at the top of the page, and the content is not sequential - like a FAQ.</p>
|
<p>I think it's useful when on first thing on the page is a table of contents, each link of which takes the user to some bottom part of this rather long page. Common example is a FAQ page with all Qs on the same page.</p>
| 45,157
|
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow noreferrer">Mac OS X Leopard</a> and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future.</p>
<p>I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?</p>
|
<p>Most Python applications are moving away from mod_python. It can vary by framework or provider, but most development effort is going into mod_wsgi.</p>
<p>Using the <a href="https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="nofollow noreferrer">WSGI</a> standard will make your Python application server agnostic, and allow for other nice additions like WSGI middleware. Other providers may only provide <a href="http://en.wikipedia.org/wiki/Common_Gateway_Interface" rel="nofollow noreferrer">CGI</a> (which won't scale well performance wise), or <a href="http://en.wikipedia.org/wiki/FastCGI" rel="nofollow noreferrer">FastCGI</a>.</p>
|
<p>What you're looking for is Mod_Python. It's an Apache-based interpreter for Python. Check it out here:</p>
<p><a href="http://www.modpython.org/" rel="nofollow noreferrer">http://www.modpython.org/</a></p>
| 33,365
|
<p>I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn't work in Internet Explorer.</p>
<p>Here is the JavaScript I have:</p>
<pre class="lang-js prettyprint-override"><code>function SetTopMargin (ObjectID, Value)
{
document.getElementById(ObjectID).style.marginTop = Value.toString() + "px";
}
</code></pre>
<p>And it is called like this:</p>
<pre class="lang-js prettyprint-override"><code>SetTopMargin("test_div_id", 100);
</code></pre>
<p>So does anyone know some code that will work in Internet Explorer?</p>
|
<p>[Updated in 2016] On all current browsers (including IE8+), your code</p>
<pre><code>document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px';
</code></pre>
<p>works fine.</p>
<p>On <em>very old</em> IE (< 8) versions, you must use this non-standard contraption instead:</p>
<pre><code>document.getElementById(ObjectId).style.setAttribute(
'marginTop', Value.ToString() + 'px');
</code></pre>
<p><strong>EDIT</strong> - From deleted comment by OP:</p>
<blockquote>
<p>Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..)</p>
</blockquote>
|
<p>First of all, you should really use a javascript library like jQuery or Dojo. I also recommend www.debugbar.com for inspecting IE's DOM.</p>
<p>About your problem, <code>elem.style = "margin: 10px"</code> should work in IE.</p>
<p>Hope this helps!</p>
| 41,109
|
<p>I just ran a "PROCEDURE ANALYSE ( )" on one of my tables. And I have this column that is of type INT and it only ever contains values from 0 to 12 (category IDs).
And MySQL said that I would be better of with a ENUM('0','1','2',...,'12'). This category's are basically static and won't change in the future, but if they do I can just alter that column and add it to the ENUM list...</p>
<p>So why is ENUM better in this case?</p>
<p>edit: I'm mostly interested in the performance aspect of this...</p>
|
<p>Put simply, it's because it's indexed in a different way.</p>
<p>In this case, <code>ENUM</code> says "It's one of these 13 values" whereas <code>INT</code> is saying "It could be any integer."</p>
<p>This means that indexing is easier, as it doesn't have to take into account indexing for those integers you don't use "just in case" you ever use them.</p>
<p>It's all to do with the algorithms.</p>
<p>I'd be interested myself though when it gets to a point where the <code>INT</code> would be quicker than the <code>ENUM</code>.</p>
<p>Using numbers in an <code>ENUM</code> might be a little dangerous though... as if you send this number unquoted to SQL - you might end up getting the wrong value back!</p>
|
<p>On Oracle I would have a BITMAP index which is much faster than a hash-based lookup for such a small number of values. (So I presume a similar benefit in query optomisation or indexing is available for MySQL.) </p>
<p>Interestingly The MySQL docs suggest that using 'things that look like numbers' are a bad choice for the ENUM type because of potential confusion between the enum value and the enum index (<a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/enum.html</a>). </p>
| 13,872
|
<p>I just came onto a project with a pretty huge code base. </p>
<p>I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. </p>
<pre><code> if (!!variable && (!!api.lookup("some-string"))) {
do_some_stuff();
}
</code></pre>
<p>I know these guys are intelligent programmers, it's obvious they aren't doing this by accident. </p>
<p>I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value. </p>
<p>Is this correct, or am I missing something?</p>
|
<p>It's a trick to convert to bool.</p>
|
<p>It's correct but, in C, pointless here -- 'if' and '&&' would treat the expression the same way without the '!!'.</p>
<p>The reason to do this in C++, I suppose, is that '&&' could be overloaded. But then, so could '!', so it doesn't <em>really</em> guarantee you get a bool, without looking at the code for the types of <code>variable</code> and <code>api.call</code>. Maybe someone with more C++ experience could explain; perhaps it's meant as a defense-in-depth sort of measure, not a guarantee.</p>
| 30,908
|
<p>I have a Mini Kossel and I am going through calibration.</p>
<p>I can home carriages and find the bed with paper-test getting some Z value with <code>M114</code>. Then I run the effector almost full height <strong>up and then down</strong> - and now <strong>Z value for the bed is greater</strong>!</p>
<p>If I repeat the process I get greater and greater values in paper-test. It seems that travel per step is different moving in different directions.</p>
<p>How can I fix that? I am using RAMPS 1.4 with Marlin firmware.</p>
<p>UPDATE:</p>
<p>Z values near bed after subsequent runs of five passes of <code>G1 X100 G1 X10</code></p>
<pre><code>100% speed: 0.1 0.3 0.5 0.7 1.0
20% speed: 0.1 0.4 0.9 1.4 4.6 6.6
300% speed: 0.0 0.7 1.0 1.3
</code></pre>
|
<p>After some more testing I checked that the problem shows up only on Z tower and is not related with current. Examining the tower I found very dumb mistake. Pulley on the motor didn't have a setscrew! Don't know how could I missed that. The fact that it could somehow run is even more amazing. Thanks @tom-van-der-zanden and @darthpixel for help. It is for sure that such synchronization failure could have been caused by current shortage as well.</p>
<p>UPDATE:</p>
<p>Oh! Y tower pulley doesn't have setscrew as well! But it was running smoothly and in sync with X (which has that screw). Amazing. - UPDATE2. Not really. After closer look only Z tower misses the screw, which explains all.</p>
<p>UPDATE3:</p>
<p>After setting a srew into pulley the problem is completely gone!)</p>
|
<p>According to discussions in comments, I'm pretty sure the problem lies in too low current. </p>
<p>Please review <a href="https://3dprinting.stackexchange.com/questions/1480/how-do-you-make-sure-you-have-the-right-voltage-on-the-timpots-on-a-a4988-steppe/1483#1483">this answer</a> to <a href="https://3dprinting.stackexchange.com/questions/1480/how-do-you-make-sure-you-have-the-right-voltage-on-the-timpots-on-a-a4988-steppe/">How do you make sure you have the right voltage on the trimpots on a A4988 stepper driver?</a>.</p>
<p><strong>Why it happens?</strong></p>
<p>If there is not enough current then motors can omit some steps as the stress is not equal while going up and down. Sometimes inertia can have higher influence than friction.</p>
<p>Additionally because the resistance/stress/friction on towers is different for sure then there are some issues in centering hotend.</p>
<p>So friction/inertia/assembly inaccuracy and current settings inaccuracy can cause such effects. If you are "on the edge" your printer may work well one day but the other day it can fail positioning. </p>
<p>Please refer to post mentioned above. Perform calibration and temperature test (finger test could be ok). I hope you'll manage the issue.</p>
| 371
|
<p>My question is in regards to MySQL, but I also wonder how this affects other databases. I have several fields that are <code>varchar(255)</code> but my coworker insists if they were <code>varchar(30)</code> -- or any smaller size -- then queries would run faster. I'm not so sure, but if it's so I'll admit to it.</p>
|
<p>It depends on the query and the data, but you're probably optimizing too soon to even be worried.</p>
<p>For SELECT queries, the statement itself will run just as fast within MySQL, and as long as the data doesn't get larger than it would be at the smaller sized field then it will transmit as fast. If the smaller field forces you to store the information in a smaller space (would you use the extra 225 chars?), then you will get fast transmission to other programs.</p>
<p>For INSERT queries the size of the field isn't an issue, but using variable length fields will slow the process done. INSERTs with fixed length rows are notably faster (at least in MySQL 5.0 and earlier).</p>
<p>Generally, use the size you need for the data. If you don't know if you need 255 chars or 30 chars you're probably optimizing too soon. Are large data fields causing a bottleneck? Is you program suffering from database performance problems at all? Find your bottlenecks first, solve the problem with them second. I'd guess the difference in time you're looking at here is unimportant to whatever problem you are trying to solve. </p>
|
<p>If you're only ever using the first 30 characters, then there won't be a difference between a varchar(30) and a varchar(255) (although there would be a difference with varchar(1000), which would take an extra byte).</p>
<p>Of course, if you end up using more than 30 characters, it will be slower as you have more data to pass to the client, and your indexes will be larger.</p>
| 25,063
|
<p>This certainly presupposes that unit testing is a good thing. Our projects have some level of unit testing, but it's inconsistent at best.</p>
<p>What are the most convincing ways that you have used or have had used with you to convince everyone that formalized unit testing is a good thing and that making it required is really in the best interest of the 'largeish' projects we work on. I am not a developer, but I am in Quality Assurance and would like to improve the quality of the work delivered to ensure it is ready to test.</p>
<p>By formalized unit tests, I'm simply talking about </p>
<ul>
<li>Identifying the Unit Tests to be written</li>
<li>Identifying the test data (or describe it)</li>
<li>Writing these tests</li>
<li>Tracking these tests (and re-using as needed)</li>
<li>Making the results available</li>
</ul>
|
<p>The event which convinced me was when we managed to regress a bug three times, in three consecutive releases. Once I realised how much more productive I was as a programmer when I wasn't constantly fixing trivial mistakes after they had gone to the client, and I could have a warm fuzzy feeling that colleagues code would do what they claimed it would, I became a convert.</p>
|
<p>Remind your team or the other developers that they're professionals, not amateurs. Worked for me!</p>
<p>Also, it's an industry standard these days. Without unit testing experience, they are less desirable and less valuable as employees to potential future employers.</p>
| 14,646
|
<p>I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).</p>
<p>Basically, I need to check for IsPostBack in JavaScript.</p>
<p>Thank you.</p>
|
<p>Server-side, write:</p>
<pre><code>if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
</code></pre>
<p>Then, in your script which runs for the onLoad, check for the existence of that variable:</p>
<pre><code>if(isPostBack) {
// do your thing
}
</code></pre>
<hr>
<p>You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.</p>
|
<p>You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.</p>
| 8,439
|
<p>I have populated a Datatable, from 2 different servers. I am able to make adjustments where my length>0, what I want to do is remove the rows that does not hit. Here is a summary of what I have</p>
<pre><code>DataRow[] dr = payments.dtPayments.Select(myselect);
if (dr.Length > 0)
{
for (int a = 0; a < dr.Length; a++)
{
if (thisOption == true)
dr[0].Delete();
else if (otherOption == true)
{
dr[0]["Date"] = myDataReader["date"].ToString().Trim();
dr[0]["Pay"] = payTypeName(myDataReader["ccdsrc"].ToString()
.Trim());
}
}
}
if (dr.Length == 0)
{
if (LastOption == true)
{
//DataRow should be removed
}
}
</code></pre>
|
<p>I'm not sure I completely understand your question but it seems that you try to remove an entry from the collection while you are still looping over it. (which will cause an array index error)</p>
<p>You should save a reference to each entry you want to delete in a new collection and then remove all the new entries from the old collection:</p>
<pre><code>DataRow[] dr = payments.dtPayments.Select(myselect);
List<DataRow> rowsToRemove = new List<DataRow>();
for (int a = 0; a < dr.Length; a++) {
if(/* You want to delete this row */) {
rowsToRemove.Add(dr[a]);
}
}
foreach(var dr in rowsToRemove) {
payments.dtPayments.Rows.Remove(dr);
}
</code></pre>
|
<p>Have you tryed this?</p>
<p>payments.dtPayments.Rows.Remove(dr)</p>
| 40,649
|
<p>I have a variable of type Hashmap<code><String,Integer</code>>.</p>
<p>In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...</p>
<pre><code>Hashmapvariable.put( somestring,
if (flag_variable) {
//manipulation code goes here
new Integer(manipulated value);
} else {
new Integer(non-manipulated value);
}
);
</code></pre>
<p>But I get an error: </p>
<blockquote>
<p>Syntax error on token(s), misplaced
constructs.</p>
</blockquote>
<p>at the Hashmapvariable.put call.</p>
<p>I also get another error</p>
<blockquote>
<p>Syntax error on token ")", delete this
token.</p>
</blockquote>
<p>at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.</p>
<p>I don't get this. What mistake am I doing?</p>
|
<p>You cannot place a statement in the method call.</p>
<p>However, one option could be to make an method that returns a <code>Integer</code> such as:</p>
<pre><code>private Integer getIntegerDependingOnFlag(boolean flag)
{
if (flag)
return new Integer(MANIPULATED_VALUE);
else
return new Integer(NON-MANIPULATED_VALUE);
}
</code></pre>
<p>Then, you can make a call like this:</p>
<pre><code>hashmap.put(someString, getIntegerDependingOnFlag(flag));
</code></pre>
|
<p>This isn't scheme, so if statements don't evaluate to a value. You'll have to use a tri-if-thing (the name escapes me for some reason right now) or create a function, as someone else said.</p>
| 40,255
|
<p>I'd like to show an image in an iPhone app, but the image I'm using is too big.
I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.</p>
|
<pre><code>UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"your_image.png"]];
view.frame = CGRectMake(0, 0, width, height);
</code></pre>
<p>To get the frame of the iPhone screen you can use</p>
<pre><code>CGRect frame = [[UIScreen mainScreen] bounds];
</code></pre>
|
<p>My ImageView was set in IB, and I would need to show multiple images, so set the image of imageView, instead of creating ImageView for individual image. </p>
<p>After I set the image view frame size, I am still see the same result, the image was too big, so that only part of the image was displayed on the screen.</p>
| 30,436
|
<p>I use XML serialization for the reading of my Config-POCOs. </p>
<p>To get intellisense support in Visual Studio for XML files I need a schema file. I can create the schema with xsd.exe mylibrary.dll and this works fine.</p>
<p>But I want that the schema is always created if I serialize an object to the file system. Is there any way without using xsd.exe?</p>
|
<p>thank you, this was the right way for me.
solution:</p>
<pre><code>XmlReflectionImporter importer = new XmlReflectionImporter();
XmlSchemas schemas = new XmlSchemas();
XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
Type type = toSerialize.GetType();
XmlTypeMapping map = importer.ImportTypeMapping(type);
exporter.ExportTypeMapping(map);
TextWriter tw = new StreamWriter(fileName + ".xsd");
schemas[0].Write(tw);
tw.Close();
</code></pre>
|
<p>Improvement to Matt Murrell version: to apply XmlAttributes recursively for nested property user type (for example CustomerClass property).</p>
<pre><code>private static void AttachXmlAttributes(XmlAttributeOverrides xao, List<Type> all, Type t)
{
if (all.Contains(t))
{
return;
}
else
{
all.Add(t);
}
var list1 = GetAttributeList(t.GetCustomAttributes(false));
xao.Add(t, list1);
foreach (var prop in t.GetProperties())
{
var propType = prop.PropertyType;
if (propType.IsGenericType) // is list?
{
var args = propType.GetGenericArguments();
if (args != null && args.Length == 1)
{
var genType = args[0];
if (genType.Name.ToLower() != "object")
{
var list2 = GetAttributeList(prop.GetCustomAttributes(false));
xao.Add(t, prop.Name, list2);
AttachXmlAttributes(xao, all, genType);
}
}
}
else
{
var list2 = GetAttributeList(prop.GetCustomAttributes(false));
xao.Add(t, prop.Name, list2);
AttachXmlAttributes(xao, all, prop.PropertyType);
}
}
}
private static XmlAttributes GetAttributeList(object[] attributes)
{
var list = new XmlAttributes();
foreach (var attr in attributes)
{
Type type = attr.GetType();
switch (type.Name)
{
case "XmlAttributeAttribute":
list.XmlAttribute = (XmlAttributeAttribute)attr;
break;
case "XmlRootAttribute":
list.XmlRoot = (XmlRootAttribute)attr;
break;
case "XmlElementAttribute":
list.XmlElements.Add((XmlElementAttribute)attr);
break;
case "XmlArrayAttribute":
list.XmlArray = (XmlArrayAttribute)attr;
break;
case "XmlArrayItemAttribute":
list.XmlArrayItems.Add((XmlArrayItemAttribute)attr);
break;
}
}
return list;
}
</code></pre>
| 43,721
|
<p>I want a checkbox on a web page. When I click it, it sends an ajax request to the server. When the server replies, I want the checkbox to change. I can fix everything except the fact that the checkbox immediately changes state when clicked. </p>
|
<p>Are you sure you really want this? An Ajax-Request can take its time. When the user gets no feedback, they may be inclined to click again and again, until something happens. When this deactivates the button (again after some time) the user gets even more puzzled.</p>
<p>Rather think about providing immediate feedback (e.g. check the box) and display an indicator next to it, that signals communication with the server (e.g. the famous spinning wheel). When the result is back, hide the indicator and deactivate the checkbox if needed. You may also want to inhibit posting the form during the ajax request.</p>
|
<p>You could start your onchange method with <code>checkbox.checked=NOT checkbox.checked</code> (you may have to modify this for your language of choice), you'll probably get a flicker but it should put it back quickly enough.</p>
| 23,197
|
<p>I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)</p>
<pre><code>System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
</code></pre>
<p>What is the problem with my regular expression?</p>
|
<p>The problem is the space in the name of the capture. Remove the space and it works fine.</p>
<p>From the MSDN documentation:
"The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')."</p>
<p>It does not matter if you use angle brackets <> or single quotes '' to indicate a group name.</p>
|
<p>The problem is your quotes around the name of the named capture group. Try the string: (?<Named>asdf)</p>
| 14,965
|
<p>The auto-collapse feature for <em>code</em> properties is neat AFTER you've got your properties all worked out, but while you're still editing them I find the feature to be REALLY annoying.</p>
<p><strong>How can you disable it?</strong></p>
<p>(I'm in VS2008 if it makes a difference)</p>
<p>Edit: I'm not talking about the Property Window... I'm talking about properties in code.</p>
<pre><code>Private _firstName As String
Public Property FirstName() As String Implements IPerson.FirstName
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
</code></pre>
<p>displays as </p>
<pre><code>Public Property FirstName()...
</code></pre>
|
<p>From the EDIT menu, choose OUTLINING, STOP OUTLINING. You can also use the keyboard shortcut CTRL+M, CTRL+P.</p>
|
<p>When the window is open, click on the pin in the upper right hand corner (the middle icon between the X and the down arrow). When you're done, click it again to enable auto hide again.</p>
| 28,019
|
<p>I need to do a number of network-related things in C++ that I would normally do with <code>ifconfig</code> in Linux, but I'd like to do it without parsing the output of a group of system calls. Which C or C++ libraries can I use to tell if a network adapter is up or down, read or change an adapter's IP address and netmask, and change the default DNS gateway?</p>
|
<p>Basically you need to make a bunch of ioctl calls using a socket handle (SIOCGIFADDR, SIOCADDRT). You can find sample programs that use it in the Linux kernel source under Documentation/networking. Some other links that might be helpful:</p>
<ul>
<li><a href="http://www.ibm.com/developerworks/aix/library/au-ioctl-socket.html" rel="nofollow noreferrer">Network Interface operations on AIX</a></li>
<li><a href="http://xbmc.org/trac/browser/branches/linuxport/XBMC/xbmc/linux/NetworkLinux.cpp" rel="nofollow noreferrer">XBMC's implementation</a> (check out CNetworkInterfaceLinux)</li>
</ul>
<p>EDIT: Let me also add that if your target is desktop linux, then you can consider using the DBUS API to query network parameters using the NetworkManager.</p>
<ul>
<li><a href="http://people.redhat.com/dcbw/NetworkManager/NetworkManager" rel="nofollow noreferrer">http://people.redhat.com/dcbw/NetworkManager/NetworkManager</a> DBUS API.txt (sorry there's some issue inserting links in edits)</li>
</ul>
|
<p>The <a href="http://projects.gnome.org/NetworkManager/" rel="nofollow noreferrer">NetworkManager</a> service exposes an API over <a href="http://www.freedesktop.org/wiki/Software/dbus" rel="nofollow noreferrer">dbus</a> for querying/manipulating the networking on many distributions these days. This may be too high-level for your purposes (e.g. you require finer control of the network, or dbus/NetworkManager are not available on the system...), but it may provide you with what you need.</p>
<p>Check out the <a href="http://www.freedesktop.org/wiki/Software/dbus-c%2B%2B" rel="nofollow noreferrer">dbus C++ bindings</a> and the <a href="http://people.redhat.com/dcbw/NetworkManager/NetworkManager%20DBUS%20API.txt" rel="nofollow noreferrer">NetworkManager API</a> (sorry, I can't find a better formatted version right now, but the information is there).</p>
| 49,622
|
<p>Change Data Capture is a new feature in SQL Server 2008. From MSDN:</p>
<blockquote>
<p>Change data capture provides
historical change information for a
user table by capturing both the fact
that DML changes were made and the
actual data that was changed. Changes
are captured by using an asynchronous
process that reads the transaction log
and has a low impact on the system</p>
</blockquote>
<p>This is highly sweet - no more adding CreatedDate and LastModifiedBy columns manually.</p>
<p>Does Oracle have anything like this?</p>
|
<p>Sure. Oracle actually has a number of technologies for this sort of thing depending on the business requirements.</p>
<ul>
<li>Oracle has had something called <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14253/long_intro.htm#ADWSM010" rel="noreferrer">Workspace Manager</a> for a long time (8i days) that allows you to version-enable a table and track changes over time. This can be a bit heavyweight, though, because it is based on views with instead-of triggers.</li>
<li>Starting in 11.1 (as an extra cost option to the enterprise edition), Oracle has a Total Recall that asynchronously mines the redo logs for data changes that get logged to a separate table which can then be queried using flashback query syntax on the main table. Total Recall is automatically going to partition and compress the historical data and automatically takes care of purging the data after a specified data retention period.</li>
<li>Oracle has a LogMiner technology that mines the redo logs and presents transactions to consumers. There are a number of technologies that are then built on top of LogMiner including <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/cdc.htm#sthref889" rel="noreferrer">Change Data Capture</a> and <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14229/strms_over.htm#STRMS001" rel="noreferrer">Streams</a>.</li>
<li>You can also use materialized views and materialized view logs if the goal is to replicate changes.</li>
</ul>
|
<p>I believe Oracle has provided auditing features since 8i, however the tables used to capture the data are rather complex and there is a significant performance impact when this is turned on.</p>
<p>In Oracle 8i you could only enable this for an entire database and not a table at a time, however 9i introduced Fine Grained Auditing which provides far more flexibility. This has been expanded upon in 10/11g.</p>
<p>For more information see <a href="http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html" rel="nofollow noreferrer">http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html</a>.</p>
<p>Also in 11g Oracle introduced the Audit Vault, which provides secure storage for audit information, even DBA's cannot change this data (according to Oracle's documentation, I haven't used this feature yet). More info can be found at <a href="http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html" rel="nofollow noreferrer">http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html</a>.</p>
| 18,788
|
<p>Inside a visual studio project I have the following folders (for example)</p>
<ul>
<li>foo/ </li>
<li>bar/</li>
<li>LongFolderName/</li>
</ul>
<p>When I open up a file in LongFolderName/ the tab gets labeled with <code>LongFolderName/L...me.ascx</code> when I'd prefer <code>LongFileName.ascx</code> (omitting the name of the folder). Any way to set Visual Studio to ignore the folder name when labeling the tab?</p>
<p>EDIT: here is what my tab bar looks like:</p>
<p><a href="http://img355.imageshack.us/img355/7040/tabsmn7.png">http://img355.imageshack.us/img355/7040/tabsmn7.png</a> </p>
<p>Notice how the names of my files are truncated past readability. I've got "EventCalendar," "MonthlyEventCalendar," and "WeeklyEventCalendar" and as it stands its rather hard to tell the difference. I know that these files are in UserControls/. How do I get VS to stop telling me?</p>
<p>EDIT:
The name of the file in the <strong>Window | Windows</strong> menu is <code>longfoldername/longfilename</code> as is the title of the window if I switch VS to MDI interface. </p>
|
<p><a href="http://www.tabsstudio.com" rel="nofollow noreferrer">Tabs Studio add-in</a> for Visual Studio that replaces built-in Visual Studio tabs doesn't shorten tab names and has option to remove path from tab name.</p>
|
<p>If you click on the <strong>Window | Windows...</strong> menuitem, what do the Name and Path fields look like for your open documents?</p>
<p>On my install, the Name fields are just the filenames, exactly what appears in the tabs.</p>
<p>Do the full paths appear in the window titles if you set the Window layout to "Multiple documents"?</p>
| 27,968
|
<p>I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.</p>
<p>I'd like to read the values of assembly attributes in these assemblies.</p>
<p>This can be achieved using <code>Assembly.ReflectionOnlyLoad</code>, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.</p>
<p>At this point I'm assuming the solution will involve using temporary <code>AppDomain</code>s.</p>
<p>Can someone detail how to load an assembly into another <code>AppDomain</code>, read the attributes from it and then unload the <code>AppDomain</code>?</p>
<p>This needs to work for assemblies on the file system as well as those at URL addresses.</p>
|
<p>From the <a href="http://msdn.microsoft.com/en-us/library/0et80c7k.aspx" rel="noreferrer">MSDN documentation of System.Reflection.Assembly.ReflectionOnlyLoad (String)</a> :</p>
<blockquote>
<p>The reflection-only context is no
different from other contexts.
Assemblies that are loaded into the
context can be unloaded only by
unloading the application domain.</p>
</blockquote>
<p>So, I am afraid the only way to unload an assembly is unloading the application domain.
To create a new AppDomain and load assemblies into it:</p>
<pre><code>public void TempLoadAssembly()
{
AppDomain tempDomain = AppDomain.CreateDomain("TemporaryAppDomain");
tempDomain.DoCallBack(LoaderCallback);
AppDomain.Unload(tempDomain);
}
private void LoaderCallback()
{
Assembly.ReflectionOnlyLoad("YourAssembly");
// Do your stuff here
}
</code></pre>
|
<p>You can try to use <a href="http://msdn.microsoft.com/en-us/library/ms404434.aspx" rel="nofollow noreferrer">Unmanaged Metadata API</a>, which is COM and can easily be used from .NET application with some kind of wrapper. </p>
| 27,850
|
<p>I found a bug in Delphi 2009's implementation of TFields and wrote a quick patch. I copied DB.pas to my projects folder and added it to the project's file list, but now I can't get it to compile. The first two error messages don't even make any sense when I go to the indicated places in the code.</p>
<p>Surely if anything can be counted on to compile properly, it's the code from CodeGear. They've already managed to compile it, to produce the VCL components. So what am I missing? Here's the compiler's output:</p>
<pre><code>[DCC Error] DB.pas(2536): E2134 Type 'Pointer' has no type info
[DCC Error] DB.pas(10799): E2066 Missing operator or semicolon
[DCC Error] DB.pas(12933): E2217 Published field 'FCursor' not a class or interface type
[DCC Error] DB.pas(12934): E2217 Published field 'FTitle' not a class or interface type
[DCC Fatal Error] testing.dpr(23): F2063 Could not compile used unit '..\..\..\vclpatch\DB.pas'
</code></pre>
|
<p>Does it help if you add the following line at the top of the DB.pas unit.</p>
<p>{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N-,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}</p>
<p>If it works after using this line, then your project options are not compatible with the settings that CodeGear used to compile the RTL/VCL.</p>
<p>BTW: Line 2536 is a line that contains only the text "type". Have you changed the file? Or are you missing Update 1?</p>
|
<p>I ran into the same problem with DB.pas but did never modify any VCL units. So the cause clearly had to be my project. Switching <strong>Emit runtime type information</strong> to <strong>false</strong> did the trick and solved the problem.</p>
<p>(Project Options: Delphi Compiler -> Compiling -> Code generation -> Emit runtime type information)</p>
| 45,268
|
<p>Say I have the following web.config:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Windows"></authentication>
</system.web>
</configuration>
</code></pre>
<p>Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?</p>
|
<p>The mode property from the authenticationsection: <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx" rel="noreferrer">AuthenticationSection.Mode Property (System.Web.Configuration)</a>. And you can even modify it.</p>
<pre><code>// Get the current Mode property.
AuthenticationMode currentMode =
authenticationSection.Mode;
// Set the Mode property to Windows.
authenticationSection.Mode =
AuthenticationMode.Windows;
</code></pre>
<p>This article describes <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx" rel="noreferrer">how to get a reference to the AuthenticationSection</a>.</p>
|
<p>use an xpath query //configuration/system.web/authentication[mode] ?</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
XmlDocument config = new XmlDocument();
config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication");
this.Label1.Text = node.Attributes["mode"].Value;
}
</code></pre>
| 11,729
|
<p>How do I make all occurrences of a phrase (search term) in a file to be highlighted in the VS code editor?</p>
|
<p>When you run a "find" you can click "bookmark all"
which will identify on the left which lines the search terms occur on, but you can't "highlight" the elements using visual studio, out of the box.</p>
|
<p>I copied and pasted the source code into Word 2007. This has highlight all option called 'Reading Highlight'. This keeps the highlighting on even when you search for another term.</p>
| 32,056
|
<p>We all know what virtual functions are in C++, but how are they implemented at a deep level?</p>
<p>Can the vtable be modified or even directly accessed at runtime?</p>
<p>Does the vtable exist for all classes, or only those that have at least one virtual function? </p>
<p>Do abstract classes simply have a NULL for the function pointer of at least one entry?</p>
<p>Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.</p>
|
<h2>How are virtual functions implemented at a deep level?</h2>
<p>From <a href="http://wayback.archive.org/web/20100209040010/http://www.codersource.net/published/view/325/virtual_functions_in.aspx" rel="noreferrer">"Virtual Functions in C++"</a>:</p>
<blockquote>
<p>Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.</p>
</blockquote>
<h2>Can the vtable be modified or even directly accessed at runtime?</h2>
<p>Universally, I believe the answer is "no". You could do some memory mangling to find the vtable but you still wouldn't know what the function signature looks like to call it. Anything that you would want to achieve with this ability (that the language supports) should be possible without access to the vtable directly or modifying it at runtime. Also note, the C++ language spec <strong>does not</strong> specify that vtables are required - however that is how most compilers implement virtual functions.</p>
<h2>Does the vtable exist for all objects, or only those that have at least one virtual function?</h2>
<p>I <em>believe</em> the answer here is "it depends on the implementation" since the spec doesn't require vtables in the first place. However, in practice, I believe all modern compilers only create a vtable if a class has at least 1 virtual function. There is a space overhead associated with the vtable and a time overhead associated with calling a virtual function vs a non-virtual function.</p>
<h2>Do abstract classes simply have a NULL for the function pointer of at least one entry?</h2>
<p>The answer is it is unspecified by the language spec so it depends on the implementation. Calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). In practice it does allocate a slot in the vtable for the function but does not assign an address to it. This leaves the vtable incomplete which requires the derived classes to implement the function and complete the vtable. Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion.</p>
<p>Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override.</p>
<h2>Does having a single virtual function slow down the whole class or only the call to the function that is virtual?</h2>
<p>This is getting to the edge of my knowledge, so someone please help me out here if I'm wrong!</p>
<p>I <em>believe</em> that only the functions that are virtual in the class experience the time performance hit related to calling a virtual function vs. a non-virtual function. The space overhead for the class is there either way. Note that if there is a vtable, there is only 1 per <em>class</em>, not one per <em>object</em>.</p>
<h2>Does the speed get affected if the virtual function is actually overridden or not, or does this have no effect so long as it is virtual?</h2>
<p>I don't believe the execution time of a virtual function that is overridden decreases compared to calling the base virtual function. However, there is an additional space overhead for the class associated with defining another vtable for the derived class vs the base class.</p>
<h2>Additional Resources:</h2>
<p><a href="http://wayback.archive.org/web/20100209040010/http://www.codersource.net/published/view/325/virtual_functions_in.aspx" rel="noreferrer">http://www.codersource.net/published/view/325/virtual_functions_in.aspx</a> (via way back machine)<br>
<a href="http://en.wikipedia.org/wiki/Virtual_table" rel="noreferrer">http://en.wikipedia.org/wiki/Virtual_table</a><br>
<a href="http://www.codesourcery.com/public/cxx-abi/abi.html#vtable" rel="noreferrer">http://www.codesourcery.com/public/cxx-abi/abi.html#vtable</a></p>
|
<p>Burly's answers are correct here except for the question:</p>
<p><em>Do abstract classes simply have a NULL for the function pointer of at least one entry?</em></p>
<p>The answer is that no virtual table is created at all for abstract classes. There is no need since no objects of these classes can be created!</p>
<p>In other words if we have:</p>
<pre><code>class B { ~B() = 0; }; // Abstract Base class
class D : public B { ~D() {} }; // Concrete Derived class
D* pD = new D();
B* pB = pD;
</code></pre>
<p>The vtbl pointer accessed through pB will be the vtbl of class D. This is exactly how polymorphism is implemented. That is, how D methods are accessed through pB. There is no need for a vtbl for class B.</p>
<h2>In response to Mike's comment below...</h2>
<p>If the B class in my description has a virtual method <em>foo()</em> that is not overridden by D and a virtual method <em>bar()</em> that is overridden, then D's vtbl will have a pointer to B's <em>foo()</em> and to its own <em>bar()</em>. There is still no vtbl created for B. </p>
| 12,451
|
<p>Is there a way to prompt the user for input during a NAnt build? I want to execute a command that takes a password, but I don't want to put the password into the build script.</p>
|
<p>I'm using a script for now, but I'd love to hear if there's a prebuilt method already available. Many thanks to sundar for the ForegroundColor trick.</p>
<p>I'm not sure if it matters whether you use Project.Log or go direct to Console.WriteLine(), any NAnt ninjas want to educate me?</p>
<p>Here's the script and a sample target that uses it:</p>
<pre><code><target name="input">
<script language="C#" prefix="password" >
<code><![CDATA[
[Function("ask")]
public string AskPassword(string prompt) {
Project.Log(Level.Info, prompt);
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = Console.BackgroundColor;
try
{
return Console.ReadLine();
}
finally
{
Console.ForegroundColor = oldColor;
}
}
]]></code>
</script>
<echo message="Password is ${password::ask('What is the password?')}"/>
</target>
</code></pre>
|
<p>Try this :</p>
<pre><code><script language="C#" prefix="test" >
<code>
<![CDATA[
[Function("get-password")]
public static string GetPassword( ) {
Console.WriteLine("Please enter the password");
ConsoleColor oldForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = Console.BackgroundColor;
string password = Console.ReadLine();
Console.ForegroundColor = oldForegroundColor;
return password;
}
]]>
</code>
</script>
<target name="test.password">
<echo message='${test::get-password()}'/>
</target>
-->
</code></pre>
| 38,011
|
<p>I have a Nant build file which executes NUnit after compiling the dll's. I am executing the NAnt build file with a task in CruiseControl. So NAnt is running the tests not CruiseControl.</p>
<p>How do I configure it so that the CruiseControl web dashboard can be used to view the NUnit output ?</p>
<hr>
<p>This fixed it:</p>
<pre><code><publishers>
<merge>
<files>
<file>build\*.test-result.xml</file>
</files>
</merge>
<xmllogger />
</publishers>
</code></pre>
|
<p>You want to use the merge capabilities of CruiseControl to grab your NUnit XML output. This is the situation my company has going, and it seems to work fairly well. Here is a config snippet (This goes in the <publishers> element in CCNet.config):</p>
<pre><code> <merge>
<files>
<file><path to XML output>\*.xml</file>
</files>
</merge>
</code></pre>
<p>Hope this works for you.</p>
|
<p>Make sure that in the the dashboard.config file you have a valid xsl file in the section we run nunit with ncover and use this xsl\NCoverExplorer.xsl
I think that the xsl file we took from the ncover install somewhere.</p>
<p>also make sure that this line is correct:
</p>
<p>Then make sure in the ccnet.config file that under the section you have the xml output from the nunit test listed.</p>
<p>Also make sure you put the xsl file in the xsl folder under webdashboard.</p>
| 19,593
|
<p>How do I do <code>mv original.filename new.original.filename</code> without retyping the original filename?</p>
<p>I would imagine being able to do something like <code>mv -p=new. original.filename</code> or perhaps <code>mv original.filename new.~</code> or whatever - but I can't see anything like this after looking at <code>man mv</code> / <code>info mv</code> pages.</p>
<p>Of course, I could write a shell script to do this, but isn't there an existing command/flag for it?</p>
|
<p>You could use the <code>rename(1)</code> command:</p>
<pre><code>rename 's/(.*)$/new.$1/' original.filename
</code></pre>
<p><strong>Edit:</strong> If <code>rename</code> isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all <code>*.jpg</code> to <code>prefix_*.jpg</code> in the current directory:</p>
<pre><code>for filename in *.jpg; do mv "$filename" "prefix_${filename}"; done;
</code></pre>
<p>or also, leveraging from <a href="https://stackoverflow.com/a/208260/2436175">Dave Webb's answer</a> and using brace expansion:</p>
<pre><code>for filename in *.jpg; do mv {,prefix_}"$filename"; done;
</code></pre>
|
<p>In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern. <br></p>
<p>As result I have a list of rename commands like this:</p>
<pre><code>f=`ls *canctn[0-9]*` ; mv $f CNLC.$f
f=`ls *acustb[0-9]*` ; mv $f CATB.$f
f=`ls *accusgtb[0-9]*` ; mv $f CATB.$f
f=`ls *acus[0-9]*` ; mv $f CAUS.$f
</code></pre>
<p>Try this also :</p>
<pre><code>f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}
</code></pre>
<p>This will produce all combinations with prefixes and suffixes:</p>
<pre><code>pref1.MyFileName.suf1
...
pref2.MyFileName.suf2
</code></pre>
<p>Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:</p>
<pre><code>#!/bin/bash
unset masks
typeset -A masks
masks[ip[0-9]]=ip
masks[iaf_usg[0-9]]=ip_usg
masks[ipusg[0-9]]=ip_usg
...
for fileMask in ${!masks[*]};
do
registryEntry="${masks[$fileMask]}";
fileName=*${fileMask}*
[ -e ${fileName} ] && mv ${fileName} ${registryEntry}.${fileName}
done
</code></pre>
| 25,536
|
<p>I have a SQL Server database and I want to know what columns and types it has. I'd prefer to do this through a query rather than using a GUI like Enterprise Manager. Is there a way to do this?</p>
|
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/ms176077.aspx" rel="noreferrer">sp_columns</a> stored procedure:</p>
<pre><code>exec sp_columns MyTable
</code></pre>
|
<pre><code>CREATE PROCEDURE [dbo].[describe]
(
@SearchStr nvarchar(max)
)
AS
BEGIN
SELECT
CONCAT([COLUMN_NAME],' ',[DATA_TYPE],' ',[CHARACTER_MAXIMUM_LENGTH],' ',
(SELECT CASE [IS_NULLABLE] WHEN 'NO' THEN 'NOT NULL' ELSE 'NULL' END),
(SELECT CASE WHEN [COLUMN_DEFAULT] IS NULL THEN '' ELSE CONCAT(' DEFAULT ',[COLUMN_DEFAULT]) END)
) AS DESCRIPTION
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE @SearchStr
END
</code></pre>
| 41,289
|
<p>I have a custom control that I need to use in another custom control. I have written all code at server side (no HTML). Can anyone tell me how to write below line of code in code behind using <code>htmlTextWriter</code> and how to register this control or how to write custom control within another where html is written from code behind?</p>
<pre><code><cc2:test id="test1" runat="server" marqueedirection="left" marqueeheight="25"
marqueewidth="725" ShowImage="False" ShowTitle="False" ShowUrlUnderLine="True"></cc2:test
</code></pre>
|
<p>First, build a simple custom web control:</p>
<pre><code>namespace My.Controls
{
public class InnerControl : Control
{
protected override void Render(HtmlTextWriter writer)
{
writer.WriteLine("<h1>Inner Control</h1>");
}
}
}
</code></pre>
<p>Then build your second web control that contains and renders the first:</p>
<pre><code>namespace My.Controls
{
public class OuterControl : Control
{
protected override void Render(HtmlTextWriter writer)
{
writer.WriteLine("<h1>Outer Control</h1>");
InnerControl innerControl = new InnerControl();
innerControl.RenderControl(writer);
}
}
}
</code></pre>
<p>Finally, register the control on your page, and display it:</p>
<pre><code><%@ Register TagPrefix="c" Namespace="My.Controls" %>
<c:OuterControl runat="server" />
</code></pre>
|
<p>Thankx it works..
i was missing only one line--</p>
<p>innerControl.RenderControl(writer);</p>
| 38,144
|
<p>While I've seen rare cases where <em>private</em> inheritance was needed, I've never encountered a case where <em>protected</em> inheritance is needed. Does someone have an example?</p>
|
<p>People here seem to mistake Protected class inheritance and Protected methods.</p>
<p>FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection level and only rely on public and private. </p>
|
<p><a href="http://www.parashift.com/c++-faq-lite/" rel="nofollow noreferrer">C++ FAQ Lite</a> mentions of a case where using private inheritance is a legitimate solution (See <a href="http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3" rel="nofollow noreferrer">[24.3.] Which should I prefer: composition or private inheritance?</a>). It's when you want to call the derived class from within a private base class through a virtual function (in this case <code>derivedFunction()</code>):</p>
<pre><code>class SomeImplementationClass
{
protected:
void service() {
derivedFunction();
}
virtual void derivedFunction() = 0;
// virtual destructor etc
};
class Derived : private SomeImplementationClass
{
void someFunction() {
service();
}
virtual void derivedFunction() {
// ...
}
// ...
};
</code></pre>
<p>Now if you want to derive from the class Derived, and you want to use <code>Base::service()</code> from within the derived class (say you want to move <code>Derived::someFunction()</code> to the derived class), the easiest way to accomplish this is to change the private inheritance of <code>Base</code> to protected inheritance.</p>
<p>Sorry, can't think of a more concrete example. Personally I like to make all inheritance public so as to avoid wasting time with "should I make inheritance relation protected or private" discussions.</p>
| 5,178
|
<p>The "ATL simple object" wizard doesn't provide a way to specify that a new class is derived from an existing coclass and its interface. In Visual Studio 2008, how do I make a new ATL COM class derived from an existing one (i.e. <code>Base</code> implements <code>IBase</code>, and I want to make a new <code>Derived</code> class derived from <code>Base</code> that implements <code>IDerived</code>, where <code>IDerived</code> is derived from <code>IBase</code>.)</p>
<p>Update: it sounds simple, but a wizard-generated ATL class has up to six base classes, a COM map and a connection point map. Which of these base classes and maps should be repeated in the derived class? If maps are repeated in the derived class should they contain the contents of the base class map or just the additional items? Does the order of base classes matter? What about <code>FinalConstruct()</code> and <code>FinalRelease()</code>? Should <code>DECLARE_PROTECT_FINAL_CONSTRUCT</code> and <code>DECLARE_REGISTRY_RESOURCEID</code> be repeated in the derived class?</p>
<p>Here's a sample base class that is empty except for all the boilerplate. Now what should the derived class look like?</p>
<pre><code>class ATL_NO_VTABLE CBase :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CBase, &CLSID_Base>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<CBase>,
public CProxy_IBaseEvents<CBase>,
public IDispatchImpl<IBase, &IID_IBase, &LIBID_ExampleLib, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
CBase()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_Base)
BEGIN_COM_MAP(CBase)
COM_INTERFACE_ENTRY(IBase)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(CBase)
CONNECTION_POINT_ENTRY(__uuidof(_IBaseEvents))
END_CONNECTION_POINT_MAP()
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
};
OBJECT_ENTRY_AUTO(__uuidof(Base), CBase)
</code></pre>
|
<p>Just a suggestion - if your COM object does not need to do anything special with COM related stuff then you can implement code such that the real logic that your base COM class does is encapsulated in another plain old C++ class say CBaseLogic. </p>
<pre><code>CBaseLogic : IBase
class ATL_NO_VTABLE CBase :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CBase, &CLSID_Base>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<CBase>,
public CProxy_IBaseEvents<CBase>,
public IDispatchImpl<IBase, &IID_IBase, &LIBID_ExampleLib
{
CBaseLogic m_LogicObj; /* Method calls are simply forwarded to this member */
};
CDerivedLogic : public CBaseLogic
class ATL_NO_VTABLE CDerived :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CDerived, &CLSID_Base>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<CDerived>,
public CProxy_IBaseEvents<CDerived>,
public IDispatchImpl<IBase, &IID_IBase, &LIBID_ExampleLib
{
CDerivedLogic m_LogicObj;
};
</code></pre>
<p>This achieves what you are trying to do with the added advantage of </p>
<ol>
<li>Keeps your real program logic separate from the infrastructure / packaging (COM)</li>
<li>Makes the real logic platform independent. </li>
<li>Future maintainer need not understand your clever COM hack</li>
<li>Keeps your program logic clean and away from the COM syntax, improving readability</li>
<li>Makes re-use of real logic easier in other forms of packaging eg as a C DLL</li>
</ol>
|
<p>Edit the code that the wizards generate. If you want an object to derive from additional interfaces, add these base classes to the resulting class declaration.</p>
| 37,889
|
<p>I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a <a href="http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html" rel="nofollow noreferrer">Too Many Clauses</a> error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.</p>
<p>Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?</p>
|
<p>I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite()</p>
<p>From: <a href="http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html" rel="nofollow noreferrer">http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html</a></p>
<pre><code>public Query rewrite(IndexReader reader)
throws IOException
Expert: called to re-write queries into primitive queries.
For example, a PrefixQuery will be rewritten into a
BooleanQuery that consists of TermQuerys.
Throws:
IOException
</code></pre>
|
<p>When running a prefix query, Lucene searches for all terms in its "dictionary" that match the query. If more than 1024 (by default) match, the TooManyClauses-Exception is thrown.</p>
<p>You can call BooleanQuery.setMaxClauseCount to increase the maximum number of clauses permitted per BooleanQuery.</p>
| 2,997
|
<p>I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:</p>
<pre><code><?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
</code></pre>
<p>I'm getting these errors:</p>
<blockquote>
<p>Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p>
<p>Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4</p>
</blockquote>
<p>PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.</p>
<p>Any ideas?</p>
|
<p>As it's Windows, there is no real 777. If you're using <a href="http://fr2.php.net/manual/en/function.chmod.php" rel="noreferrer">chmod</a>, check the Windows-related comments.</p>
<p>Check that the IIS Account can access (read, write, modify) these two folders:</p>
<pre><code>E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\
C:\WINDOWS\Temp\
</code></pre>
|
<p>Create a folder named "image" with folder permission <code>777</code></p>
<pre><code><?php
move_uploaded_file($_FILES['file']['tmp_name'],"image/".$_FILES['file']['name']);
?>
</code></pre>
| 2,569
|
<p>What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?</p>
<p>Some details:</p>
<ul>
<li><p>I am looking for solution for the entire page.</p></li>
<li><p>You need to specify only width of the element to be centered. Height of the element is not known in design time.</p></li>
<li><p>When minimizing window, scrolling should appear only when all white space is gone.
In other words, width of screen should be represented as: </p></li>
</ul>
<p>"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+<br>
"centeredElement width=widthOfCenteredElement"+<br>
"rightSpace width=(screenWidth-widthOfCenteredElement)/2" </p>
<p>And the same for the height:</p>
<p>"topSpace height=(screenHeight-heightOfCenteredElement)/2"+<br>
"centeredElement height=heightOfCenteredElement"+<br>
"bottomSpace height=(screenWidth-heightOfCenteredElement)/2"</p>
<ul>
<li>By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility.</li>
</ul>
|
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Centering</title>
<style type="text/css" media="screen">
body, html {height: 100%; padding: 0px; margin: 0px;}
#outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
#middle {vertical-align: middle}
#centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
</style>
</head>
<body>
<table id="outer" cellpadding="0" cellspacing="0">
<tr><td id="middle">
<div id="centered" style="border: 1px solid green;">
Centered content
</div>
</td></tr>
</table>
</body>
</html>
</code></pre>
<p>Solution from <a href="http://community.contractwebdevelopment.com/css-vertically-horizontally-center" rel="nofollow noreferrer">community.contractwebdevelopment.com</a> also is a good one. And if you know height of your content that needs to be centered seems to be better.</p>
|
<p>Is this what you are trying to accomplish? If not, please explain what is different than the image below?</p>
<p><img src="https://content.screencast.com/users/jessegavin/folders/Jing/media/a7adbb3d-dfc9-4f57-9cca-c47e9d399dd0/2008-09-11_1259.png" alt="alt text"></p>
| 7,187
|
<p>In my .NET/Forms app I have a DataGridView which is bound to a DataTable. The user selects a row of the DataGridView by double-clicking and does some interaction with the app. After that the content of the row is updated programmatically.</p>
<p>When the user selects a new row the changes on the previous one are automagically propagated to the DataTable by the framework. How can I trigger this update from my code so the user does not have to select a new row?</p>
|
<p>I just had the same issue, and found the answer <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.iscurrentrowdirty.aspx" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>When the user navigates away from the
row, the control commits all row
changes. The user can also press
CTRL+ENTER to commit row changes
without leaving the row. To commit row
changes programmatically, call the
form's Validate method. If your data
source is a BindingSource, you can
also call BindingSource.EndEdit.</p>
</blockquote>
<p>Calling Validate() worked for me.</p>
|
<p>I guess it depends on what triggers the update to take place, if it is in a validation routine you could simply call that after the user clicks OK on editing the data. Your question is vague it would be easier to answer with more information. What is this interaction? Is it a dialog? What actually updates the data?</p>
| 9,840
|
<p>I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up.</p>
<p>I would just <i>love</i> to just dump this kind of functions, they seem totally superfluous. <b>Is it still necessary these days to write '&auml;' instead of 'ä'?</b> At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding.</p>
<p><b>Update:</b> To be more precise: Are named entities necessary for <i>anything else than displaying HTML tags</i> (as in "&lt;" for "<")</p>
<h3>Update 2:</h3>
<p>@Konrad: Are you saying that, no, named entities are not needed?</p>
<p>@Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)</p>
|
<p>Named entities in "real" XHTML (i.e. with <code>application/xhtml+xml</code>, rather than the more frequently-used <code>text/html</code> compatibility mode) are discouraged. Aside from the five defined in XML itself (<code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>, <code>&quot;</code>, <code>&apos;</code>), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character.</p>
<p>As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities.</p>
|
<p>Safari seems to have issues with some glyphs but not others, it may not be <strong>needed</strong> but it's probably best to do so, of course, this is my opinion and not backed up by anything but my own observations.</p>
| 4,474
|
<p>I'd like to be able to read the mac address from the first active network adapter using VB.net or C# (using .NET 3.5 SP1) for a winform application</p>
|
<p>Since .Net 2.0 there's been a NetworkInterface class in the System.Net.NetworkInformation namespace that will give you this information. Try this:</p>
<pre><code> foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
Console.WriteLine(nic.GetPhysicalAddress().ToString());
break;
}
}
</code></pre>
|
<p>You need to DllImport GetAdaptersInfo -- here's some C# code</p>
<p><a href="http://www.codeguru.com/cpp/i-n/network/networkinformation/comments.php/c5451/?thread=60212" rel="nofollow noreferrer">http://www.codeguru.com/cpp/i-n/network/networkinformation/comments.php/c5451/?thread=60212</a></p>
| 26,857
|
<p>I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views?</p>
<p>On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach...</p>
<pre><code><body onload="<%=ViewData["Body_OnLoad"]%>">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</code></pre>
<p>Edit - I suppose one idea would be to use jQuery's document ready event instead...</p>
<p>Any other ideas?</p>
|
<p>I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far...</p>
<p>Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then define whatever events that are needed in my master page (onLoad, onSave, etc.). Each content page that I create will have it's own .js file associated with it and I load that script file within the content .aspx page. Any .js events that need to be implemented differently between content pages are handled within the individual content .js file. So basically my Master Page has a set of .js functions that my content page scripts will implement. Right now I just store those template .js function signatures in a file and copy and paste them into every new content.js file that I need to create. However, I'm thinking about building a code generator or tool that would spit these template signatures out for me in any new .js file I need created (if .js has some form of interface capability or inheritance features let me know).</p>
<p>So to recap:</p>
<p>MasterPage.Master Loads: jquery.js, global.js, plugins.js</p>
<p>ContentPage Loads: ContentPage.js</p>
<p>Global.js contains functions that the master page invokes that do not change between content pages along with any other global routine functions.</p>
<p>Each ContentPage.js implements it's own functions for the content page along with those functions the master page invokes that have different behavior.</p>
|
<p>You should definitely be using jQuery or another JavaScript framework anyway.</p>
<p>Have your controllers pass some kind of status indicator to your views, but not views-specific things like the names of JavaScript functions. It is up to your views to map status indicators to JavaScript function names.</p>
| 25,382
|
<p>I recently came across the data structure known as a <a href="http://en.wikipedia.org/wiki/Skip_list" rel="noreferrer"><em>skip list</em></a>. It seems to have very similar behavior to a binary search tree. </p>
<p>Why would you ever want to use a skip list over a binary search tree? </p>
|
<p>Skip lists are more amenable to concurrent access/modification. Herb Sutter wrote an <a href="http://www.ddj.com/hpc-high-performance-computing/208801371" rel="noreferrer">article</a> about data structure in concurrent environments. It has more indepth information.</p>
<h2>The most frequently used implementation of a binary search tree is a <a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="noreferrer">red-black tree</a>. The concurrent problems come in when the tree is modified it often needs to rebalance. The rebalance operation can affect large portions of the tree, which would require a mutex lock on many of the tree nodes. Inserting a node into a skip list is far more localized, only nodes directly linked to the affected node need to be locked.</h2>
<p>Update from Jon Harrops comments</p>
<p>I read Fraser and Harris's latest paper <a href="http://www.cl.cam.ac.uk/netos/papers/2007-cpwl.pdf" rel="noreferrer">Concurrent programming without locks</a>. Really good stuff if you're interested in lock-free data structures. The paper focuses on <a href="http://en.wikipedia.org/wiki/Transactional_memory" rel="noreferrer">Transactional Memory</a> and a theoretical operation multiword-compare-and-swap MCAS. Both of these are simulated in software as no hardware supports them yet. I'm fairly impressed that they were able to build MCAS in software at all.</p>
<p>I didn't find the transactional memory stuff particularly compelling as it requires a garbage collector. Also <a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">software transactional memory</a> is plagued with performance issues. However, I'd be very excited if hardware transactional memory ever becomes common. In the end it's still research and won't be of use for production code for another decade or so.</p>
<p>In section 8.2 they compare the performance of several concurrent tree implementations. I'll summarize their findings. It's worth it to download the pdf as it has some very informative graphs on pages 50, 53, and 54.</p>
<ul>
<li><strong>Locking skip lists</strong> is insanely fast. They scale incredibly well with the number of concurrent accesses. This is what makes skip lists special, other lock based data structures tend to croak under pressure.</li>
<li><strong>Lock-free skip lists</strong> are consistently faster than locking skip lists but only barely.</li>
<li><strong>transactional skip lists</strong> are consistently 2-3 times slower than the locking and non-locking versions.</li>
<li><strong>locking red-black trees</strong> croak under concurrent access. Their performance degrades linearly with each new concurrent user. Of the two known locking red-black tree implementations, one essentially has a global lock during tree rebalancing. The other uses fancy (and complicated) lock escalation but still doesn't significantly outperform the global lock version.</li>
<li><strong>lock-free red-black trees</strong> don't exist (no longer true, see Update).</li>
<li><strong>transactional red-black trees</strong> are comparable with transactional skip-lists. That was very surprising and very promising. Transactional memory, though slower if far easier to write. It can be as easy as quick search and replace on the non-concurrent version.</li>
</ul>
<hr />
<p>Update<br />
Here is paper about lock-free trees: <a href="http://www.cs.umanitoba.ca/%7Ehacamero/Research/RBTreesKim.pdf" rel="noreferrer">Lock-Free Red-Black Trees Using CAS</a>.<br />
I haven't looked into it deeply, but on the surface it seems solid.</p>
|
<p>Skip Lists do have the advantage of lock stripping. But, the runt time depends on how the level of a new node is decided. Usually this is done using Random(). On a dictionary of 56000 words, skip list took more time than a splay tree and the tree took more time than a hash table. The first two could not match hash table's runtime. Also, the array of the hash table can be lock stripped in a concurrent way too.</p>
<p>Skip List and similar ordered lists are used when locality of reference is needed. For ex: finding flights next and before a date in an application.</p>
<p>An inmemory binary search splay tree is great and more frequently used.</p>
<p><a href="http://harisankar-krishnaswamy.blogspot.in/2012/04/skip-list-runtime-on-dictionay.html" rel="nofollow noreferrer">Skip List Vs Splay Tree Vs Hash Table Runtime on dictionary find op</a></p>
| 32,009
|
<p>This question intends to provide a list of solutions to common pitfalls, "gotcha's", or design issues when developing WPF applications. This can also include proper design-patterns as long as there is an explanation as to why it works best. Responses should be voted up or down based on how common the type of issue is. Here are the rules:</p>
<ul>
<li>One response per post. This will clearly give the most common issues the highest ranking.</li>
<li>It would be best to provide the link to the a related post or solution already living somewhere in SO land.</li>
</ul>
|
<p><strong>Problem</strong> : The major issue I have seen so far is that people start coding in WPF with the winform UI model in mind.</p>
<p><strong>Solution</strong>: <strong>WPF is not WinForms/MFC/Win32</strong> So Forget all the UI side assumptions and norms you have used and learned while developing Windows based UI for last 20+ years.</p>
<p>It is very important to understand the core ideas behind this platform, This link- <a href="http://msdn.microsoft.com/en-us/magazine/cc163662.aspx" rel="noreferrer">Major UI Development Breakthroughs in the new WPF platform</a> will give an in depth view of WPF. Which lists out the following points. The highlighted ones are my favorite features of this platform.</p>
<ol start="10">
<li><strong>Advanced Graphics</strong></li>
<li>Drawing Object Model</li>
<li>Rich Application Text</li>
<li><strong>Adaptable UI Layout</strong></li>
<li>Flexible Content Model</li>
<li><strong>Lookless Controls</strong></li>
<li><strong>Data-Driven UI</strong></li>
<li>Consistent Styles</li>
<li>Triggers</li>
<li>Declarative Programming</li>
</ol>
|
<p>Ivan Towlson did a really good presentation on this topic. Most of the information is in his slides, which you can get from here:
<a href="http://hestia.typepad.com/flatlander/2008/08/codecamp-2008-.html" rel="nofollow noreferrer">http://hestia.typepad.com/flatlander/2008/08/codecamp-2008-.html</a></p>
| 41,756
|
<p>I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.</p>
<p>As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko_spellcheck option, which is supposed to fix it, but it doesn't.</p>
<p>Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?</p>
|
<p>TinyMCE only goes out of its way to disable spell-checking when you don't specify the <code>gecko_spellcheck</code> option (i verified this with their example code). Might want to double-check your <code>tinyMCE.init()</code> call - it should look something like this:</p>
<pre><code>tinyMCE.init({
mode : "textareas",
theme : "simple",
gecko_spellcheck : true
});
</code></pre>
|
<p>I know at least <a href="http://developer.yahoo.com/yui/editor/" rel="nofollow noreferrer">yahoo!'s Rich Text Editor</a> will let you use the included spell checker in FireFox.</p>
<p>I also tested FCKeditor, but that requires the users to install additional plugins on their computer.</p>
| 4,353
|
<p>Is there any centralized repository of useful Objective-C / Cocoa libraries as there is for Perl, Ruby, Python, etc.?</p>
<p>In building my first iPhone app, I'm finding myself implementing some very basic functions that would be just a quick "gem install" away in Ruby.</p>
|
<p>Unfortunately not :(
There are some very useful sites however. I find one of the best is <a href="http://www.cocoadev.com/" rel="nofollow noreferrer">cocoadev.com</a> as it contains lots of useful information about many of the more obscure classes usually including snippets of code to do some really cool things :)
Maybe we (the cocoa community) should look into building something like this!</p>
<p>Oh and I just remembered this site <a href="http://www.cocoadevcentral.com/" rel="nofollow noreferrer">cocoadevcentral.com</a> which is also very good for starting out with cocoa.</p>
|
<p>I might be confused or missing something here... But doesn't apple provide all the Foundation / Cocoa / AppKit / CoreAudio / Qtkit / etc libraries that should provide all of the very basic functions you are looking for?</p>
<p>Other than what xcode comes with or is on the apple dev site, there are no centralized repo's for Cocoa.</p>
| 11,439
|
<p>I'm looking for a library that can deal with RDF and OWL data.</p>
<p>So far I have found:</p>
<ul>
<li><a href="http://razor.occams.info/code/semweb/" rel="nofollow noreferrer">semweb</a> (no owl support for all I know)</li>
<li><a href="http://rowlex.nc3a.nato.int/HowToUse.aspx" rel="nofollow noreferrer">rowlex</a> (more of a 'browser' application)</li>
</ul>
<p>Your recommendations:</p>
<ul>
<li><a href="https://code.google.com/p/linqtordf/" rel="nofollow noreferrer">LinqToRdf</a> (very interesting, thanks mark!)</li>
</ul>
|
<p><a href="http://rowlex.nc3a.nato.int" rel="noreferrer">ROWLEX</a> is actually very cool (uses <a href="http://razor.occams.info/code/semweb/" rel="noreferrer">SemWeb</a> internally). It is not just a browser app but rather an SDK written in C#. If you use ROWLEX, you do not directly interact with the tripples of RDF anymore (though you can), but gives an object oriented look&feel. There are two main usage scenarios:</p>
<ol>
<li><strong>Business class first:</strong> You have your .NET business classes. You declaratively add attributes to your classes similarly as you do with XML serialization attributes. After this, ROWLEX can extract the ontology corresponding your business classes and/or can serialize your business objects into RDF.</li>
<li><strong>Ontology first:</strong> You have your ontology(s) and <a href="http://rowlex.nc3a.nato.int" rel="noreferrer">ROWLEX</a> generates .NET classes for you that you can use to build/browse RDF documents. The great thing is that these autogenerated classes are far better then the typical results of codegenerators. They are comfortable to use and mimic the multiple inheritence feature of OWL by providing implicit and explicit cast operators to cover the entire inheritence graph.</li>
</ol>
<p>The typical usage is the Ontology first approach. For example, let us say that your ontology describes the following multiple inheritence scenario:</p>
<blockquote>
<p>Car isSubClassOf Vehicle</p>
<p>Car isSubClassOf CompanyAsset</p>
</blockquote>
<p>Using ROWLEX, you will get .NET classes for Car, Vehicle, and CompanyAsset. The following C# code will compile without any problem:</p>
<pre><code> RdfDocument rdfDoc = new RdfDocument();
Car car = new Car("myCarUri", rdfDoc);
Vehicle vehicle = car; // implicit casting
CompanyAsset companyAsset = car; // implicit casting
vehicle.WheelCount = 4;
companyAsset.MonetaryValue = 15000;
Console.WriteLine(rdfDoc.ToN3());
</code></pre>
<p>This would print:</p>
<pre><code>myCarUri typeOf Car
myCarUri WheelCount 4
myCarUri MonetaryValue 15000
</code></pre>
<p>The "car" business object is represented inside the RdfDocument as triples. The autogenerated C#/VB classes behave as a views. You can have several C# views - each of a completely different type - on the same business object. When you interact with these views, you actually modifying the RdfDocument.</p>
|
<p>I researched this just a bit several months ago. One of the more interesting
projects I could find is:
<a href="http://www.hookedonlinq.com/linqtordf.ashx" rel="nofollow noreferrer">http://www.hookedonlinq.com/linqtordf.ashx</a></p>
| 29,813
|
<p>What would be the best way of inserting functionality into a binary application (3d party, closed source).</p>
<p>The target application is on OSX and seems to have been compiled using gcc 3+. I can see the listing of functions implemented in the binary and have debugged and isolated one particular function which I would like to remotely call.</p>
<p>Specifically, I would like to call this function - let's call it void <code>zoomByFactor(x,y)</code> - when I receive certain data from a complex HIDevice.</p>
<p>I can easily modify or inject instructions into the binary file itself (ie. the patching does not need to occur only in RAM).</p>
<p>What would you recommend as a way of "nicely" doing this?</p>
<p><strong>Edit:</strong></p>
<p>I do indeed need to entire application. So I can't ditch it and use a library. (For those who need an ethical explanation: this is a proprietary piece of CAD software whose company website hasn't been updated since 2006. I have paid for this product (quite a lot of money for what it is, really) and have project data which I can not easily migrate away from it. The product suits me just fine as it is, but I want to use a new HID which I recently got. I've examined the internals of the application, and I'm fairly confident that I can call the correct function with the relevant data and get it to work properly).</p>
<p>Here's what I've done so far, and it is quite gheto.</p>
<p>I've already modified parts of the application through this process:</p>
<pre>
xxd -g 0 binary > binary.hex
cat binary.hex | awk 'substitute work' > modified.hex
xxd -r modified.hex > newbinary
chmod 777 newbinary
</pre>
<p>I'm doing this kind of jumping through hoops because the binary is almost 100 megs large.</p>
<p>The jist of what I'm thinking is that I'd jmp somewhere in the main application loop, launch a thread, and return to the main function. </p>
<p>Now, the questions are: where can I insert the new code? do I need to modify symbol tables? alternatively, how could I make a dylib load automatically so that the only "hacking" I need to do is inserting a call to a normally loaded dylib into the main function?</p>
|
<p>For those interested in what I've ended up doing, here's a summary:</p>
<p>I've looked at several possibilities. They fall into runtime patching, and static binary file patching.</p>
<p>As far as file patching is concerned, I essentially tried two approaches:</p>
<ol>
<li><p>modifying the assembly in the code
segments (__TEXT) of the binary.</p></li>
<li><p>modifying the load commands in the
mach header.</p></li>
</ol>
<p>The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed.</p>
<p>The second method was to try and add a LC_ LOAD_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by <code>otool -l</code>. However, this didn't actually work as there was a <code>dyld: bad external relocation length</code> at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor.</p>
<p>Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to <code>fork()</code> and get the initialization process launched, but I never go that.</p>
<p>There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff.</p>
<p>Next up was mach_ inject and the mach_star project. There is also a newer project called
PlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach_inject.</p>
<p>Mach_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach_inject.c file requires there to be a MAP_ SHARED or'd with the MAP_READ or else the mmap will fail.</p>
<p>Aside from that, the whole thing actually works as advertised. I ended up using mach_ inject_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business.</p>
<p>Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.</p>
|
<p>Interesting problem. If I understand you correctly, you'd like to add the ability to remotely call functions in a running executable. </p>
<p>If you don't really need the whole application, you might be able to strip out the main function and turn it into a library file that you can link against. It'll be up to you to figure out how to make sure all the required initialization occurs. </p>
<p>Another approach could be to act like a virus. Inject a function that handles the remote calls, probably in another thread. You'll need to launch this thread by injecting some code into the main function, or wherever else is appropriate. Most likely you'll run into major issues with initialization, thread safety, and/or maintaining proper program state.</p>
<p>The best option, if its available, is to get the vendor of your application to expose a plugin API that lets you do this cleanly and reliably in a supported manner.</p>
<p>If you go with either hack-the-binary route, it'll be time consuming and brittle, but you'll learn a lot in the process.</p>
| 32,859
|
<p>I've read and followed <a href="http://developer.yahoo.com/yui/menu/" rel="nofollow noreferrer">YUI's tutorial</a> for subscribing to Menu events. I also looked through the API and bits of the code for Menu, MenuBar, and Custom Events, but the following <em>refuses</em> to work</p>
<pre><code>// oMenuBar is a MenuBar instance with submenus
var buyMenu = oMenuBar.getSubmenus()[1];
// this works
buyMenu.subscribe('show', onShow, {foo: 'bar'}, false);
// using the subscribe method doesn't work
buyMenu.subscribe('mouseOver', onMouseOver, {foo: 'bar'}, false);
// manually attaching a listener doesn't work
YAHOO.util.Event.addListener(buyMenu, 'mouseOver', onMouseOver);
// http://developer.yahoo.com/yui/docs/YAHOO.widget.Menu.html#event_keyPressEvent
// there is a keyPress Event, but no spelling of it will trigger the handler
buyMenu.subscribe('keypress', onShow, {foo: 'bar'}, false);
buyMenu.subscribe('keypressed', onShow, {foo: 'bar'}, false);
buyMenu.subscribe('keyPressed', onShow, {foo: 'bar'}, false);
buyMenu.subscribe('keyPress', onShow, {foo: 'bar'}, false);
</code></pre>
<p>Functionally, I'm trying to attach a keyPress listener for each submenu of the MenuBar. I do not want to add Bubbling library as a dependency.</p>
|
<p>Todd Kloots here, author of the YUI Menu widget. When you are subscribing to DOM-based events, the event name is all lower case. So, for the "mouseover" event, subscribe as follows:</p>
<p>buyMenu.subscribe('mouseover', onMouseOver, {foo: 'bar'}, false);</p>
<p>Regarding your keypress event handler: you are subscribing correctly. However, remember that any key-related event handlers will only fire if the Menu has focus. So, make sure your Menu has focus before testing your key-related event handlers. Also - I would recommend listening for the "keydown" event rather than "keypress" as not all keys result in the firing of the "keypress" event in IE.</p>
<p>If you have any other questions, please direct them to the ydn-javascript Y! Group as I monitor the messages on that group frequently.</p>
<p>I hope that helps.</p>
<ul>
<li>Todd</li>
</ul>
|
<p>Based on my testing, the following will work:</p>
<pre><code>oMenu.subscribe('keypress', function () { alert("I'm your friendly neighborhood keypress listener.")});
</code></pre>
<p>but that only fires when the <code>Menu</code> is receiving the <code>keypress</code> event, so it would need to already have focus.</p>
| 19,220
|
<p>In an application I'm working on, we have a bunch of custom controls with their ControlTemplates defined in Generic.xaml.</p>
<p>For instance, our custom textbox would look similar to this:</p>
<pre><code><Style TargetType="{x:Type controls:FieldTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:FieldTextBox}">
<Border BorderThickness="0" Margin="5">
<StackPanel ToolTip="{Binding Path=Field.HintText, RelativeSource={RelativeSource TemplatedParent}}">
<TextBlock Text="{Binding Path=Field.FieldLabel, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Left"
/>
<TextBox Width="{Binding Path=Field.DisplayWidth, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Left"
Text="{Binding Path=Field.Data.CurrentValue, RelativeSource={RelativeSource TemplatedParent}}"
IsEnabled="{Binding Path=Field.IsEnabled, RelativeSource={RelativeSource TemplatedParent}}"
ContextMenu="{Binding Source={StaticResource FieldContextMenu}}" >
<TextBox.Background>
<SolidColorBrush Color="{Binding Path=Field.CurrentBackgroundColor, RelativeSource={RelativeSource TemplatedParent}}"/>
</TextBox.Background>
</TextBox>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Focusable" Value="True" />
<Setter Property="IsTabStop" Value="False" />
</Style>
</code></pre>
<p>In our application, we need to be able to programatically set the focus on a particular control within the ControlTemplate.</p>
<p>Within our C# code, we can get to the particular "FieldTextBox" based on our data. Once we have the correct FieldTextBox, we need to be able to set the focus on the actual TextBox contained within the ControlTemplate.</p>
<p>The best solution I've come up with is to set a name on the primary control in each control template (in this case it's the TextBox), such as "FocusableControl."</p>
<p>My code (contained in the code-behind for the FieldTextBox) to then set focus on the control would be:</p>
<pre><code> Control control = (Control)this.Template.FindName("FocusableControl", this);
if (control != null)
{
control.Focus();
}
</code></pre>
<p>This solution works. However, does anyone else know of a solution that would be more efficient than this?</p>
|
<p>Within your control template you can add a Trigger that sets the FocusedElement of the StackPanel's <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx" rel="nofollow noreferrer">FocusManager</a> to the textbox you want focused. You set the Trigger's property to {TemplateBinding IsFocused} so it fires when the containing control is focused.</p>
|
<p>You can get rid of the hard coding of control name in the code by providing some DependancyProperty and have the same code in controlLoaded or OnApplyTemplate function based on the DependancyProperty.
This DependancyProperty's sender will the candidate for .Focus() call.</p>
| 19,176
|
<p>Do any editors honer C #line directives with regards to goto line features?</p>
<p><em>Context:</em>
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directives I'm adding.
I can drop them but then finding the input line is even a worse pain</p>
|
<p>If the editor is scriptable it should be possible to write a script to do the navigation. There might even be a Vim or Emacs script that already does something similar.</p>
<p>FWIW when I writing a lot of Bison/Flexx I wrote a <a href="http://www.zeusedit.com" rel="nofollow noreferrer">Zeus</a> Lua macro script that attempted to do something similar (i.e. move from input file to the corresponding line of the output file by search for the #line marker).</p>
<p>For any one that might be interested <a href="http://www.zeusedit.com/forum/viewtopic.php?p=4065" rel="nofollow noreferrer">here is</a> that particular macro script.</p>
|
<p><code>#line</code> directives are normally inserted by the precompiler, not into source code, so editors won't usually honor that if the file extension is <code>.c</code>.</p>
<p>However, the normal file extension for post-compiled files is <code>.i</code> or <code>.gch</code>, so you might try using that and see what happens.</p>
| 7,362
|
<p>The object I’m working on is instantiated in JavaScript, but used in VBScript. In one code path, the variable <code>M.DOM.IPt</code> is defined and has a value, in the other however it is not. I need to detect if it has been defined or not. I checked that <code>M.DOM</code> is defined and accessable in both code paths. Every test I have tried simply results in this error:</p>
<blockquote>
<p>Error: Object doesn't support this property or method</p>
</blockquote>
<p>I have tried:</p>
<ul>
<li><code>IsEmpty(M.DOM.IPt)</code></li>
<li><code>M.DOM.IPt is Nothing</code></li>
<li><code>isNull(M.DOM.IPt)</code></li>
</ul>
<p>Is there any way to detect the variable isn’t defined and avoid the error?</p>
<p>Note: I can put <code>On Error Resume Next</code> in and it will simply ignore the error, but I actually need to detect it and conditionally do something about it.</p>
|
<pre>
Function SupportsMember(object, memberName)
On Error Resume Next
Dim x
Eval("x = object."+memberName)
If Err = 438 Then
SupportsMember = False
Else
SupportsMember = True
End If
On Error Goto 0 'clears error
End Function
</pre>
|
<p>Have you tried On Error Goto label?</p>
| 31,242
|
<p>I get the following error message in SQL Server 2005:</p>
<pre><code>User '<username>' does not have permission to run DBCC DBREINDEX for object '<table>'.
</code></pre>
<p>Which minimum role do I have to give to user in order to run the command?</p>
|
<p>You will need to be a member of the <strong>db_ddladmin</strong> or the <strong>db_owner</strong> role AFAIK</p>
|
<blockquote>
<p>Caller must own the table, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.</p>
</blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/ms181671(SQL.90).aspx" rel="nofollow noreferrer">DBCC DBREINDEX (Transact-SQL) @ MSDN</a></p>
| 8,077
|
<p>By "better" I mean "more precise"...</p>
<p>With respect to a RepRap P3Steel or Wilson II, I am getting some 330 mm T8 leadscrews for the Z-axis movement.</p>
<p>There seems to be a choice between a <em>lead</em> of 1, 2 or 8 mm - the <em>pitch</em> is 1 mm in the first case and 2 mm in the last two cases<sup>1</sup>. However, there is precious little information about the advantages and disadvantages of each lead size in <a href="http://reprap.org/wiki/Threaded_rod#Leadscrew" rel="noreferrer">RepRapWiki - Threaded Rod - Leadscrew</a>.</p>
<p>It seems to me that using a leadscrew with a 1 or 2 mm lead could result in a more precise Z-axis movement, as one rotation of the stepper results in a smaller increment in height. Therefore the layer thicknesses could be smaller.</p>
<p>However, is the minimum layer thickness not, also, dictated by the thickness of the filament, horizontal speed of the print head, nozzle size, etc.? Thus, at some point there would be no need for a super fine vertical resolution from the leadscrew, as it may be constrained by other limiting factors.</p>
<p>Of course, conversely, the use of a 2 mm lead would mean that the stepper would need to "work" four times as hard, than when using 8 mm, in order to raise the print head the same distance, as well as making the movement, during a "home", take four times as long (or, if you will, four times slower). In the case of a 1 mm lead that would become eight times...</p>
<hr />
<h3>TL;DR</h3>
<p>Is it worth getting a leadscrew with a 2 mm lead, or is 8 mm sufficient?</p>
<p>By extension, would a 1 mm lead be even better, or just overkill?</p>
<hr />
<h3>Footnote</h3>
<p><sup>1</sup> Nomenclature:</p>
<ul>
<li><strong>Pitch</strong> is the distance between the adjacent threads;</li>
<li><strong>Lead</strong> is the distance that a nut will turn with one rotation, and;</li>
<li><strong>Start</strong> is how many starting (or thread entry) points at either end.</li>
</ul>
<p>So, for a leadscrew, with a <em>pitch</em> of 2 mm, if there is only one <em>start</em> to the screw then the lead is the same as the pitch. However, if there are four <em>starts</em> to the screw, then the lead will be 8 mm. If there are two <em>starts</em> to the screw, then the lead will be 4 mm. And so on.</p>
<p>For more information, see <a href="https://en.wikipedia.org/wiki/Screw_thread#Lead.2C_pitch.2C_and_starts" rel="noreferrer">Wikipedia - Lead, pitch and starts</a>.</p>
|
<p>Based on what I've learned over 8 months of printing:</p>
<p>What matters the most is getting a very accurate zero relative to the bed surface. An offset of 30 or 40 microns can strongly affect first-layer adhesion. Now, unless you put in some of the advanced auto-levelling sensors, the repeatability of the Z-axis limit switch may outweigh the precision of the lead screw itself. But if you've got a good limit sensor, then the more precision in the lead screw, the better you can set (and repeat) the position of the first layer. </p>
<p>I don't see a significant difference in strain on the drive motors if they have to run longer per mm of z-drive - just make sure the lead screws are clean :-)</p>
|
<p><strong>Longer lead</strong></p>
<p>Pros:</p>
<ol>
<li>Faster movement (mostly benefits homing)</li>
<li>More standard</li>
<li>Weak motor friendly</li>
<li>Might be slightly more stable (sideways) than shorter leads because of more starts creating more contact with nut (?)</li>
</ol>
<p>Cons</p>
<ol>
<li>Backlash</li>
<li>Less resolution (unless using 0.9 degree motor but see note<sup>1</sup>) although this is ignorable since it's still very high. It's already around 5x higher than xy axes using the longest leads<sup>2</sup>.</li>
</ol>
<p><strong>Shorter leads</strong></p>
<p>Pros</p>
<ol>
<li>More accuracy if you turn off microstepping. it can give you more resolution, but it's useless resolution unless you print with < 0.01 mm layer heights<sup>3</sup>. Turning off microstepping trades away this useless resolution for increased accuracy. But this comes at the cost of (much) louder drivers.</li>
<li>Less backlash</li>
</ol>
<p>Cons</p>
<ol>
<li>Stronger motors maybe needed</li>
<li>Slower homing</li>
</ol>
<p>The reason why companies prefer longer leads is because shorter leads simply add useless resolution and slows down movement.</p>
<p><strong>Footnotes</strong></p>
<p><sup>1</sup> It makes more sense to use higher degree motors to drive shorter leads than vice versa because of higher torque.</p>
<p><sup>2</sup> 0.0025 mm vs 0.0125 mm</p>
<p><sup>3</sup> or using a probe to autolevel, which causes the z axis to go up and down in very small increments </p>
| 594
|
<p>Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?</p>
|
<p>Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it.</p>
<pre><code><target name="build.application">
<exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true">
<arg value="${Application.Compiler.Directive}" />
<arg value="-Q" />
<arg value="/B" />
<arg value="/E${Application.Output.Folder}" />
<arg value="/U${Application.Lib.Folder};${Application.Search.Folder}" />
<arg value="${Application.Folder}\${Delphi.Project}" />
</exec>
</target>
</code></pre>
|
<p>You could also use the <code><exec></code> task.</p>
| 11,344
|
<p>Before I begin, I want to clarify that this is not a command-line tool, but an application that accepts commands through it's own command-line interface.</p>
<p><strong>Edit:</strong> I must apologize about my explanation from before, apparently I didn't do a very good job at explaining it. One more time...</p>
<p>I am building a command-line interface application that accepts commands from a user. I have a signal handler setup to catch the signals, which then sets a flag that I need to terminate the application. The problem I'm having is all of the console functions I can find are blocking, which means that I can't detect that I need to exit from my console processing loop until the user presses a key (or enter, depending on the function).</p>
<p>Is there some standard way I can do either non-block console interaction, or is there an elegant way to structure the program so that if I just terminate from the signal thread, that everything will be handled and released properly (please don't mis-understand this, I know how this could be done using locking and releasing the resources from the signaling thread, but this could get messy, so I'd rather avoid it)</p>
<p>Hopefully that explanation makes more sense...</p>
|
<p>On *nix, you can use the <code>signal</code> function to register a signal handler:</p>
<pre><code>
#include <signal.h>
void signal_handler(int sig)
{
// Handle the signal
}
int main(void)
{
// Register the signal handler for the SIGINT signal (Ctrl+C)
signal(SIGINT, signal_handler);
...
}
</code></pre>
<p>Now, whenever someone hits <kbd>Ctrl</kbd>+<kbd>C</kbd>, your signal handler will be called.</p>
|
<p>A better *nix solution that is thread safe is to use <a href="http://linux.die.net/man/3/pthread_sigmask" rel="nofollow">pthread_sigmask()</a> instead of signal().<br>
For example, this is how you signore SIGINT, SIGTERM, and SIGPIPE in the current thread and future spawned threads:</p>
<pre><code>sigset_t waitset;
sigemptyset(&waitset);
sigaddset(&waitset, SIGINT);
sigaddset(&waitset, SIGTERM);
sigaddset(&waitset, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &waitset, NULL);
</code></pre>
| 21,897
|
<p>Should the model just be data structures? Where do the services (data access, business logic) sit in MVC?</p>
<p>Lets assume I have a view that shows a list of customer orders. I have a controller class that handles the clicks on the view controls (buttons, etc).</p>
<p>Should the controller kick off the data access code? Think button click, reload order query. Or should this go through the model layer at all?</p>
<p>Any example code would be great!</p>
|
<p>Generally I implement MVC as follows:</p>
<p>View - Receives data from the controller and generates output. Generally only display logic should appear here. For example, if you wanted to take an existing site and produce a mobile/iPhone version of it, you should be able to do that just by replacing the views (assuming you wanted the same functionality).</p>
<p>Model - Wrap access to data in models. In my apps, all SQL lives in the Model layer, no direct data access is allowed in the Views or Controllers. As Elie points out in another answer, the idea here is to (at least partially) insulate your Controllers/Views from changes in database structure. Models are also a good place to implement logic such as updating a "last modified" date whenever a field changes. If a major data source for your application is an external web service, consider whether wrapping that in a model class.</p>
<p>Controllers - Used to glue Models and Views together. Implement application logic here, validate forms, transfer data from models to views, etc.</p>
<p>For example, in my apps, when a page is requested, the controller will fetch whatever data is required from the models, and pass it to a view to generate the page the user sees. If that page was a form, the form may then be submitted, the controller handles validation, creates the necessary model and uses it to save the data.</p>
<p>If you follow this method, Models end up being quite generic and reusable. Your controllers are of a manageable size and complexity because data access and display has been removed to Models and Views respectively, and your views should be simple enough that a designer (with a little training) could comprehend them.</p>
|
<p>The View would relay what should happen on a click in the UI to the Control layer, which would contain ALL business logic, and would in turn call the Model layer which would only make database calls. Only the model layer should be making database calls, or you will defeat the purpose of the MVC design pattern. </p>
<p>Think about it this way. Let's say you change your database. You would want to limit the amount of code change required, and keep all those changes together without affecting other pieces of your application. So by keeping all data access in the Model layer, even the simple calls, you limit any changes required to the Model layer. If you were to bypass the Model layer for any reason, you would now have to extend any changes needed to any code that knows about the database, making such maintenance more complex than it should be.</p>
| 42,735
|
<p>Here's my situation: I'm trying to understand how msbuild works by looking at the build files located in the .NET framework install path:</p>
<pre><code>C:\Windows\Microsoft.NET\Framework\v3.5>dir /s/b microsoft*
Microsoft.Build.Tasks.v3.5.xml
Microsoft.Build.xsd
Microsoft.Common.targets
Microsoft.Common.Tasks
Microsoft.CSharp.targets
Microsoft.Data.Entity.targets
Microsoft.VisualBasic.targets
Microsoft.WinFx.targets
MSBuild\Microsoft.Build.Commontypes.xsd
MSBuild\Microsoft.Build.Core.xsd
</code></pre>
<p>I'm assuming that msbuild starts with Microsoft.Common.Targets, and then at some point in the future msbuild 'looks' at my vb project file extension (.vbproj) and loads 'Microsoft.VisualBasic.targets'. </p>
<p>two questions:</p>
<p>1) Is my interpetation correct?</p>
<p>2) can you explain to me, where is the code that determines that this is a .vbproj file, and loads 'Microsoft.VisualBasic.targets' accordingly? Is the code locked away in an assembly somewhere, or is it visible in the build files listed above?</p>
|
<p>It "starts" with your .vbproj file. Take a look at that file, it will <Import> the Microsoft.VisualBasic.targets, which in turn will <Import> Microsoft.Common.targets.</p>
|
<p>In 4.0, which is currently available in Beta, there is a /preprocess switch which will make this all clear.</p>
| 37,295
|
<p>I have been hearing a lot of good things about DVCS systems, in particular about bazaar. Apart from the concept of distributed repository, I see two main advantages being touted: the merge is better automated, and the rename is handled right.</p>
<p>Could someone please point me at some text explaining how exactly the improvements work? How does bazaar know that I renamed a file? What if I rename two files as part of the same commit? What happens when I refactor by putting half of the file's contents into a new file, re-indenting everything and losing some whitespace in nearly every line?</p>
<p>In other words, I'd like to hear from people using bazaar (or another DVCS) in real life, or from people who know how it (they) works. Is the merge really that much better? And how is it achieved?</p>
<hr>
<p>Related question, with a useful answer:</p>
<p><a href="https://stackoverflow.com/questions/43995/why-is-branching-and-merging-easier-in-mercurial-than-in-subversion">Why is branching and merging easier in Mercurial than in Subversion?</a></p>
|
<p>Merge is not intrinsically better in DVCS, it is just that they would be practically very difficult to use if the branch/merge did not work correctly (svn arguably does not implement branching/merging correctly), because instead of making a checkout, you are making a new branch everytime you start working on a project from an existing code. I think some proprietary, centralized SCS do handle merge/branch correctly.</p>
<p>The way it works for all of them is to record every commit in a Directly Acyclic Graph (DAG), and from this, you have different merge strategies available. Here you can find more information:</p>
<p><a href="http://revctrl.org/CategoryMergeAlgorithm" rel="nofollow noreferrer">http://revctrl.org/CategoryMergeAlgorithm</a></p>
<p>At least hg, bzr and git can use external merge utilities.</p>
|
<p>I'm not familiar with bazaar, but git doesn't track file renames. To git, this looks like a delete and an add. However, git is smart enough to see that the contents of the file already exist in its repository and will track their position in the system. If you split files up or merge them it's smart enough to keep track of segments of code (blobs) and store that information too.</p>
| 6,834
|
<p>I have an ASP.NET GridView which has columns that look like this:</p>
<pre><code>| Foo | Bar | Total1 | Total2 | Total3 |
</code></pre>
<p>Is it possible to create a header on two rows that looks like this?</p>
<pre><code>| | Totals |
| Foo | Bar | 1 | 2 | 3 |
</code></pre>
<p>The data in each row will remain unchanged as this is just to pretty up the header and decrease the horizontal space that the grid takes up. </p>
<p>The entire GridView is sortable in case that matters. I don't intend for the added "Totals" spanning column to have any sort functionality.</p>
<p><strong>Edit:</strong></p>
<p>Based on one of the articles given below, I created a class which inherits from GridView and adds the second header row in.</p>
<pre><code>namespace CustomControls
{
public class TwoHeadedGridView : GridView
{
protected Table InnerTable
{
get
{
if (this.HasControls())
{
return (Table)this.Controls[0];
}
return null;
}
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
this.CreateSecondHeader();
}
private void CreateSecondHeader()
{
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = this.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
this.InnerTable.Rows.AddAt(0, row);
}
}
}
</code></pre>
<p>In case you are new to ASP.NET like I am, I should also point out that you need to:</p>
<p>1) Register your class by adding a line like this to your web form:</p>
<pre><code><%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
</code></pre>
<p>2) Change asp:GridView in your previous markup to foo:TwoHeadedGridView. Don't forget the closing tag.</p>
<p><strong>Another edit:</strong></p>
<p>You can also do this without creating a custom class.</p>
<p>Simply add an event handler for the DataBound event of your grid like this:</p>
<pre><code>protected void gvOrganisms_DataBound(object sender, EventArgs e)
{
GridView grid = sender as GridView;
if (grid != null)
{
GridViewRow row = new GridViewRow(0, -1,
DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = grid.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
Table t = grid.Controls[0] as Table;
if (t != null)
{
t.Rows.AddAt(0, row);
}
}
}
</code></pre>
<p>The advantage of the custom control is that you can see the extra header row on the design view of your web form. The event handler method is a bit simpler, though.</p>
|
<p><a href="https://web.archive.org/web/20100201202857/http://blogs.msdn.com/mattdotson/articles/541795.aspx" rel="nofollow noreferrer">This article</a> should point you in the right direction. You can programmatically create the row and add it to the collection at position 0.</p>
|
<p>Please refer to <a href="https://stackoverflow.com/a/9333714/1060656">https://stackoverflow.com/a/9333714/1060656</a></p>
<p>i created this solution example </p>
<p>To run in your local system will will need to create 2 files ( one for the control and one aspx) you can either do it one project or 2 projects.</p>
<ol>
<li>GridViewPlus ==> Control class</li>
<li>GridViewPlusCustomHeaderRows ==> a collection to hold custom header class</li>
<li>CustomHeaderEventArgs ==> Event Args when custom header row is created </li>
<li><p>aspx file ==> Test program</p>
<pre><code>public class GridViewPlus : GridView
{
public event EventHandler<CustomHeaderEventArgs> CustomHeaderTableCellCreated;
private GridViewPlusCustomHeaderRows _rows;
public GridViewPlus() : base ()
{
_rows = new GridViewPlusCustomHeaderRows();
}
/// <summary>
/// Allow Custom Headers
/// </summary>
public bool ShowCustomHeader { get; set; }
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
[MergableProperty(false)]
public GridViewPlusCustomHeaderRows CustomHeaderRows
{
get {return _rows; }
}
protected virtual void OnCustomHeaderTableCellCreated(CustomHeaderEventArgs e)
{
EventHandler<CustomHeaderEventArgs> handler = CustomHeaderTableCellCreated;
// Event will be null if there are no subscribers
if (handler != null)
{
// Use the () operator to raise the event.
handler(this, e);
}
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (ShowCustomHeader && e.Row.RowType == DataControlRowType.Header) return;
base.OnRowCreated(e);
}
protected override void PrepareControlHierarchy()
{
//Do not show the Gridview header if show custom header is ON
if (ShowCustomHeader) this.ShowHeader = false;
base.PrepareControlHierarchy();
//Safety Check
if (this.Controls.Count == 0)
return;
bool controlStyleCreated = this.ControlStyleCreated;
Table table = (Table)this.Controls[0];
int j = 0;
if (CustomHeaderRows ==null )return ;
foreach (TableRow tr in CustomHeaderRows)
{
OnCustomHeaderTableCellCreated(new CustomHeaderEventArgs(tr,j));
table.Rows.AddAt(j, tr);
tr.ApplyStyle(this.HeaderStyle);
j++;
}
}
}
public class GridViewPlusCustomHeaderRows : System.Collections.CollectionBase
{
public GridViewPlusCustomHeaderRows()
{
}
public void Add(TableRow aGridViewCustomRow)
{
List.Add(aGridViewCustomRow);
}
public void Remove(int index)
{
// Check to see if there is a widget at the supplied index.
if (index > Count - 1 || index < 0)
// If no widget exists, a messagebox is shown and the operation
// is cancelled.
{
throw (new Exception("Index not valid"));
}
else
{
List.RemoveAt(index);
}
}
public TableRow Item(int Index)
{
// The appropriate item is retrieved from the List object and
// explicitly cast to the Widget type, then returned to the
// caller.
return (TableRow)List[Index];
}
}
public class CustomHeaderEventArgs : EventArgs
{
public CustomHeaderEventArgs(TableRow tr ,int RowNumber )
{
tRow = tr;
_rownumber = RowNumber;
}
private TableRow tRow;
private int _rownumber = 0;
public int RowNumber { get { return _rownumber; } }
public TableRow HeaderRow
{
get { return tRow; }
set { tRow = value; }
}
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Example1();
GridViewExtension1.CustomHeaderTableCellCreated += new EventHandler<CustomHeaderEventArgs>(GridViewExtension1_CustomHeaderTableCellCreated);
}
void GridViewExtension1_CustomHeaderTableCellCreated(object sender, CustomHeaderEventArgs e)
{
TableRow tc = (TableRow)e.HeaderRow;
tc.BackColor = System.Drawing.Color.AliceBlue;
}
private void Example1()
{
System.Data.DataTable dtSample = new DataTable();
DataColumn dc1 = new DataColumn("Column1",typeof(string));
DataColumn dc2 = new DataColumn("Column2",typeof(string));
DataColumn dc3 = new DataColumn("Column3",typeof(string));
DataColumn dc4 = new DataColumn("Column4",typeof(string));
// DataColumn dc5 = new DataColumn("Column5",typeof(string));
dtSample.Columns.Add(dc1);
dtSample.Columns.Add(dc2);
dtSample.Columns.Add(dc3);
dtSample.Columns.Add(dc4);
// dtSample.Columns.Add(dc5);
dtSample.AcceptChanges();
for (int i = 0; i < 25; i++)
{
DataRow dr = dtSample.NewRow();
for (int j = 0; j < dtSample.Columns.Count; j++)
{
dr[j] = j;
}
dtSample.Rows.Add(dr);
}
dtSample.AcceptChanges();
//GridViewExtension1.ShowHeader = false;
GridViewExtension1.ShowCustomHeader = true;
/*
*=======================================================================
* |Row 1 Cell 1 | Row 1 Col 2 (Span=2) | Row 1 Col 3 |
* | | | |
*=======================================================================
* |Row 2 Cell 1 | | | |
* | | Row 2 Col 2 | Row 2 Col 3 |Row 2 Col 4 |
*=======================================================================
*
*
*
*
* */
// SO we have to make 2 header row as shown above
TableRow TR1 = new TableRow();
TableCell tcR1C1 = new TableCell();
tcR1C1.Text = "Row 1 Cell 1";
tcR1C1.ColumnSpan = 1;
TR1.Cells.Add(tcR1C1);
TableCell tcR1C2 = new TableCell();
tcR1C2.Text = "Row 1 Cell 2";
tcR1C2.ColumnSpan = 2;
TR1.Cells.Add(tcR1C2);
TableCell tcR1C3 = new TableCell();
tcR1C3.Text = "Row 1 Cell 3";
tcR1C3.ColumnSpan = 1;
TR1.Cells.Add(tcR1C3);
GridViewExtension1.CustomHeaderRows.Add(TR1);
TableRow TR2 = new TableRow();
TableCell tcR2C1 = new TableCell();
tcR2C1.Text = "Row 2 Cell 1";
tcR2C1.ColumnSpan = 1;
TR2.Cells.Add(tcR2C1);
TableCell tcR2C2 = new TableCell();
tcR2C2.Text = "Row 2 Cell 2";
tcR2C2.ColumnSpan = 1;
TR2.Cells.Add(tcR2C2);
TableCell tcR2C3 = new TableCell();
tcR2C3.Text = "Row 2 Cell 3";
tcR2C3.ColumnSpan = 1;
TR2.Cells.Add(tcR2C3);
TableCell tcR2C4 = new TableCell();
tcR2C4.Text = "Row 2 Cell 4";
tcR2C4.ColumnSpan = 1;
TR2.Cells.Add(tcR2C4);
GridViewExtension1.CustomHeaderRows.Add(TR2);
GridViewExtension1.DataSource = dtSample;
GridViewExtension1.DataBind();
}
}
</code></pre></li>
</ol>
| 40,623
|
<p>Given two image buffers (assume it's an array of ints of size width * height, with each element a color value), how can I map an area defined by a quadrilateral from one image buffer into the other (always square) image buffer? I'm led to understand this is called "projective transformation".</p>
<p>I'm also looking for a general (not language- or library-specific) way of doing this, such that it could be reasonably applied in any language without relying on "magic function X that does all the work for me".</p>
<p>An example: I've written a short program in Java using the Processing library (processing.org) that captures video from a camera. During an initial "calibrating" step, the captured video is output directly into a window. The user then clicks on four points to define an area of the video that will be transformed, then mapped into the square window during subsequent operation of the program. If the user were to click on the four points defining the corners of a door visible at an angle in the camera's output, then this transformation would cause the subsequent video to map the transformed image of the door to the entire area of the window, albeit somewhat distorted.</p>
|
<p><strong>EDIT</strong></p>
<p>The assumption below of the invariance of angle ratios is incorrect. Projective transformations instead preserve cross-ratios and incidence. A solution then is:</p>
<ol>
<li>Find the point C' at the intersection of the lines defined by the segments AD and CP.</li>
<li>Find the point B' at the intersection of the lines defined by the segments AD and BP.</li>
<li>Determine the cross-ratio of B'DAC', i.e. r = (BA' * DC') / (DA * B'C').</li>
<li>Construct the projected line F'HEG'. The cross-ratio of these points is equal to r, i.e. r = (F'E * HG') / (HE * F'G').</li>
<li>F'F and G'G will intersect at the projected point Q so equating the cross-ratios and knowing the length of the side of the square you can determine the position of Q with some arithmetic gymnastics.</li>
</ol>
<hr>
<p>Hmmmm....I'll take a stab at this one. This solution relies on the assumption that ratios of angles are preserved in the transformation. See the image for guidance (sorry for the poor image quality...it's REALLY late). The algorithm only provides the mapping of a point in the quadrilateral to a point in the square. You would still need to implement dealing with multiple quad points being mapped to the same square point.</p>
<p>Let ABCD be a quadrilateral where A is the top-left vertex, B is the top-right vertex, C is the bottom-right vertex and D is the bottom-left vertex. The pair (xA, yA) represent the x and y coordinates of the vertex A. We are mapping points in this quadrilateral to the square EFGH whose side has length equal to m.</p>
<p><img src="https://i.stack.imgur.com/tPION.gif" alt="alt text"></p>
<p>Compute the lengths AD, CD, AC, BD and BC:</p>
<pre><code>AD = sqrt((xA-xD)^2 + (yA-yD)^2)
CD = sqrt((xC-xD)^2 + (yC-yD)^2)
AC = sqrt((xA-xC)^2 + (yA-yC)^2)
BD = sqrt((xB-xD)^2 + (yB-yD)^2)
BC = sqrt((xB-xC)^2 + (yB-yC)^2)
</code></pre>
<p>Let thetaD be the angle at the vertex D and thetaC be the angle at the vertex C. Compute these angles using the cosine law:</p>
<pre><code>thetaD = arccos((AD^2 + CD^2 - AC^2) / (2*AD*CD))
thetaC = arccos((BC^2 + CD^2 - BD^2) / (2*BC*CD))
</code></pre>
<p>We map each point P in the quadrilateral to a point Q in the square. For each point P in the quadrilateral, do the following:</p>
<ul>
<li><p>Find the distance DP: </p>
<pre><code>DP = sqrt((xP-xD)^2 + (yP-yD)^2)
</code></pre></li>
<li><p>Find the distance CP: </p>
<pre><code>CP = sqrt((xP-xC)^2 + (yP-yC)^2)
</code></pre></li>
<li><p>Find the angle thetaP1 between CD and DP: </p>
<pre><code>thetaP1 = arccos((DP^2 + CD^2 - CP^2) / (2*DP*CD))
</code></pre></li>
<li><p>Find the angle thetaP2 between CD and CP: </p>
<pre><code>thetaP2 = arccos((CP^2 + CD^2 - DP^2) / (2*CP*CD))
</code></pre></li>
<li><p>The ratio of thetaP1 to thetaD should be the ratio of thetaQ1 to 90. Therefore, calculate thetaQ1: </p>
<pre><code>thetaQ1 = thetaP1 * 90 / thetaD
</code></pre></li>
<li><p>Similarly, calculate thetaQ2: </p>
<pre><code>thetaQ2 = thetaP2 * 90 / thetaC
</code></pre></li>
<li><p>Find the distance HQ: </p>
<pre><code>HQ = m * sin(thetaQ2) / sin(180-thetaQ1-thetaQ2)
</code></pre></li>
<li><p>Finally, the x and y position of Q relative to the bottom-left corner of EFGH is: </p>
<pre><code>x = HQ * cos(thetaQ1)
y = HQ * sin(thetaQ1)
</code></pre></li>
</ul>
<p>You would have to keep track of how many colour values get mapped to each point in the square so that you can calculate an average colour for each of those points.</p>
|
<p>Here's how would do it in principle:</p>
<ul>
<li>map the origin of A to the origin of B via a traslation vector <code>t</code>.</li>
<li>take unit vectors of A (1,0) and (0,1) and calculate how they would be mapped onto the unit vectors of B.</li>
<li>this gives you a transformation matrix <strong>M</strong> so that every vector <code>a</code> in A maps to <strong>M</strong> <code>a</code> + <code>t</code></li>
<li>invert the matrix and negate the traslation vector so for every vector <code>b</code> in B you have the inverse mapping <code>b</code> -> <strong>M<sup>-1</sup></strong> (<code>b</code> - <code>t</code>)</li>
<li>once you have this transformation, for each point in the target area in B, find the corresponding in A and copy.</li>
</ul>
<p>The advantage of this mapping is that you only calculate the points you need, i.e. you loop on the <em>target</em> points, not the <em>source</em> points. It was a widely used technique in the "demo coding" scene a few years back.</p>
| 20,506
|
<p>I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days.</p>
|
<pre><code>// use this to avoid redirects when a user clicks "back" in their browser
window.location.replace('http://somewhereelse.com');
// use this to redirect, a back button call will trigger the redirection again
window.location.href = "http://somewhereelse.com";
// given for completeness, essentially an alias to window.location.href
window.location = "http://somewhereelse.com";
</code></pre>
<p><strong>edit</strong>: looks like the user who posted the better answer has left SO, i've consolidated his answers here.</p>
|
<p>One important thing to remember when redirecting a page using JavaScript is, always provide a non-JavaScript redirect as well! A link would do, or better a <code><META></code> tag, for example: <code><meta http-equiv="refresh" content="2;url=http://example.com"></code></p>
| 24,434
|
<p>My development shop has put together a fairly useful Python-based test suite, and we'd like to test some Linux-based C++ code with it. We've gotten the test project they ship with Boost to compile (type 'bjam' in the directory and it works), but we're having issues with our actual project.</p>
<p>Building the boost libraries and bjam from source (v1.35.0), when I run bjam I get a .so in the bin/gcc-4.1.2/debug directory. I run python and "import " and I get:
ImportError: <code>libboost_python-gcc41-d-1_35.so.1.35.0</code>: cannot open shared object file: No such file or directory</p>
<p>Looking in the library directory, I have the following:
<code>libboost_python-gcc41-mt-1_35.so</code> <code>libboost_python-gcc41-mt-1_35.so.1.35.0</code> <code>libboost_python-gcc41-mt.so</code></p>
<p>Obviously I need the -d instead of the -mt libraries, or to point at the -mt libraries instead of -d, but I can't figure out how to make my Jamroot file do that.</p>
<p>When I install Debian Etch's versions of the libraries, I get "No Jamfile in /usr/include" - and there's a debian bug that says they left out the system-level jamfile.</p>
<p>I'm more hopeful about getting it working from source, so if anyone has any suggestions to resolve the library issues, I'd like to hear them.</p>
<p>Response to answer 1: Thanks for the tip. So, do you know how I'd go about getting it to use the MT libraries instead? It appears to be more of a problem with bjam or the Jamfile I am using thinking I am in debug mode, even though I can't find any flags for that. While I know how to include specific libraries in a call to GCC, I don't see a way to configure that from the Boost end.</p>
|
<p>"Google Maps Hacks" has a hack, <a href="http://safari.oreilly.com/0596101619/googlemapshks-CHP-4-SECT-3" rel="nofollow noreferrer">"Hack 30. Stay Out of Traffic Jams"</a>, on that.</p>
<p>You can also find out how to get U.S. traffic info from John Resig's <a href="http://ejohn.org/blog/traffic-conditions-data/" rel="nofollow noreferrer">"Traffic Conditions Data"</a> article.</p>
|
<p>Google is mum on what source they use for their traffic data. You might contact them directly to see if they want to implement something for you, but my guess is that they'd simply refer you to their provider if they really wanted your data.</p>
<p>Keep in mind that traffic data is available for more than just the metropolitan areas, but Google isn't using it for a variety of reasons - one of the big reasons is that the entire tile set for the traffic overlay in areas with traffic tiles has to be regenerated every 15 minutes or so. It just doesn't scale.</p>
<p>So even if you managed to get your data in their flow, it likely won't be rendered.</p>
<p>-Adam</p>
| 9,259
|
<p>I had developed an application in visual Studio 2005. whenever i run that application active directory locks domain my account. I really cant understand what am i doing wrong.</p>
|
<p>I can't tell you exactly what's causing it, but here are some tips for troubleshooting. Install the <strong><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=7af2e69c-91f3-4e63-8629-b999adde0b9e&DisplayLang=en" rel="nofollow noreferrer">Account Lockout and Management Tools</a></strong> from Microsoft so you can get a bit more detail about the why's and whens on a lockout.</p>
<p>Here's an excellent article of debugging that walks you though everything and is more resourceful that me repeating it here : <strong><a href="http://www.windowsecurity.com/articles/Implementing-Troubleshooting-Account-Lockout.html" rel="nofollow noreferrer">Implementing and Troubleshooting Account Lockout</a></strong></p>
<p>Using these tools you can see if it's stale credentials used in your app, bad password overloads, or some security elsewhere that's being tripped by your application that your AD policies don't like.</p>
|
<p>Are you using authentication to a database, SSAS cube or other item that uses user/password authentication against an AD account?</p>
<p>If this is the case and your application tries three logins with the wrong password, AD may lock out your account (depending on its settings). Analysis Services is quite bad for this.</p>
<p>Nigel.</p>
| 15,136
|
<p>Say, I have a script that gets called with this line:</p>
<pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile
</code></pre>
<p>or this one:</p>
<pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile
</code></pre>
<p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
|
<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-space-separated.sh <<'EOF'
#!/bin/bash
POSITIONAL_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-e|--extension)
EXTENSION="$2"
shift # past argument
shift # past value
;;
-s|--searchpath)
SEARCHPATH="$2"
shift # past argument
shift # past value
;;
--default)
DEFAULT=YES
shift # past argument
;;
-*|--*)
echo "Unknown option $1"
exit 1
;;
*)
POSITIONAL_ARGS+=("$1") # save positional arg
shift # past argument
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 "$1"
fi
EOF
chmod +x /tmp/demo-space-separated.sh
/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-space-separated.sh -e conf -s /etc /etc/hosts
</code></pre>
<hr />
<h4>Bash Equals-Separated (e.g., <code>--option=argument</code>)</h4>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-equals-separated.sh <<'EOF'
#!/bin/bash
for i in "$@"; do
case $i in
-e=*|--extension=*)
EXTENSION="${i#*=}"
shift # past argument=value
;;
-s=*|--searchpath=*)
SEARCHPATH="${i#*=}"
shift # past argument=value
;;
--default)
DEFAULT=YES
shift # past argument with no value
;;
-*|--*)
echo "Unknown option $i"
exit 1
;;
*)
;;
esac
done
echo "FILE EXTENSION = ${EXTENSION}"
echo "SEARCH PATH = ${SEARCHPATH}"
echo "DEFAULT = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
echo "Last line of file specified as non-opt/last argument:"
tail -1 $1
fi
EOF
chmod +x /tmp/demo-equals-separated.sh
/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>FILE EXTENSION = conf
SEARCH PATH = /etc
DEFAULT =
Number files in SEARCH PATH with EXTENSION: 14
Last line of file specified as non-opt/last argument:
#93.184.216.34 example.com
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-equals-separated.sh -e=conf -s=/etc /etc/hosts
</code></pre>
<hr />
<p>To better understand <code>${i#*=}</code> search for "Substring Removal" in <a href="http://tldp.org/LDP/abs/html/string-manipulation.html" rel="noreferrer">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' <<< "$i"`</code> which calls a needless subprocess or <code>`echo "$i" | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p>
<hr />
<h4>Using bash with getopt[s]</h4>
<p>getopt(1) limitations (older, relatively-recent <code>getopt</code> versions):</p>
<ul>
<li>can't handle arguments that are empty strings</li>
<li>can't handle arguments with embedded whitespace</li>
</ul>
<p>More recent <code>getopt</code> versions don't have these limitations. For more information, see these <a href="https://mywiki.wooledge.org/BashFAQ/035#getopts" rel="noreferrer">docs</a>.</p>
<hr />
<h4>POSIX getopts</h4>
<p>Additionally, the POSIX shell and others offer <code>getopts</code> which doen't have these limitations. I've included a simplistic <code>getopts</code> example.</p>
<pre class="lang-sh prettyprint-override"><code>cat >/tmp/demo-getopts.sh <<'EOF'
#!/bin/sh
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize our own variables:
output_file=""
verbose=0
while getopts "h?vf:" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v) verbose=1
;;
f) output_file=$OPTARG
;;
esac
done
shift $((OPTIND-1))
[ "${1:-}" = "--" ] && shift
echo "verbose=$verbose, output_file='$output_file', Leftovers: $@"
EOF
chmod +x /tmp/demo-getopts.sh
/tmp/demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<h5>Output from copy-pasting the block above</h5>
<pre class="lang-sh prettyprint-override"><code>verbose=1, output_file='/etc/hosts', Leftovers: foo bar
</code></pre>
<h5>Usage</h5>
<pre class="lang-bash prettyprint-override"><code>demo-getopts.sh -vf /etc/hosts foo bar
</code></pre>
<p>The advantages of <code>getopts</code> are:</p>
<ol>
<li>It's more portable, and will work in other shells like <code>dash</code>.</li>
<li>It can handle multiple single options like <code>-vf filename</code> in the typical Unix way, automatically.</li>
</ol>
<p>The disadvantage of <code>getopts</code> is that it can only handle short options (<code>-h</code>, not <code>--help</code>) without additional code.</p>
<p>There is a <a href="http://wiki.bash-hackers.org/howto/getopts_tutorial" rel="noreferrer">getopts tutorial</a> which explains what all of the syntax and variables mean. In bash, there is also <code>help getopts</code>, which might be informative.</p>
|
<p>This also might be useful to know: you can set a value and if someone provides input, override the default with that value.</p>
<p><code>myscript.sh -f ./serverlist.txt</code> or just <code>./myscript.sh</code> (and it takes defaults)</p>
<pre><code> #!/bin/bash
# --- set the value, if there is inputs, override the defaults.
HOME_FOLDER="${HOME}/owned_id_checker"
SERVER_FILE_LIST="${HOME_FOLDER}/server_list.txt"
while [[ $# > 1 ]]
do
key="$1"
shift
case $key in
-i|--inputlist)
SERVER_FILE_LIST="$1"
shift
;;
esac
done
echo "SERVER LIST = ${SERVER_FILE_LIST}"
</code></pre>
| 23,365
|
<p>Does anybody have any pointers to what SWD files are in Flash 9, why Flash Player wants to download them sometimes, how to make ones, how to make use of them? Didn't manage to dig anything useful myself yet.</p>
<p><em>Update</em></p>
<p>I know roughly what are swd files used in Flash8, and <a href="http://livedocs.adobe.com/flex/15/flex_docs_en/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flex_Documentation&file=00000838.htm" rel="nofollow noreferrer">there is even a way to make them</a>, but Flash 9 doesn't seem to need it at first glance, but still attempts to use sometimes.</p>
|
<p>SWD files are needed to debug content with Adobe's debugging tools. You can see this in action by publishing from Flash authoring with shift-control-enter. </p>
<p>The SWD itself is only needed for the debugging tool to see inside the SWF. You can throw it away once you're done debugging, and you never need to upload it to the server unless you're planning to do remote debugging.</p>
<p>Docs:<br>
<a href="http://livedocs.adobe.com/flash/9.0/UsingFlash/help.html?content=WS3e7c64e37a1d85e1e229110db38dec34-7fc0.html" rel="nofollow noreferrer">Debugging local files</a><br>
<a href="http://livedocs.adobe.com/flash/9.0/UsingFlash/help.html?content=WSE9184681-3417-4849-B487-8D6C2F8CC688.html" rel="nofollow noreferrer">Debugging remote files</a></p>
|
<blockquote>
<p>SWD files are similar to SWF files, except that they contain debugging-specific information that the debugger and Flash Debug Player watch for.</p>
</blockquote>
<p>From: About SWD files</p>
<p>The citation above is from the Flex documentation but applies to 'normal' Flash too.</p>
| 15,387
|
<p>Is there a way to compile multiple java source directories in a single maven project? </p>
|
<p>You can add a new source directory with build-helper:</p>
<pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
|
<p>This can be done in two steps:</p>
<ul>
<li>For each source directory you should create own module.</li>
<li>In all modules you should specify the same build directory: <code>${build.directory}</code></li>
</ul>
<p>If you work with started Jetty (<code>jetty:run</code>), then recompilation of any class in any module (with Maven, IDEA or Eclipse) will lead to Jetty's restart. The same behavior you'll get for modified resources.</p>
| 33,989
|
<p>Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met. </p>
<p>Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?</p>
<p>Main thing I am looking for is how to catch a program starting up, rest should be easy.</p>
|
<p>Well, you can definitely determine which programs are running by looking for the process names you want (GetProcessesByName()) and killing them.</p>
<pre><code>Process[] processes = Process.GetProcessesByName(processName);
foreach(Process process in processes)
{
process.Kill();
}
</code></pre>
<p>You could just have a list of them you didn't want to run, do the time check (or whatever criteria was to be met) and then walk the list. I did something like this once for a test and it works well enough.</p>
|
<p>I'm not sure if you can catch it starting up, but you could try to look for the program in the list of windows (was it ENUM_WINDOWS? I can never remember) and shut it down as soon as it shows up.</p>
<p>You could probably even do this in AutoIt!</p>
<p>Drag out the Petzold and have some fun with windows...</p>
<p><strong>EDIT:</strong> Check out sysinternals for source on how to list the active processes - do this in a loop and you can catch your program when it starts. I don't think the official site still has the source though, but it's bound to be out there somewhere...</p>
| 17,636
|
<p>I have the following command which will loop over all the subdirectories in a specific location and output the full path:</p>
<pre><code>for /d %i in ("E:\Test\*") do echo %i
</code></pre>
<p>Will give me:</p>
<pre><code>E:\Test\One
E:\Test\Two
</code></pre>
<p>But how do I get both the full path, and just the directory name, so the do command might be something like:</p>
<pre><code>echo %i - %j
</code></pre>
<p>And the output might be something like:</p>
<pre><code>E:\Test\One - One
E:\Test\Two - Two
</code></pre>
<p>Thanks in advance!</p>
|
<p>The following command syntax can be used to return the full path or directory name only:</p>
<pre><code>%~fI - expands %I to a fully qualified path name
%~nI - expands %I to a file name only
</code></pre>
<p>Using your example, the following command will list directories in the format that you specified:</p>
<pre><code>for /d %i in ("E:\Test*") do echo %~fi - %~ni
</code></pre>
|
<p>You can use "%~ni". This is an enhanced substitution that will return the file name of a path (or, more accurately, the last part, which is the directory name in your case):</p>
<pre><code>for /d %i in ("E:\Test\*") do echo %i - %~ni
</code></pre>
<p>See also this question: <a href="https://stackoverflow.com/questions/112055/what-does-d0-mean-in-a-windows-batch-file">What does %~d0 mean in a Windows batch file?</a></p>
| 39,424
|
<p>When I enable common control visual style support (InitCommonControls()) and I am using any theme other then Windows Classic Theme, buttons inside a group box appear with a black border with square corners. </p>
<p>Windows Classic Theme appears normal, as well as when I turn off visual styling.</p>
<p>I am using the following code:</p>
<pre><code>group_box = CreateWindow(TEXT("BUTTON"), TEXT("BS_GROUPBOX"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_GROUP,
10, 10, 200, 300,
hwnd, NULL, hInstance, 0);
push_button = CreateWindow(TEXT("BUTTON"), TEXT("BS_PUSHBUTTON"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
40, 40, 100, 22,
group_box, NULL, hInstance, 0);
</code></pre>
<p>EDIT: The issue occurs with radio buttons as well</p>
<p>EDIT: I am not using any dialogs/resources, only CreateWindow/Ex. </p>
<p>I am compiling under Visual C++ 2008 Express SP1, with a generic <a href="http://msdn.microsoft.com/en-us/library/ms997646.aspx" rel="nofollow noreferrer">manifest</a> file</p>
<p><a href="http://img.ispankcode.com/black_border_issue.png" rel="nofollow noreferrer">Screenshot http://img.ispankcode.com/black_border_issue.png</a></p>
|
<p>The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from <strong>group_box</strong> to <strong>hwnd</strong> (i.e. the dialog).</p>
<p>I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:</p>
<pre><code>// Calculate the client area of a dialog that corresponds to the perceived
// client area of a groupbox control. An extra padding in dialog units can
// be specified (preferably in multiples of 4).
//
RECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {
HWND group = GetDlgItem(dlg, id);
RECT rc;
GetWindowRect(group, &rc);
MapWindowPoints(0, dlg, (POINT*)&rc, 2);
// Note that the top DUs should be 9 to completely avoid overlapping the
// groupbox label, but 8 is used instead for better alignment on a 4x4
// design grid.
RECT border = { 4, 8, 4, 4 };
OffsetRect(&border, padding, padding);
MapDialogRect(dlg, &border);
rc.left += border.left;
rc.right -= border.right;
rc.top += border.top;
rc.bottom -= border.bottom;
return rc;
}
</code></pre>
<p>Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.</p>
|
<p>Ahh yes the black background with radio buttons and group boxes. Although I'm not sure if this will work for VC++ 2008, but back-in-the-day the solution for VB6 themed apps was to put the radio controls on a PictureBox (a generic container really) first and then add that to the group box.</p>
<p>Its worth a shot!</p>
| 26,371
|
<p>I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?</p>
|
<p>I downloaded the wxWidgets source and dug around, and I think this will work.</p>
<p>You need the handle (HWND) for the external window, not the DC.</p>
<pre><code>window = wx.Frame(None, -1, '')
window.AssociateHandle(hwnd)
dc = wx.WindowDC(window)
</code></pre>
|
<p>From what I can tell, DCs in python are abstracted due to platform variation. So a device context in python doesn't directly map to a device context in Windows even though many of the methods are direct Windows method calls. To make this happen it appears you would need to make your own DelegateDC class or something similar that is intended just for Windows so that you could set the DC handle directly.</p>
<p>There might also be some way to attach a wxWindow to the window handle after which you could get a wxWindowDC from the wxWindow...can't figure this out though.</p>
| 30,297
|
<p>I'm working my way into MVC at the moment, but on my "To learn at some point" list, I also have WCF.</p>
<p>I just wonder if WCF is something that should/could be used in an MVC Application or not? The Background is that I want a Desktop Application (.NET 3.5, WPF) interact with my MVC Web Site, and I wonder what the best way to transfer data between the two is. Should I just use special Views/have the controllers return JSON or XML (using the ContentResult)?</p>
<p>And maybe even more important, for the other way round, could I just call special controllers? Not sure how Authorization would work in such a context. I can either use Windows Authentication or (if the Site is running forms authentication) have the user store his/her credentials in the application, but I would then essentially create a HTTP Client in my Application. So while MVC => Application seems really easy, Application => MVC does seem to be somewhat tricky and a possible use for WCF?</p>
<p>I'm not trying to brute-force WCF in this, but I just wonder if there is indeed a good use case for WCF in an MVC application.</p>
|
<p>WCF services might make sense in this situation, but don't create services that align with your UI, create services that align with the business processes. ie. you won't have a service that returns the view data for each page, you will have a service that exposes logical operations. Then, your site can call the same services that the windows client calls, but you don't have to couple the design of the windows client to the design of the web site. </p>
<p>Instead of this:</p>
<p>Windows Client -> Services -> Web Site </p>
<p>It should be:</p>
<p>Windows Client -> Services</p>
<p>Web Site -> Services</p>
|
<p>You could use <a href="http://www.odata.org/" rel="nofollow noreferrer">OData</a> for your MVC application to handle Xml/Json type stuff. I know other people have suggested roll your own - and this is what I'm currently doing .. via the use of my own custom ActionFilter or custom ViewResult.</p>
<p>Sample OData code: <a href="http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.aspx" rel="nofollow noreferrer">Scott Hanselman's OData + StackOverflow blog post</a>.</p>
| 26,685
|
<p>I'm having some minor problems with some animations I'm trying to set up. I have a couple divs stacked on top of each other kind of like this.</p>
<pre><code><div id="div1">
Stuff...
</div>
<div id="div2">
More Stuff...
</div>
</code></pre>
<p>Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js).</p>
<p>The problem occurs when I expand one of the divs using some kind of animation. The shadow does not update with the size of the div. I can redraw the shadow in the callback of the animation but still looks pretty joggy.</p>
<p>Is there a way that I can update the status of my shadows periodically throughout the course of the animation or can anyone recommend a better drop shadow library that would fix the problem? It doesn't have to be jQuery plugin.</p>
|
<p>I would suggest using <strong>CSS</strong> for your drop shadows, and <strong>not JS</strong>.</p>
<p>I have dealt with this exact problem in the past and I have completely stopped using JS for drop shadows. I have never seen animations with JS shadows look as smooth as pure CSS. Also, using too much JS to alter the page elements can cause performance issues.</p>
|
<p>Ok, I still don't know how you animate, but I give you another example:</p>
<pre><code>$('#foo').slideToggle().ready(function(){
$('#foo').dropShadow(options);
});
</code></pre>
<p>So, instead of <code>slideToggle</code>, just use whatever animation <em>thingy</em> you got.</p>
<p>Hope that helps.</p>
| 22,930
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.