instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
---|---|---|---|
<p>What is the best way to debug a custom ODBC driver on Windows? A former member of our team wrote the driver so we have the source available.</p>
<p>How do you attach a debugger to the driver? Or is it easier to just add "trace prints" to the driver to see what is going on?</p>
| <p>The best solution i found so far is a combination of trace prints and breakpoints (int 3) compiled into the driver.</p>
<p>Trace prints for general debug information and the breakpoints for pieces of the code where I need to more thoroughly investigate the inner state of the driver.</p>
| <p>Supportingly to VS you could use <a href="http://www.wireshark.org/" rel="nofollow noreferrer">WireShark</a> to see what the ODCB driver is sending to the DB.</p>
| 11,684 |
<p>I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.</p>
| <pre>
CREATE TABLE #tmpSizeChar (
table_name sysname ,
row_count int,
reserved_size varchar(50),
data_size varchar(50),
index_size varchar(50),
unused_size varchar(50))
CREATE TABLE #tmpSizeInt (
table_name sysname ,
row_count int,
reserved_size_KB int,
data_size_KB int,
index_size_KB int,
unused_size_KB int)
SET NOCOUNT ON
INSERT #tmpSizeChar
EXEC sp_msforeachtable 'sp_spaceused ''?'''
INSERT INTO #tmpSizeInt (
table_name,
row_count,
reserved_size_KB,
data_size_KB,
index_size_KB,
unused_size_KB
)
SELECT [table_name],
row_count,
CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size,
CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size,
CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size,
CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size
FROM #tmpSizeChar
/*
DROP TABLE #tmpSizeChar
DROP TABLE #tmpSizeInt
*/
SELECT * FROM #tmpSizeInt
ORDER BY reserved_size_KB DESC
</pre>
| <p>Check out this, I know it works in 2005 (<a href="https://learn.microsoft.com/sql/relational-databases/system-catalog-views/sys-database-files-transact-sql" rel="nofollow noreferrer">Microsoft Documentation</a>):</p>
<p>Here is is for the pubs DB
<pre><code>
select *
from pubs.sys.database_files
</pre></code></p>
<p>Returns the size and max_size.</p>
| 2,482 |
<p>I have just finished building a Tronxy P802M Prusa i3.</p>
<p>When I try to move the Z-axis, using the hardware buttons in the LCD menu (without a computer connected), it only goes down, when I both increase, and decrease, the value of Z.</p>
<p>Any suggestions?</p>
| <p>It could be a hardware fault. </p>
<p>First check, and compare, the control board connections to the motors of the three axes. You don't state it in your question but, presumably, the X and Y axes move correctly? If so, then compare the connections for the Z-axis motors with the connections for the motors of the axes that work as expected.</p>
<p>If they are correct then the problem is likely to be with the firmware.</p>
<p>Have you...</p>
<ul>
<li>homed the Z-axis yet?</li>
<li>installed the endstops?</li>
</ul>
<p>From <a href="https://makerware.thingiverse.com/groups/prusa-i3/topic:7370" rel="noreferrer">X Y Z axis only move one direction?</a>:</p>
<blockquote>
<p>Using Marlin? Before you do a <code>G28</code> homing the axes will only move
towards the endstops. But also check your endstops with <code>M119</code> to make
sure they are triggered at the right time. On older Marlin, you may
need to set <code>DISABLE_MAX_ENDSTOPS</code> (on a machine that has no max
endstops). Newer Marlin uses <code>USE_XMIN_PLUG</code>, etc., to specifically
set which endstops are connected. If the switches show the opposite
state (off when triggered) then set the
<code>[XYZ]_(MIN|MAX)_ENDSTOP_INVERTING</code> flags, as needed.</p>
</blockquote>
<p>Likewise, from <a href="http://www.instructables.com/id/Building-a-Prusa-i3-3D-Printer/" rel="noreferrer">Building a Prusa I3 3D Printer</a>:</p>
<blockquote>
<p>You will probably also find the motor will turn only in one direction. This is normal for now as we don't have end-stops installed and haven't homed the axis - so the software doesn't know how far it can go in one direction or the other.</p>
</blockquote>
<hr>
<p>As Mark states in his <a href="https://3dprinting.stackexchange.com/questions/4158/prusa-i3-z-axis-only-goes-down-even-on-up-command#comment5758_4162">comment</a>, the P802M uses a Melzi board. From <a href="https://github.com/repetier/Repetier-Firmware/tree/master/boards/Zonestar%20P802M" rel="noreferrer">Github: Repetier-Firmware/boards/Zonestar P802M/</a>:</p>
<blockquote>
<p>There are some printers sold under different names like 'Zonestar
P802M', 'Prusa i3 P802M DIY kit', 'Anet A8-B', etc, which have LCD
20x4 with 5 keys controller connected to Melzi V2.0 board via 10 wires
cable. Keys are connected to a single analog input using resistive
divider.</p>
</blockquote>
| <p>It could be a hardware fault. </p>
<p>First check, and compare, the control board connections to the motors of the three axes. You don't state it in your question but, presumably, the X and Y axes move correctly? If so, then compare the connections for the Z-axis motors with the connections for the motors of the axes that work as expected.</p>
<p>If they are correct then the problem is likely to be with the firmware.</p>
<p>Have you...</p>
<ul>
<li>homed the Z-axis yet?</li>
<li>installed the endstops?</li>
</ul>
<p>From <a href="https://makerware.thingiverse.com/groups/prusa-i3/topic:7370" rel="noreferrer">X Y Z axis only move one direction?</a>:</p>
<blockquote>
<p>Using Marlin? Before you do a <code>G28</code> homing the axes will only move
towards the endstops. But also check your endstops with <code>M119</code> to make
sure they are triggered at the right time. On older Marlin, you may
need to set <code>DISABLE_MAX_ENDSTOPS</code> (on a machine that has no max
endstops). Newer Marlin uses <code>USE_XMIN_PLUG</code>, etc., to specifically
set which endstops are connected. If the switches show the opposite
state (off when triggered) then set the
<code>[XYZ]_(MIN|MAX)_ENDSTOP_INVERTING</code> flags, as needed.</p>
</blockquote>
<p>Likewise, from <a href="http://www.instructables.com/id/Building-a-Prusa-i3-3D-Printer/" rel="noreferrer">Building a Prusa I3 3D Printer</a>:</p>
<blockquote>
<p>You will probably also find the motor will turn only in one direction. This is normal for now as we don't have end-stops installed and haven't homed the axis - so the software doesn't know how far it can go in one direction or the other.</p>
</blockquote>
<hr>
<p>As Mark states in his <a href="https://3dprinting.stackexchange.com/questions/4158/prusa-i3-z-axis-only-goes-down-even-on-up-command#comment5758_4162">comment</a>, the P802M uses a Melzi board. From <a href="https://github.com/repetier/Repetier-Firmware/tree/master/boards/Zonestar%20P802M" rel="noreferrer">Github: Repetier-Firmware/boards/Zonestar P802M/</a>:</p>
<blockquote>
<p>There are some printers sold under different names like 'Zonestar
P802M', 'Prusa i3 P802M DIY kit', 'Anet A8-B', etc, which have LCD
20x4 with 5 keys controller connected to Melzi V2.0 board via 10 wires
cable. Keys are connected to a single analog input using resistive
divider.</p>
</blockquote>
| 611 |
<p>I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding. </p>
<p>Previously:</p>
<pre><code><%= Html.Encode( ViewData['username'] ) %>
</code></pre>
<p>Would be equivalent to:</p>
<pre><code><%=h ViewData['username'] %>
</code></pre>
<p>Anyone have any ideas how I could do this, maybe using an extension method or something?</p>
| <p>It's not so clean as an operator overload, but I used the following extension method:</p>
<pre><code>public static string Safe(this string sz)
{
return HttpUtility.HtmlEncode(sz);
}
</code></pre>
<p>So in my aspx id do:</p>
<pre><code><%= this.ViewData["username"].Safe() %>
</code></pre>
<p>Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.</p>
| <p><strong>NOTE: This is an ugly and untested hack, I don't think I'd ever do this</strong></p>
<pre><code>public static String h (this System.Object o, System.Object viewData)
{
return Html.Encode(viewData);
}
</code></pre>
<p>I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.</p>
<p>this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job:</p>
<pre><code><%=h(ViewData['username']) %>
</code></pre>
| 23,397 |
<p>Ok so I've implemented both REST and SOAP services and I like both depending on the context. For me, WS* is great when I want an explicit contract between the server and the client e.g. for sensitive information or for mission critical stuff. REST on the other hand whilst flexible in terms of the schema definition, is in my mind more ideal for content services or data which is not required to undergo any serious business logic.</p>
<p>REST seems to be very much the flavour of the day, and I was somewhat put out when Martin Fowler et al from Thoughworks gave this podcast: <a href="http://www.thoughtworks.com/what-we-say/podcasts.html" rel="nofollow noreferrer">http://www.thoughtworks.com/what-we-say/podcasts.html</a> on REST and were derisive toward WS*. Whilst the man himself is well respected, am I right in thinking that there still is very much a place for SOAP and pinch of salt is required here? And has anyone used REST in a serious business application? </p>
| <p>Can you document your REST api by providing someone a description of the media types you use and a single URL?</p>
<p>If you find yourself providing a list of URLs and what verbs can be used on those URLs then you probably don't have a <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven" rel="nofollow noreferrer">REST api</a>.</p>
<p>Once you have created a true REST api then go back and compare it to WS* api. You will see they are very different.</p>
<p>REST apis can easily handle "serious business logic" and yes I have used REST in a serious business application.</p>
| <p><a href="http://www.infoq.com/presentations/mark-little-soa-rest" rel="nofollow noreferrer">Diary of a Fence Sitting SOA Geek - Dr Mark Little</a></p>
<p>Presentation is very recent - pretty revealing stuff.</p>
<p>REST actually works. It's not as good for repeat business as SOAP is. So many consultants fight to save SOAP on that basis. As the tools and frameworks for RESTful architectures improve, businesses will move in that direction. Governance is big talk at the moment also.</p>
<p>The new version of JAX-RS is a pretty interesting new tool for RESTful dev, Mark Little mentions this in his presentation.</p>
<p>You're probably better off considering SOAP as legacy technology, it'll serve you better going forward. ;)</p>
| 28,702 |
<p>I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:</p>
<blockquote>
<p>Could not find default endpoint element that references contract
'MyServiceReference.IMyService' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this contract could be found in the client element.</p>
</blockquote>
<p>The code I am using to create the instance is:</p>
<pre><code>myServiceClient = new MyServiceClient();
</code></pre>
<p>where MyServiceClient inherits from</p>
<p>System.ServiceModel.ClientBase</p>
<p>How do I solve this?</p>
<p>Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.</p>
| <blockquote>
<p>Here is my app.config file of the class library:</p>
</blockquote>
<p>You should put this configuration settings to main app's config file. .NET application (which is calling your class library) uses data from it's own config file not from your library config file.</p>
| <p>It would probably help if you posted your app.config file, since this kind of error tends to point to a problem in the <code><endpoint></code> block. Make sure the contract attribute seems right to you.</p>
<p>Edit: Try fully qualifying your contract value; use the full namespace. I think that is needed.</p>
| 4,464 |
<p>We have an e-commerce site that uses certificates from Thawte, we had our certficate renewed in October. If you access https-pages from IE6 you get a warning that the certificate has expired, if you look at the expiration date it's actually the old certificate. Now, this doesn't happen at all when accessing the page from IE7.</p>
<p>This happens when accessing the page from ANY computer with IE6 so it can't be that the certificate is cached locally.</p>
| <p>I don't know if it will work, but you could try <a href="http://www.codeguru.com/csharp/csharp/cs_misc/icons/article.php/c4261" rel="nofollow noreferrer">this</a>, pointing at the drive root.</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx" rel="nofollow noreferrer">SHGetFileInfo</a> is how the operating system exposes information about objects in the file system. How you go about calling it from a .NET WinForms app? I can't help you there.</p>
| 49,033 |
<p>If we are going to develop a community website for non geeks, is it ok if we implement openid registration. How much openid is acceptable in non geek community. Anybody having any idea about this. </p>
| <p>Do both - provide OpenID for those that want to use it and have a regular user account signup for those that don't. You could even go all the way and become an OpenID provider and allow users with regular accounts on your system to use them as OpenIDs on other systems.</p>
<p>In short, OpenID is OK as long as it's not the only option.</p>
<p>One small note: If you do decide to provide OpenID authentication, you need to be prepared for users <a href="https://web.archive.org/web/20090407063154/http://stackoverflow.com:80/questions/347019/regaining-access-to-a-stackoverflow-profile" rel="nofollow noreferrer">locking themselves out of their accounts</a>. You should also provide a mechanism for <a href="https://web.archive.org/web/20090424075552/http://stackoverflow.uservoice.com:80/pages/general/suggestions/16685" rel="nofollow noreferrer">changing the associated OpenID</a>.</p>
| <p>You can choose both Open ID and Traditional login functionality. its becoming quite adaptable among non geeks also. You can even look for Google's <a href="http://www.google.com/friendconnect/" rel="nofollow noreferrer">friend connect</a> for further reference. </p>
| 45,836 |
<p>My 3D prints shift along the Y-axis on my Ender 3 3D printer. I don't know what to do. My Y-axis belt is tight, So I don't think that is the problem...</p>
<p><a href="https://i.stack.imgur.com/zVtPS.png" rel="nofollow noreferrer" title="Y-axis layer shifting"><img src="https://i.stack.imgur.com/zVtPS.png" alt="Y-axis layer shifting" title="Y-axis layer shifting" /></a></p>
| <p>8 mm rods and 6 mm GT2 belts are generally accepted as a good tradeoff between price and performance, an exact calculation is possible but might not be very relevant if another part is flexing. Also, generally speaking, the smaller the part the sooner it will wear out of specification. Thus your service interval might be higher compared to an over-engineered printer.</p>
<p>In short, it depends on what your goal is, if you desire low maintenance and accurate machine, you might be better off with heavier gauge parts. Obviously, this will also affect the speed of printing.
A 6 mm GT2 belt might have a higher stretch factor compared to a 10 mm belt, but can be mitigated by adjusting the acceleration. In addition, a 10 mm belt has a larger pulley reducing the number of steps per mm, lowering precision. As such you might be better of using two 6 mm belts.</p>
<p>Increased rod size for the print bed will not affect printing speed much but might help with accuracy since the bending modulus is lower. Play around with the calculators below to get an idea of the force your beam will have to withstand. That said, there are a lot of other factors that will flex under load, for example, the bed leveling springs. You can replace them with solid spacers, but that might warp the bed when it heats up.</p>
<p><a href="https://www.engineering.com/calculators/beams.htm" rel="nofollow noreferrer">https://www.engineering.com/calculators/beams.htm</a></p>
<p><a href="https://www.omnicalculator.com/physics/acceleration" rel="nofollow noreferrer">https://www.omnicalculator.com/physics/acceleration</a></p>
<p>To conclude, I would use the calculators to figure out if the 8 mm rods are within tolerance for the intended speeds and load, but don't forget to look at the overall picture. The quality of parts you choose is one such thing.</p>
| <p>The 3D printing revolution started out with the idea/community project to build self-replicating machines:</p>
<blockquote>
<p>RepRap was the first of the low-cost 3D printers, and the RepRap Project started the open-source 3D printer revolution. It has become the most widely-used 3D printer among the global members of the Maker Community.
<em>(From RepRap.org)</em></p>
</blockquote>
<p>The main aspects for this project was to build self-replicating machines from cheap and "simple" available materials and making them freely available for the benefit of everyone. The rod solution is a simple and affordable solution for linear motion with fair tolerances.</p>
<p>As far as the rigidity of the X carriage, rods aren't the best solution, increasing rod diameter will surely increase the stiffness, but it will be smaller than a design that uses a (quality) linear rail, these are much stiffer. Note that instead of steel, carbon rods can be used, these are stiff and light and reduce the weight of the carriage, allowing for higher acceleration and speed. The solution of using rods is mainly based on availability and being a cheap solution.</p>
<p>Do note that rods flex much more than linear rails, even when you increase the diameter, this will limit the length of the X-axis.</p>
<p><a href="https://m.all3dp.com/2/linear-rail-3d-printer-really-better-or-just-a-hype/" rel="nofollow noreferrer">From all3Dp</a>:</p>
<blockquote>
<p>Any decent rail will have far less give. In terms of 3D printing, this leads to greatly reduced backlash and ringing artifacts, yielding cleaner print surfaces and edges.</p>
</blockquote>
<p>Belts allow the rotational motion to be transferred into a linear motion. Belt width depends on the force (carriage weight) you need to move. Same as for rods, an increased height will allow for a larger load to be driven/moved, but for a fixed load, the increasing height allows for less stretch and thus less printing defects. Note the different <a href="https://3dprinting.stackexchange.com/a/6714">types of belts</a> are available, all having their own stiffness and load bearing capacity.</p>
| 1,772 |
<p>We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords.</p>
<p>The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query?</p>
<p>Example:</p>
<pre><code>@CustomerId AS INT
@Keywords AS NVARCHAR(MAX)
@sql = 'SELECT event_name FROM calendar WHERE customer_id = @CustomerId '
--(loop through each keyword passed in and concatenate)
@sql = @sql + 'AND (event_name LIKE ''%' + @Keywords + '%'' OR event_details LIKE ''%' + @Keywords + '%'')'
EXEC sp_executesql @sql N'@CustomerId INT, @CustomerId = @CustomerId
</code></pre>
<p>What is the best way to handle this and maintaining protection from SQL injection? </p>
| <p>You may not like to hear this, but it might be better for you to go back to dynamically constructing your SQL query in code before issuing against the database. If you use parameter placeholders in the SQL string you get the protection against SQL injection attacks.</p>
<p>Example:</p>
<pre><code>string sql = "SELECT Name, Title FROM Staff WHERE UserName=@UserId";
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("@UserId", SqlType.VarChar).Value = "smithj";
</code></pre>
<p>You can build the SQL string depending on the set of columns you need to query and then add the parameter values once the string is complete. This is a bit of a pain to do, but I think it is much easier than having really complicated TSQL which unpicks lots of possible permutations of possible inputs.</p>
| <ul>
<li><p>Unless you need it, you could simply strip out any character that's not in [a-zA-Z ] - most of those things won't be in searches and you should not be able to be injected that way, nor do you have to worry about keywords or anything like that. If you allow quotes, however, you will need to be more careful.</p></li>
<li><p>Similar to sambo99's #1, you can insert the keywords into a temporary table or table variable and join to it (even using wildcards) without danger of injection:</p></li>
</ul>
<p>This isn't really dynamic:</p>
<pre><code>SELECT DISTINCT event_name
FROM calendar
INNER JOIN #keywords
ON event_name LIKE '%' + #keywords.keyword + '%'
OR event_description LIKE '%' + #keywords.keyword + '%'
</code></pre>
<ul>
<li><p>You can actually generate an SP with a large number of parameters instead of coding it by hand (set the defaults to '' or NULL depending on your preference in coding your searches). If you found you needed more parameters, it would be simple to increase the number of parameters it generated.</p></li>
<li><p>You can move the search to a full-text index outside the database like Lucene and then use the Lucene results to pull the matching database rows.</p></li>
</ul>
| 18,769 |
<p>How to solve "Must be MarshalByRefObject" in a good but multiple-inheritance amputated language like C#?</p>
<p>The problem is very simple, in several cases you just have to inherit from this class (infrastructure requirements).
It does not matter here really, which cases.
So, what do you do if you've already inherited from some other class (your domain model requirements)?</p>
<p>Btw good application frameworks, like spring.net always make sure you DON'T have to inherit from this class no matter what kind of infrastructure you need to apply to your class.</p>
<p><strong>I would like to know what am I getting -3 votes here for?? :)</strong></p>
| <p>In general you only want to make an object MarshalByRef if you're going to use it in a Remoting / WCF context. This is usually a special-enough case that it's not a pain.</p>
<p>Suppose you had a general type, and you wanted to derive from it and specialise it, and then remote the derived type - now you have a problem, because to be remoted an object must inherit from MarshalByRefObject, and your original general type didn't. Suppose you can't change it because you're doing binary inheritance, or because it itself derives from a base class you can't change? As the questioner points out, since C# (and .NET in general) doesn't allow MI, you can't inherit from both.</p>
<p>The short answer is that you're sort-of screwed. You either change the general type to inhert from MarshalByRefObject (or go far enough up the chain that you can insert it somewhere effective), or else you can think about mucking about with proxy objects. </p>
<p>You could for example create an interface contract that describes your type's interface, and then build a proxy type inheriting from MarshalByRefObject that also implements that interface by composition and delegation to an instance of your type (ie a wrapper). You could then remote an instance of that proxy type which would instantiate your type and do the work as expected - but all return types from methods have to be [Serializable].</p>
<pre><code>public interface IMyType
{
string SayHello();
string BaseTypeMethodIWantToUse();
}
public class MyType : MyBaseType, IMyType
{
public string SayHello()
{
return "Hello!";
}
}
public class MyRemoteableType : MarshalByRefObject, IMyType
{
private MyType _instance = new MyType();
public string SayHello()
{
return _instance.SayHello();
}
public string BaseTypeMethodIWantToUse()
{
return _instance.BaseTypeMethodIWantToUse();
}
}
</code></pre>
<p>Seems like a lot of work, though. Ultimately if you're in this scenario I'd suggest a redesign or a rethink.</p>
| <p>"So, what do you do if you've already inherited from some other class (your domain model requirements)?"</p>
<p>Can you create a base class for the piece of your domain model that requires inheritance from MarshalByRefObject?</p>
| 40,380 |
<p>I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the <code>pause</code> command. Is there a Linux equivalent I can use in my script?</p>
| <p><code>read</code> does this:</p>
<pre><code>user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$
</code></pre>
<p>The <code>-n1</code> specifies that it only waits for a single character. The <code>-r</code> puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The <code>-p</code> specifies the prompt, which must be quoted if it contains spaces. The <code>key</code> argument is only necessary if you want to know which key they pressed, in which case you can access it through <code>$key</code>.</p>
<p>If you are using Bash, you can also specify a timeout with <code>-t</code>, which causes read to return a failure when a key isn't pressed. So for example:</p>
<pre><code>read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
echo 'A key was pressed.'
else
echo 'No key was pressed.'
fi
</code></pre>
| <p>Try this:</p>
<pre><code>function pause(){
read -p "$*"
}
</code></pre>
| 11,826 |
<p>I want to write a simple colour management framework in C#, Java and AS3. I only want to write the unit tests once though, rather than recreating the unit tests in JUnit, FlexUnit and say NUnit. </p>
<p>I have in mind the idea of say an xml file that defines manipulations of "instance" and assertions based on the state of "instance" via setup, teardown and a set tests. Then to have a utility that can convert that XML into xUnit code, for an arbitrary number of xUnits. Before I start wasting time developing such a solution though, I want to make sure no similar solution already exists.</p>
| <p>Would FIT/ <a href="http://fitnesse.org/" rel="nofollow noreferrer">Fitnesse</a> be suitable for what you want?</p>
<p>FIT is an acceptance test framework rather than unit test framework, but from what you describe you would want to ensure that the three implementations have the same behavior rather than identical designs.</p>
<p>FIT has links to <a href="http://fitnesse.org/FitServers" rel="nofollow noreferrer">several languages</a></p>
| <p>You could also check out Fitnesse with <a href="http://www.fitnesse.org/FitNesse.SliM" rel="nofollow noreferrer">Slim</a>, as Slim should be a lot more lightweight to implement for new languages (AS3). I guess it's more about acceptance/integration testing than unit testing, but it could be worth looking into.</p>
| 9,545 |
<p>I have taken over the development of a web application that is targeted at the .net 1.0 framework and is written in C# and Visual Basic. </p>
<p>I decided that the first thing we need to do is refine the build process, I wrote build files for the C# projects, but am having tons of problems creating a build file for Visual Basic. </p>
<p>Admittedly, I do not personally know VB, but it seems like I have to hardcode all the imports and references in my build file to get anything to work...certainly not the best way to be doing things...</p>
<p>For any example: if I do not include the namespace System in the build file I will get several errors of common Unkown Types e.g: Guid</p>
<p>does NAnt typically require this for VB code or is does the VB code need a possible NAnt-freindly refactoring?</p>
<p>Does anybody have VB NAnt tips?</p>
| <p>I have had a similar experience with NAnt and the vbc compiler for VB.NET projects that are developed with Visual Studio. My solution has been to avoid importing namespaces at the project level in Visual Studio (which occurs by default), and use explicit Imports statements at the class/file level. C# projects work this way by default (no project level namespace imports), and I like the extra information provided by explicit namespace directives when looking at a file.</p>
<p>Interesting that VB.NET and C# VS projects are so different in that respect.</p>
| <p>I'm not sure, if you talk about VB or VB.Net.<br>
Either way, have a look at <a href="http://nantcontrib.sourceforge.net/release/latest/help/tasks/" rel="nofollow noreferrer">Nant Contrib</a>. Maybe they have a solution.</p>
| 3,476 |
<p>I'm writing a bit of code to display a bar (or line) graph in our software. Everything's going fine. The thing that's got me stumped is labeling the Y axis.</p>
<p>The caller can tell me how finely they want the Y scale labeled, but I seem to be stuck on exactly what to label them in an "attractive" kind of way. I can't describe "attractive", and probably neither can you, but we know it when we see it, right?</p>
<p>So if the data points are:</p>
<pre><code> 15, 234, 140, 65, 90
</code></pre>
<p>And the user asks for 10 labels on the Y axis, a little bit of finagling with paper and pencil comes up with:</p>
<pre><code> 0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250
</code></pre>
<p>So there's 10 there (not including 0), the last one extends just beyond the highest value (234 < 250), and it's a "nice" increment of 25 each. If they asked for 8 labels, an increment of 30 would have looked nice:</p>
<pre><code> 0, 30, 60, 90, 120, 150, 180, 210, 240
</code></pre>
<p>Nine would have been tricky. Maybe just have used either 8 or 10 and call it close enough would be okay. And what to do when some of the points are negative?</p>
<p>I can see Excel tackles this problem nicely. </p>
<p>Does anyone know a general-purpose algorithm (even some brute force is okay) for solving this? I don't have to do it quickly, but it should look nice.</p>
| <p>A long time ago I have written a graph module that covered this nicely. Digging in the grey mass gets the following:</p>
<ul>
<li>Determine lower and upper bound of the data. (Beware of the special case where lower bound = upper bound!</li>
<li>Divide range into the required amount of ticks.</li>
<li>Round the tick range up into nice amounts.</li>
<li>Adjust the lower and upper bound accordingly.</li>
</ul>
<p>Lets take your example:</p>
<pre><code>15, 234, 140, 65, 90 with 10 ticks
</code></pre>
<ol>
<li>lower bound = 15</li>
<li>upper bound = 234</li>
<li>range = 234-15 = 219</li>
<li>tick range = 21.9. This should be 25.0</li>
<li>new lower bound = 25 * round(15/25) = 0</li>
<li>new upper bound = 25 * round(1+235/25) = 250</li>
</ol>
<p>So the range = 0,25,50,...,225,250</p>
<p>You can get the nice tick range with the following steps:</p>
<ol>
<li>divide by 10^x such that the result lies between 0.1 and 1.0 (including 0.1 excluding 1).</li>
<li>translate accordingly:
<ul>
<li>0.1 -> 0.1</li>
<li><= 0.2 -> 0.2</li>
<li><= 0.25 -> 0.25</li>
<li><= 0.3 -> 0.3</li>
<li><= 0.4 -> 0.4</li>
<li><= 0.5 -> 0.5</li>
<li><= 0.6 -> 0.6</li>
<li><= 0.7 -> 0.7</li>
<li><= 0.75 -> 0.75</li>
<li><= 0.8 -> 0.8</li>
<li><= 0.9 -> 0.9</li>
<li><= 1.0 -> 1.0</li>
</ul></li>
<li>multiply by 10^x. </li>
</ol>
<p>In this case, 21.9 is divided by 10^2 to get 0.219. This is <= 0.25 so we now have 0.25. Multiplied by 10^2 this gives 25.</p>
<p>Lets take a look at the same example with 8 ticks:</p>
<pre><code>15, 234, 140, 65, 90 with 8 ticks
</code></pre>
<ol>
<li>lower bound = 15</li>
<li>upper bound = 234</li>
<li>range = 234-15 = 219</li>
<li>tick range = 27.375
<ol>
<li>Divide by 10^2 for 0.27375, translates to 0.3, which gives (multiplied by 10^2) 30.</li>
</ol></li>
<li>new lower bound = 30 * round(15/30) = 0</li>
<li>new upper bound = 30 * round(1+235/30) = 240</li>
</ol>
<p>Which give the result you requested ;-).</p>
<p>------ Added by KD ------</p>
<p>Here's code that achieves this algorithm without using lookup tables, etc...:</p>
<pre><code>double range = ...;
int tickCount = ...;
double unroundedTickSize = range/(tickCount-1);
double x = Math.ceil(Math.log10(unroundedTickSize)-1);
double pow10x = Math.pow(10, x);
double roundedTickRange = Math.ceil(unroundedTickSize / pow10x) * pow10x;
return roundedTickRange;
</code></pre>
<p>Generally speaking, the number of ticks includes the bottom tick, so the actual y-axis segments are one less than the number of ticks.</p>
| <p>Based on @Gamecat's algorithm, I produced the following helper class</p>
<pre><code>public struct Interval
{
public readonly double Min, Max, TickRange;
public static Interval Find(double min, double max, int tickCount, double padding = 0.05)
{
double range = max - min;
max += range*padding;
min -= range*padding;
var attempts = new List<Interval>();
for (int i = tickCount; i > tickCount / 2; --i)
attempts.Add(new Interval(min, max, i));
return attempts.MinBy(a => a.Max - a.Min);
}
private Interval(double min, double max, int tickCount)
{
var candidates = (min <= 0 && max >= 0 && tickCount <= 8) ? new[] {2, 2.5, 3, 4, 5, 7.5, 10} : new[] {2, 2.5, 5, 10};
double unroundedTickSize = (max - min) / (tickCount - 1);
double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);
double pow10X = Math.Pow(10, x);
TickRange = RoundUp(unroundedTickSize/pow10X, candidates) * pow10X;
Min = TickRange * Math.Floor(min / TickRange);
Max = TickRange * Math.Ceiling(max / TickRange);
}
// 1 < scaled <= 10
private static double RoundUp(double scaled, IEnumerable<double> candidates)
{
return candidates.First(candidate => scaled <= candidate);
}
}
</code></pre>
| 42,323 |
<p><strong>Summary:</strong> I'm developing a persistent Java web application, and I need to make sure that all resources I persist have globally unique identifiers to prevent duplicates.</p>
<p><strong>The Fine Print:</strong></p>
<ol>
<li>I'm not using an RDBMS, so I don't have any fancy sequence generators (such as the one provided by Oracle)</li>
<li>I'd like it to be fast, preferably all in memory - I'd rather not have to open up a file and increment some value</li>
<li>It needs to be thread safe (I'm anticipating that only one JVM at a time will need to generate IDs)</li>
<li>There needs to be consistency across instantiations of the JVM. If the server shuts down and starts up, the ID generator shouldn't re-generate the same IDs it generated in previous instantiations (or at least the chance has to be really, really slim - I anticipate many millions of presisted resources)</li>
<li>I have seen the examples in the EJB unique ID pattern article. They won't work for me (I'd rather not rely solely on System.currentTimeMillis() because we'll be persisting multiple resources per millisecond).</li>
<li>I have looked at the answers proposed in <a href="https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java">this question</a>. My concern about them is, what is the chance that I will get a duplicate ID over time? I'm intrigued by the suggestion to use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html" rel="nofollow noreferrer">java.util.UUID</a> for a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="nofollow noreferrer">UUID</a>, but again, the chances of a duplicate need to be infinitesimally small.</li>
<li>I'm using JDK6</li>
</ol>
| <p>Pretty sure UUIDs are "good enough". There are 340,282,366,920,938,463,463,374,607,431,770,000,000 UUIDs available.</p>
<p><a href="http://www.wilybeagle.com/guid_store/guid_explain.htm" rel="noreferrer">http://www.wilybeagle.com/guid_store/guid_explain.htm</a></p>
<p>"To put these numbers into perspective, one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion, that means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs"</p>
<p><a href="http://en.wikipedia.org/wiki/Universally_Unique_Identifier" rel="noreferrer">http://en.wikipedia.org/wiki/Universally_Unique_Identifier</a></p>
| <p>From memory the RMI remote packages contain a UUID generator. I don't know whether thats worth looking into.</p>
<p>When I've had to generate them I typically use a MD5 hashsum of the current date time, the user name and the IP address of the computer. Basically the idea is to take everything that you can find out about the computer/person and then generate a MD5 hash of this information.</p>
<p>It works really well and is incredibly fast (once you've initialised the MessageDigest for the first time).</p>
| 23,444 |
<p>Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?</p>
| <pre><code>void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl cbo =
e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDown;
}
}
</code></pre>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=13855&SiteID=1" rel="nofollow noreferrer">Problem with combobox and databound datagridview</a></p>
| <pre><code>if (!Column1.Items.Contains(e.FormattedValue.ToString())) {
Column1.Items.Add(e.FormattedValue);
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue;
}
</code></pre>
<p>may always return true because
<code>Column1.Items.Contains()</code>
is searching for <code>String</code> values.
if <code>e.FormattedValue</code> is not a <code>String</code> then the comparison will fail.</p>
<p>try</p>
<pre><code>if (!Column1.Items.Contains(e.FormattedValue.ToString())) {
Column1.Items.Add(e.FormattedValue.ToString());
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue.ToString();
}
</code></pre>
<p>or </p>
<pre><code>if (!Column1.Items.Contains(e.FormattedValue)) {
Column1.Items.Add(e.FormattedValue);
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue;
}
</code></pre>
| 24,697 |
<p>Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces?</p>
<p>For example:</p>
<pre><code>public MyMethod()
{
if (test)
{
// More { }
}
// More { }
} // End
</code></pre>
<p>Should match:</p>
<pre><code>{
if (test)
{
// More { }
}
// More { }
}
</code></pre>
| <p>No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a <em>finite</em> automaton.</p>
<p>You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).</p>
<p>There are many parser generators avialable, for instance <a href="http://www.antlr.org/" rel="noreferrer">ANTLR</a> for Java. Finding an existing grammar for Java (or C) is also not difficult.<br>
For more background: <a href="http://en.wikipedia.org/wiki/Automata_theory" rel="noreferrer">Automata Theory</a> at Wikipedia</p>
| <p>This seems to work: <code>/(\{(?:\{.*\}|[^\{])*\})/m</code></p>
| 16,170 |
<p>whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#</p>
<p>cheers.. </p>
| <p>The simplest way is to simply write either csv, or html (in particular, a <code><table><tr><td>...</td></tr>...</table></code>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...</p>
<p>Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a <code>DataTable</code>, looping over the rows).</p>
<pre><code> public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
{
if (data == null) throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename)) filename = "export.csv";
HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
// remove this line if you don't want to prompt the user to save the file
resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
// if not saving, try: "application/ms-excel"
resp.ContentType = "text/csv";
string csv = GetCsv(headers, data);
byte[] buffer = resp.ContentEncoding.GetBytes(csv);
resp.AddHeader("Content-Length", buffer.Length.ToString());
resp.BinaryWrite(buffer);
resp.End();
}
static void WriteRow(string[] row, StringBuilder destination)
{
if (row == null) return;
int fields = row.Length;
for (int i = 0; i < fields; i++)
{
string field = row[i];
if (i > 0)
{
destination.Append(',');
}
if (string.IsNullOrEmpty(field)) continue; // empty field
bool quote = false;
if (field.Contains("\""))
{
// if contains quotes, then needs quoting and escaping
quote = true;
field = field.Replace("\"", "\"\"");
}
else
{
// commas, line-breaks, and leading-trailing space also require quoting
if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
|| field.StartsWith(" ") || field.EndsWith(" "))
{
quote = true;
}
}
if (quote)
{
destination.Append('\"');
destination.Append(field);
destination.Append('\"');
}
else
{
destination.Append(field);
}
}
destination.AppendLine();
}
static string GetCsv(string[] headers, IEnumerable<string[]> data)
{
StringBuilder sb = new StringBuilder();
if (data == null) throw new ArgumentNullException("data");
WriteRow(headers, sb);
foreach (string[] row in data)
{
WriteRow(row, sb);
}
return sb.ToString();
}
</code></pre>
| <p><a href="http://www.spreadsheetgear.com/" rel="nofollow noreferrer">SpreadsheetGear for .NET</a> will do it.</p>
<p>You can see live ASP.NET samples with C# and VB source code <a href="http://www.spreadsheetgear.com/support/samples/" rel="nofollow noreferrer">here</a>. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial <a href="https://www.spreadsheetgear.com/downloads/register.aspx" rel="nofollow noreferrer">here</a> if you want to try it yourself.</p>
<p>Disclaimer: I own SpreadsheetGear LLC</p>
| 34,139 |
<p>Can you use SIMBL to develop a plug-in for the iPhone's Safari?</p>
| <p>No, you cannot.</p>
| <p>You could also create a Safari webplugin, which loads a custom UIView to display content based on MIME types.</p>
<p><a href="http://iphonedevwiki.net/index.php/Internet_Plug-Ins" rel="nofollow noreferrer">http://iphonedevwiki.net/index.php/Internet_Plug-Ins</a></p>
| 42,841 |
<p>Imagine this sample java class:</p>
<pre><code>class A {
void addListener(Listener obj);
void removeListener(Listener obj);
}
class B {
private A a;
B() {
a = new A();
a.addListener(new Listener() {
void listen() {}
}
}
</code></pre>
<p>Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance.</p>
<p>I am worried that I might be creating a garbage collector problem here. What is the best practice?</p>
| <p>There is a cycle in the reference graph. A references B and B references A. The garbage collector will detect cycles and see when there are no external references to A and B, and will then collect both.</p>
<p>Attempting to use the finaliser here is wrong. If B is being destroyed, the reference to A is also being removed.</p>
<hr>
<p>The statement: "Assume that the A instance will be shared with some other objects as well and will outlive the B instance." is wrong. The only way that will happen is if the listener is explicitly removed from somewhere other than a finalizer. If references to A are passed around, that will imply a reference to B, and B will not be garbage collected because there are external references to the A-B cycle.</p>
<hr>
<p>Further update:</p>
<p>If you want to break the cycle and not require B to explicitly remove the listener, you can use a WeakReference. Something like this:</p>
<pre><code>class A {
void addListener(Listener obj);
void removeListener(Listener obj);
}
class B {
private static class InnerListener implements Listener {
private WeakReference m_owner;
private WeakReference m_source;
InnerListener(B owner, A source) {
m_owner = new WeakReference(owner);
m_source = new WeakReference(source);
}
void listen() {
// Handling reentrancy on this function left as an excercise.
B b = (B)m_owner.get();
if (b == null) {
if (m_source != null) {
A a = (A) m_source.get();
if (a != null) {
a.removeListener(this);
m_source = null;
}
}
return;
}
...
}
}
private A a;
B() {
a = new A();
a.addListener(new InnerListener(this, a));
}
}
</code></pre>
<p>Could be further generalised if needed across multiple classes.</p>
| <p>When the B is garbage collected it should allow the A to be garbage collected as well, and therefore any references in A as well. You don't need to explicitly remove the references in A. </p>
<p>I don't know of any data on whether what you suggest would make the garbage collector run more efficiently, however, and when it's worth the bother, but I'd be interested in seeing it.</p>
| 19,088 |
<p>I was wondering are there any security concerns with adding crossdomain.xml to the root of an application server? Can it be added to any other parts of the server and are you aware of any work arounds that dont require the server to have this file in place?</p>
<p>Thanks
Damien</p>
| <p>By adding the crossdomain.xml, the main security concern is that flash applications can now connect to your server. So if someone logs into your site, and then browses over to another website with a malicious flash app, that flash app can connect back to your site. Since it's in a browser, cookies are shared to the flash app. This allows the flash app to hijack the user's session to do whatever it is your website does without the user knowing about it.</p>
<p>If your flex app is served from the same server, you don't need a crossdomain.xml</p>
<p>You can put it in a sub directory of your site and use System.security.loadSecurityPolicy()</p>
<p><a href="http://livedocs.adobe.com/flex/2/langref/flash/system/Security.html" rel="noreferrer">http://livedocs.adobe.com/flex/2/langref/flash/system/Security.html</a></p>
<p>Applications would then be limited to that tree of your directory structure.</p>
| <p>crossdomain.xml is just a file that has meaning to the Flash runtime; you can restrict what HTTP requests get to see it. You can use web server (e.g. Apache) configuration control to allow read access to it (and only it) from the "root" directory (see previous answers).</p>
<p>You might filter by other headers in the request, etc.</p>
<p>Cheers</p>
| 12,690 |
<p>I apologize in advance for the long post...</p>
<p>I used to be able to build our VC++ solutions (we're on VS 2008) when we listed the STLPort include and library directories under VS Menu > Tools > Options > VC++ Directories > Directories for Include and Library files. However, we wanted to transition to a build process that totally relies on .vcproj and .sln files. These can be checked into source control unlike VS Options which have to be configured on each development PC separately. We handled the transition for most libraries by adding the Include directories to each Project's Property Pages > Configuration Properties > C/C++ > General > Additional Include Directories, and Library directories to Linker > General > Additional Library Directories.</p>
<p>Unfortunately, this approach doesn't work for STLPort. We get LNK2019 and LNK2001 errors during linking:</p>
<pre><code>Error 1 error LNK2019: unresolved external symbol "public: virtual bool __thiscall MyClass::myFunction(class stlp_std::basic_istream<char,class stlp_std::char_traits<char> > &,class MyOtherClass &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > &)const " (?myFunction@MyClass@@UBE_NAAV?$basic_istream@DV?$char_traits@D@stlp_std@@@stlp_std@@AAVSbprobScenarioData@@AAV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@3@@Z) referenced in function _main MyLibrary.obj
Error 5 error LNK2001: unresolved external symbol "public: static void __cdecl MyClass::myFunction(class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,long,enum MyClass::MessageType,int,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &)" (?myFunction@MyClass@@SAXABV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@stlp_std@@000JW4MessageType@1@H0@Z) MyLibrary.lib
</code></pre>
<p>This happens while linking and executable project to dependencies which are library projects. Curiously, this does not happen while linking the library projects themselves. Any ideas?</p>
| <p>Raymond Chen recently talked about this at <a href="http://blogs.msdn.com/oldnewthing/archive/2008/12/29/9255240.aspx" rel="nofollow noreferrer">The Old New Thing</a>-- one cause of these problems is that the library was compiled with one set of switches, but your app is using a different set. What you have to do is:</p>
<p>Get the exact symbol that the linker is looking for. It will be a horrible mangled name.
Use a hex editor (IIRC, Visual Studio will do this) to look at the .lib file you're linking to.
Find the symbol that's almost the thing the linker is looking for, but not quite.
Given the differences in the symbols, try to figure out what command line switches will help.
Good luck -- for people who aren't used to this sort of problem, the solution can take days to figure out (!)</p>
| <p>This is a link error. It doesn't have to do with your include paths.</p>
<p>You either forgot to add MyClass.cpp to your project, or forgot to define those two functions.</p>
<p>The reason the error doesn't happen when "linking" library projects is that library projects are not linked. They are simply a bunch of OBJs that are put together by the LIB program into a library file.</p>
| 32,677 |
<p>I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.</p>
<p>To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.</p>
<pre><code><ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" />
</code></pre>
<p>Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.</p>
<p>Anyone know how to make this work?</p>
| <p>We use "linked" files in project.
Solution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_button -> Add As Link</p>
<p>Then the selected file ( AssemblyInfo.cs for now ) is not copied to the direcotry of project, bud is only linked from specified path.</p>
| <p>We use "linked" files in project.
Solution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_button -> Add As Link</p>
<p>Then the selected file ( AssemblyInfo.cs for now ) is not copied to the direcotry of project, bud is only linked from specified path.</p>
| 14,153 |
<p>I've created a login submit form in HTML but for some reason user/password autocompletion does not work like I expect in firefox.</p>
<p>This is what happens in Firefox:</p>
<ul>
<li>I give username and password and click on the login button</li>
<li>Firefox prompts me if I would like to remember the password. I press 'remember' and login works. (I made sure I deleted all remembered passwords before running this test)</li>
<li>I log out and return to the login page. I would expect the username and password field to be prefilled but that is not the case (if FF has stored only one user/pw combi for a specific URL than it automatically prefills this combi in your form)</li>
</ul>
<p>Notice that I don't (want to) use cookies. I verified in FF password manager that username and password had actually been stored (they were)</p>
<p>Here's the code for this page:</p>
<pre><code><form name="login_form" id="login_form" autocomplete="ON" onsubmit="javascript:xajax_action_login(document.getElementById('user_name').value, document.getElementById('password').value); return false;">
<div class="login_line">
<div class="login_line_left">name</div>
<div id="user_name_id" class="login_line_right"><input size="16" maxlength="16" name="user_name" id="user_name" type="text"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left">password</div>
<div id="password_id" class="login_line_right"><input size="16" maxlength="16" name="password" id="password" type="password"></div>
</div> <!-- login_line -->
<div class="login_line">
<div class="login_line_left"> </div>
<div class="login_line_right"><input class="button" value="login" type="submit">
</div> <!-- login_line -->
</form> <!-- login_form -->
</code></pre>
<p>What is wrong with my code? How can I get autocompletion to work in FF with my code?</p>
<p>Autocompletion does work correct with for instance gmail. Each time I visit the login page of gmail, the email and password fields are correctly prefilled. I don't use the 'remember me on this computer' checkbox so no cookies are used.</p>
<p>I would greatly appriciate your help.
Jasper</p>
<p><strong>Update</strong><br>
Autocomplete is enabled in firefox. I want to stay IE compatible.</p>
| <p>I found out why it doesn't work. I use ajax to paste the example html in a container div. Apperently firefox is very sensitive about this because (as mentioned before) my code does work in IE.</p>
| <p>First, check to see if autocomplete is enabled in firefox.<br />
Then try setting the 'type' attribute of the text box to be 'autocomplete'. Details are given <a href="https://developer.mozilla.org/en/XUL/textbox_(Firefox_autocomplete)" rel="nofollow noreferrer">here</a></p>
| 42,442 |
<p>What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?</p>
<p>Query 1:</p>
<pre><code>SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
</code></pre>
<p>Query 2:</p>
<pre><code>SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
</code></pre>
| <p>Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those.</p>
| <p>I agree, it's sounding a bit too much like Homework!</p>
<p>If it isn't homework then I guess the simplest answer is readability.</p>
<p>As stated before, both queries will produce the same execution plan. If this is the case then the only thing you need to worry about it maintainability.</p>
| 10,558 |
<p>My side question is there really any difference between tinyblob & tinytext? </p>
<p>Buy my real question is what reason, if any, would I choose varchar(255) over tinyblob or tinytext? </p>
| <p>Primarily <a href="http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html" rel="noreferrer">storage requirements</a> and memory handling/speed:</p>
<blockquote>
<p>In the following table, <code>M</code> represents the declared column length in characters for nonbinary string types and bytes for binary string types. <code>L</code> represents the actual length in bytes of a given string value.</p>
<p>VARCHAR(<code>M</code>), VARBINARY(<code>M</code>):<br>
<code>L</code> + 1
bytes if column values require 0 – 255
bytes,<br>
<code>L</code> + 2 bytes if values may
require more than 255 bytes </p>
<p>TINYBLOB, TINYTEXT:<br>
<code>L</code> + 1 bytes, where <code>L</code> < 2<sup>8</sup></p>
</blockquote>
<p>Additionally, see <a href="http://markmail.org/message/u5rl7bhx64jsom2l" rel="noreferrer">this</a> post:</p>
<blockquote>
<p>For each table in use, MySQL allocates
memory for 4 rows. For each of these
rows CHAR(X)/VARCHAR(X) column takes
up the X characters.</p>
<p>A TEXT/BLOB on the other hand is
represented by a 8 byte pointer + a
1-4 byte length (depending on the
BLOB/TEXT type). The BLOB/TEXT is
allocated dynamicly on use. This will
use less memory, but in some cases it
may fragment your memory in the long
run.</p>
</blockquote>
<p><strong>Edit</strong>: As an aside, blobs store binary data and text stores ASCII, thats the only difference between TINYBLOB and TINYTEXT.</p>
| <p>You can't apply CHARACTER SET to TINYTEXT, but you can to VARCHAR(255)</p>
| 17,364 |
<p>So, if i have:</p>
<pre><code>public class Sedan : Car
{
/// ...
}
public class Car : Vehicle, ITurn
{
[MyCustomAttribute(1)]
public int TurningRadius { get; set; }
}
public abstract class Vehicle : ITurn
{
[MyCustomAttribute(2)]
public int TurningRadius { get; set; }
}
public interface ITurn
{
[MyCustomAttribute(3)]
int TurningRadius { get; set; }
}
</code></pre>
<p>What magic can I use to do something like:</p>
<pre><code>[Test]
public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
var property = typeof(Sedan).GetProperty("TurningRadius");
var attributes = SomeMagic(property);
Assert.AreEqual(attributes.Count, 3);
}
</code></pre>
<hr>
<p>Both </p>
<pre><code>property.GetCustomAttributes(true);
</code></pre>
<p>And</p>
<pre><code>Attribute.GetCustomAttributes(property, true);
</code></pre>
<p>Only return 1 attribute. The instance is the one built with MyCustomAttribute(1). This doesn't seem to work as expected.</p>
| <pre><code>object[] SomeMagic (PropertyInfo property)
{
return property.GetCustomAttributes(true);
}
</code></pre>
<p>UPDATE:</p>
<p>Since my above answer doesn't work why not to try something like this:</p>
<pre><code>public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
Assert.AreEqual(checkAttributeCount (typeof (Sedan), "TurningRadious"), 3);
}
int checkAttributeCount (Type type, string propertyName)
{
var attributesCount = 0;
attributesCount += countAttributes (type, propertyName);
while (type.BaseType != null)
{
type = type.BaseType;
attributesCount += countAttributes (type, propertyName);
}
foreach (var i in type.GetInterfaces ())
attributesCount += countAttributes (type, propertyName);
return attributesCount;
}
int countAttributes (Type t, string propertyName)
{
var property = t.GetProperty (propertyName);
if (property == null)
return 0;
return (property.GetCustomAttributes (false).Length);
}
</code></pre>
| <pre><code>object[] SomeMagic (PropertyInfo property)
{
return property.GetCustomAttributes(true);
}
</code></pre>
<p>UPDATE:</p>
<p>Since my above answer doesn't work why not to try something like this:</p>
<pre><code>public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
Assert.AreEqual(checkAttributeCount (typeof (Sedan), "TurningRadious"), 3);
}
int checkAttributeCount (Type type, string propertyName)
{
var attributesCount = 0;
attributesCount += countAttributes (type, propertyName);
while (type.BaseType != null)
{
type = type.BaseType;
attributesCount += countAttributes (type, propertyName);
}
foreach (var i in type.GetInterfaces ())
attributesCount += countAttributes (type, propertyName);
return attributesCount;
}
int countAttributes (Type t, string propertyName)
{
var property = t.GetProperty (propertyName);
if (property == null)
return 0;
return (property.GetCustomAttributes (false).Length);
}
</code></pre>
| 34,438 |
<p>I'm trying to consume a SOAP webservice from an Adobe Flex 3 application, but the server tell me "Invalid SOAP Envelope. SOAP Body does not contain a message nor a fault". I already wrote other test clients (with both Delphi and C#) and I'm sure it's all ok on the server side, so I need to examine the SOAP envelope Flex is sending out to the server. How to do that? I think it should be some event to listen (in the BaseSys class?) to get the envelope before it will be sent.</p>
| <p>thanks for your replies but the problem was the status code 500 (<a href="http://bugs.adobe.com/jira/browse/SDK-14803" rel="nofollow noreferrer">flex can handle code 200 only</a>)</p>
| <p>The easiest way is to run a proxy. Paros is an easy one, written in Java, and therefore multi-platform by nature : <a href="http://www.parosproxy.org/index.shtml" rel="nofollow noreferrer">http://www.parosproxy.org/index.shtml</a></p>
<p>Also, if you do not use it already, you should install firebug : <a href="https://addons.mozilla.org/fr/firefox/addon/1843" rel="nofollow noreferrer">https://addons.mozilla.org/fr/firefox/addon/1843</a></p>
<p>The network monitoring tab should fit your needs.</p>
| 17,859 |
<p>I like to keep my websites extremely light and fast, but of course I need some kind of user tracking and analytics. </p>
<p>It seems like Google Analytics always takes significant enough processing time that I'd like to replace it with something faster (and/or hosted locally), perhaps having less features. </p>
<p>I really only care about these metrics: browser, OS, referrer, and # hits per page on a given day or week. </p>
<p>Does anyone have any good suggestions, or is Google Analytics really the best option?</p>
| <p>It may be the load time that is the main delay. Try hosting the google analytics javascript file locally.</p>
| <p>You can simply get hold of your logs and analyse them with a tool such as WebLog Expert Lite to get those metrics.</p>
| 27,096 |
<p>Are there any known issues around how many "pages" are in an ASP.NET project?</p>
<p>Does the size of the DLL created by the project matter at all?</p>
<p>My existing project is about 150 pages and the DLL is only around 3MB but it has increased from about 50 pages and 0.5 MB recently</p>
| <p><a href="http://www.hanselman.com/blog/WhatsTheUpperLimitOnTheNumberOfProjectsWithinVS2005.aspx" rel="nofollow noreferrer">Scott Hanselman</a> got on the subject two years ago.</p>
<p>The absolute limit is your system memory. The bigger the project the more memory it will use.</p>
<p>Surely you can stay in a [50-200] projects in a solution.</p>
<p>If you find your Visual Studio taking more than memory than expected start thinking about breaking your projects up. </p>
<p>In my opinion the best thing to do is to make the project size a design requirement.</p>
<p><strong>EDIT</strong> : I'm not really answering to your question. To make it clear. The more elements (Pages, projects, image, references, etc.) you have in your VS2003, VS2005 or VS2008 solution the more Visual Studio will take on memory.</p>
| <p>I haven't run into any issues with sites up to hundreds of pages in size. How big of a site are we talking about? Are there built-in redundancies between pages which can be resolved by having a single page take parameters?</p>
| 19,794 |
<p>I'm trying to pass a null value for the first parameter in the code below, but MySQL complains that </p>
<pre>
Incorrect number of arguments for PROCEDURE myProc; expected 2, got 1
</pre>
<p>When I manually call the procedure with the first argument as null, it works, but when <code>EmptyAsNullStartsWith(employeeNumberText.Text)</code> returns null, it complains. </p>
<pre><code>Database db = DatabaseFactory.CreateDatabase(
ConfigurationManager.AppSettings["dbType"]
);
DbCommand cmd = db.GetStoredProcCommand("staff_listforinquiry");
db.AddeParameter(
cmd,
"in_employeeNumber",
DbType.String,
EmptyAsNullStartsWith(employeeNumberText.Text)
);
db.AddeParameter(
cmd,
"in_name",
DbType.String,
EmptyAsNullContains(employeeNameText.Text)
);
</code></pre>
| <p>Did you try having EmptyAsNullContains(employeeNameText.Text) return DBNull instead of regular null?</p>
| <pre><code>if(employeeNumberText.Text != "")
db.AddInParameter(dbCommand, "in_employeeNumber", DbType.String, employeeNumberText.Text);
else
db.AddInParameter(dbCommand, "in_employeeNumber", DbType.String, DBNull.Value);
</code></pre>
| 36,588 |
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p>
<p>I would also like to avoid using the .*? notation if possible. </p>
<p>The text is </p>
<pre><code>foo
<!--[if IE]>
<style type="text/css">
ul.menu ul li{
font-size: 10px;
font-weight:normal;
padding-top:0px;
}
</style>
<![endif]-->
bar
</code></pre>
<p>and I want to remove everything in <code><!--[if IE]></code> and <code><![endif]--></code></p>
<p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p>
<p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p>
<p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p>
<pre><code><!--[if lt IE 7.]>
<script defer type="text/javascript" src="pngfix_253168.js"></script><!--png fix for IE-->
<![endif]-->
</code></pre>
<p>Notice the <code><!--png fix for IE--></code> comment?</p>
<p>Though my problem was solve, I would love to get a regex solution for this.</p>
| <pre><code>>>> from BeautifulSoup import BeautifulSoup, Comment
>>> html = '<html><!--[if IE]> bloo blee<![endif]--></html>'
>>> soup = BeautifulSoup(html)
>>> comments = soup.findAll(text=lambda text:isinstance(text, Comment)
and text.find('if') != -1) #This is one line, of course
>>> [comment.extract() for comment in comments]
[u'[if IE]> bloo blee<![endif]']
>>> print soup.prettify()
<html>
</html>
>>>
</code></pre>
<p>python 3 with bf4:</p>
<pre><code>from bs4 import BeautifulSoup, Comment
html = '<html><!--[if IE]> bloo blee<![endif]--></html>'
soup = BeautifulSoup(html, "html.parser")
comments = soup.findAll(text=lambda text:isinstance(text, Comment)
and text.find('if') != -1) #This is one line, of course
[comment.extract() for comment in comments]
[u'[if IE]> bloo blee<![endif]']
print (soup.prettify())
</code></pre>
<p>If your data gets BeautifulSoup confused, you can <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%20Regexps" rel="nofollow noreferrer">fix</a> it before hand or <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser" rel="nofollow noreferrer">customize</a> the parser, among other solutions.</p>
<p>EDIT: Per your comment, you just modify the lambda passed to findAll as you need (I modified it)</p>
| <p>Don't use a regular expression for this. You will get confused about comments containing opening tags and what not, and do the wrong thing. HTML isn't regular, and trying to modify it with a single regular expression will fail.</p>
<p>Use a HTML parser for this. BeautifulSoup is a good, easy, flexible and sturdy one that is able to handle real-world (meaning hopelessly broken) HTML. With it you can just look up all comment nodes, examine their content (you can use a regular expression for <em>that</em>, if you wish) and remove them if they need to be removed.</p>
| 16,066 |
<p>I have a number of RGBA pixels, each of them has an alpha component.</p>
<p>So I have a list of pixels: (<em>p0 p1 p2 p3 p4 ... pn</em>) where p_0_ is the front pixel and p_n_ is the farthest (at the back).</p>
<p>The last (or any) pixel is not necessary opaque, so the resulting blended pixel can be somehow transparent also.
I'm blending from the beginning of the list to the end, not vice-versa (yes, it is raytracing). So if the result at any moment becomes opaque enough I can stop with correct enough result.
I'll apply the blending algorithm in this way: ((((<em>p0</em> @ <em>p1</em>) @ <em>p2</em>) @ <em>p3</em>) ... )</p>
<p>Can anyone suggest me a correct blending formula not only for R, G and B, but for A component also?</p>
<p><strong>UPD</strong>: I wonder how is it possible that for determined process of blending colors we can have many formulas? Is it some kind of aproximation? This looks crazy, as for me: formulas are not so different that we really gain efficiency or optimization. Can anyone clarify this?</p>
| <p>Alpha-blending is one of those topics that has more depth than you might think. It depends on what the alpha value means in your system, and if you guess wrong, then you'll end up with results that look kind of okay, but that display weird artifacts.</p>
<p>Check out Porter and Duff's classic paper "<a href="http://keithp.com/~keithp/porterduff/p253-porter.pdf" rel="noreferrer">Compositing Digital Images</a>" for a great, readable discussion and all the formulas. You probably want the "over" operator.</p>
<p>It sounds like you're doing something closer to volume rendering. For a formula and references, see the <a href="http://www.faqs.org/faqs/graphics/algorithms-faq/" rel="noreferrer">Graphics FAQ</a>, question 5.16 "How do I perform volume rendering?". </p>
| <p>There are various possible ways of doing this, depending on how the RGBA values actually represent the properties of the materials.</p>
<p>Here's a possible algorithm. Start with final pixel colours <code>lightr=lightg=lightb=0</code>, <code>lightleft=1</code>;</p>
<p>For each r,g,b,a pixel encountered evaluate:</p>
<pre><code>lightr += lightleft*r*(1-a)
lightg += lightleft*g*(1-a)
lightb += lightleft*b*(1-a)
lightleft *= 1-a;
</code></pre>
<p>(The RGBA values are normalised between 0 and 1, and I'm assuming that a=1 means opaque, a=0 means wholly transparent)</p>
<p>If the first pixel encountered is blue with opacity 50%, then 50% of the available colour is set to blue, and the rest unknown. If a red pixel with opacity 50% is next, then 25% of the <em>remaining</em> light is set to red, so the pixel has 50% blue, 25% red. If a green pixel with opacity 60% is next, then the pixel is 50% blue, 25% red, 15% green, with 10% of the light remaining.</p>
<p>The physical materials that correspond to this function are light-emitting but partially opaque materials: thus, a pixel in the middle of the stack can never darken the final colour: it can only prevent light behind it from increasing the final colour (by being black and fully opaque).</p>
| 18,615 |
<p>One simple method I've used in the past is basically just creating a second table whose structure mirrors the one I want to audit, and then create an update/delete trigger on the main table. Before a record is updated/deleted, the current state is saved to the audit table via the trigger.</p>
<p>While effective, the data in the audit table is not the most useful or simple to report off of. I'm wondering if anyone has a better method for auditing data changes?</p>
<p>There shouldn't be too many updates of these records, but it is highly sensitive information, so it is important to the customer that all changes are audited and easily reported on.</p>
| <p>How much writing vs. reading of this table(s) do you expect?</p>
<p>I've used a single audit table, with columns for Table, Column, OldValue, NewValue, User, and ChangeDateTime - generic enough to work with any other changes in the DB, and while a LOT of data got written to that table, reports on that data were sparse enough that they could be run at low-use periods of the day.</p>
<p><strong>Added:</strong>
If the amount of data vs. reporting is a concern, the audit table could be replicated to a read-only database server, allowing you to run reports whenever necessary without bogging down the master server from doing their work.</p>
| <p>Are there any built-in audit packages? Oracle has a nice package, which will even send audit changes off to a separate server outside the access of any bad guy who is modifying the SQL.</p>
<p>Their example is awesome... it shows how to alert on anybody modifying the audit tables.</p>
| 2,587 |
<p>I'm writing a mapping application that I am writing in python and I need to get the lat/lon centroid of N points.
Say I have two locations</p>
<pre><code>a.lat = 101
a.lon = 230
b.lat = 146
b.lon = 200
</code></pre>
<p>Getting the center of two points is fairly easy using a euclidean formula. I would like
to be able to do it for more then two points.</p>
<p>Fundamentally I'm looking to do something like <a href="http://a.placebetween.us/" rel="noreferrer">http://a.placebetween.us/</a> where one can enter multiple addresses and find a the spot that is equidistant for everyone.</p>
| <p>Have a look at the pdf document linked below. It explains how to apply <a href="https://stackoverflow.com/questions/353684/determine-the-centroid-of-multiple-points#353718">the plane figure algorithm that Bill the Lizard</a> mentions, but on the surface of a sphere.</p>
<p><a href="http://img51.imageshack.us/img51/4093/centroidspostersummary.jpg" rel="nofollow noreferrer">poster thumbnail and some details http://img51.imageshack.us/img51/4093/centroidspostersummary.jpg</a><br>
Source: <a href="http://www.jennessent.com/arcgis/shapes_poster.htm" rel="nofollow noreferrer">http://www.jennessent.com/arcgis/shapes_poster.htm</a><br>
There is also a <a href="http://www.jennessent.com/downloads/graphics_shapes_poster_full.pdf" rel="nofollow noreferrer">25 MB full-size PDF</a> available for download.<br>
Credit goes to <a href="https://stackoverflow.com/users/6109/mixdev">mixdev</a> for finding the link to the original source, and of course to Jenness Enterprises for making the information available. Note: I am in no way affiliated with the author of this material.</p>
| <p>Separately average the latitudes and longitudes.</p>
| 46,071 |
<p>I have div containing a list of flash objects. The list is long so I've set the div height to 400 and overflow to auto. </p>
<p>This works fine on FF but on IE6 only the first 5 flash objects that are visible work. The rest of the flash objects that are initially outside the viewable area are empty when I scroll down. The swfs are loaded ok because I don't get the "movie not loaded". They also seem to be embedded correctly they are just empty ie. the content is never drawn.</p>
<p>Any ideas on how to fix this?</p>
<p>ps. The html elements involved are mainly floating in case that has an impact on this. The flash objects are embedded using the popular swfObject.</p>
<p>EDIT: It seems that the bug only occurs with the flash plugin "WIN 8,0,24,0" </p>
<p>Since I cant post a link I'll summarize the relevant code here:</p>
<pre><code><div style="overflow:auto; height:400px; float:left;">
<div id="item_1" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
...
<div id="item_7" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
</div>
</code></pre>
<p>EDIT:
After trying to recreate this problem in a separate page I found that the bug is some how related to the flash objects being hidden initially. My container div has "display:none; visibility:hidden" when page is loaded. Later on the style is changed via javascript to visible. If I load the page so that everything is visible from the start all is fine.</p>
| <p>You should probably create a VIEW which limits the records and then apply the proper rights on the view. </p>
| <p><p>I have my first draft. It goes like that:
<p>The app is a Project Management/Issue Tracking/Event Management/Collaboration Web app.
<p>I created a Role "External User". By default a user in that role </p>
<ul>
<li>can SELECT FROM Persons
<li>can SELECT FROM Units (organizational units-companies-depts etc)
<li>can SELECT Projects assigned to him
<li>can SELECT Tasks assigned to him
<li>can not SELECT any other Projects & Tasks
</ul>
<p><p>The administrator can create a user group "External Partner" and assign to that some Projects and Products (with Issues)
<p>The members of this group can SELECT the assigned Objects.</p>
<p><p>It is a complicated solution, but the only one that solves my customers problem (they don't want external partners to have access to all their project database).</p>
| 27,234 |
<p>Do you primarily think of reasons TO implement it, or reasons NOT TO implement it? What are the advantages of each?</p>
| <p>I think first about the stakeholder (the client).<br>
Will that feature help <em>him</em> ? Is it indeed a functional feature that brings value?</p>
<p>Then I think about technical implications and the resulting complexity, in order to evaluate the trade off between implementation cost vs. not having that feature.</p>
<p>Based on those two first elements of reflexions, I can begin to know if I must implement it or not. </p>
<p>I guess there is no clear cut between reasons to or not not implement it.</p>
| <p>The customer gets to decide on features. If I think of something I run it by the customer. Together we figure out how to get the customer's most important features implemented soonest.</p>
| 29,183 |
<p>Does anyone know how to use the credential cache or network credential to get the user's personal info from the Active Directory using C# or VB? I need to get personal info such as name, telephone ID and so on.</p>
| <p>See the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx" rel="nofollow noreferrer">System.DirectoryServices class documentation</a>.</p>
| <pre><code>DirectorySearcher ds = new DirectorySearcher("LDAP://DC=test,dc=com");
ds.Filter = String.Format("&(samaccountname={0})(objectcategory=user)",Environment.Username);
ds.PropertiesToLoad.Add("telephoneNumber");
ds.PropertiesToLoad.Add("Name");
// add all properties here
DirectoryEntry de = ds.FindOne();
</code></pre>
<p>By default a user will have sufficent rights to read their own personal details.<br>
If they do not you may need to use Delegation on your directory to allow SELF read access to extra attributes</p>
| 21,477 |
<p>I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?</p>
| <p>Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.</p>
<ul>
<li><p><strong>Proxy</strong> could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.</p></li>
<li><p><strong>Decorator</strong> is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.</p></li>
<li><p><strong>Adapter</strong> is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.</p></li>
<li><p><strong>Bridge</strong> is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.</p></li>
<li><p><strong>Facade</strong> is a higher-level (read: simpler) interface to a subsystem of one or more classes. Suppose you have a complex concept that requires multiple objects to represent. Making changes to that set of objects is confusing, because you don't always know which object has the method you need to call. That's the time to write a Facade that provides high-level methods for all the complex operations you can do to the collection of objects. Example: a Domain Model for a school section, with methods like <code>countStudents()</code>, <code>reportAttendance()</code>, <code>assignSubstituteTeacher()</code>, and so on.</p></li>
</ul>
| <p>Design pattern is not mathematics, it is combination of art and software engineering. There is nothing like for this requirment you have to use proxy, bridge etc. Design patterns are created to solve the problems. If you anticipate a design problem, then use it. Based on experience, you will come to know for specific problem, which pattern to use. If you are good in solid design principles, you would have implemented design pattern without knowing it is pattern. Common example is statergy and factory patterns</p>
<p>Hence concentrate more on solid desighn principles, clean coding principles and ttd</p>
| 45,611 |
<p>I'm building a project along with a Dll.</p>
<p>The Dll must support native code so I declared it as a /clr.
My project was initialy also a /clr project and everything was fine. However I'd like to include some NUnit testing so I had to switch my main project from /clr to /clr:pure.</p>
<p>Everything still compiles but any Dll call generates a runtime error. When I revert back to /clr everything is ok</p>
<p>In my Dll, exported functions are declared as follow : </p>
<pre><code>#define DllExport __declspec( dllexport )
DllExport bool DisplayScan(bool bShow, bool bAllPasses) { }
</code></pre>
<p>I also made a .def file containing the real names of all the exported functions</p>
<pre><code>LIBRARY "Controller"
EXPORTS
DisplayScan
</code></pre>
<p>From my main project my imports are declared as follow :</p>
<pre><code>#define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static
_DllImport bool DisplayScan(bool bShow, bool bAllPasses)
</code></pre>
<p>Anyone ever encountered such a problem?</p>
| <p>Ok everything is working now</p>
<p>In fact, it has been working from the beginning.</p>
<p>Moral : don't try to cast a char* into a std::string </p>
<p>Weird thing : its ok in /clr until you return from the function. It crashes right away in /clr:pure</p>
| <p>your problem is calling conventionCallingConvention = CallingConvention::Cdecl ... define your function like that or use stdcall or clrcall, clecl is for pure C</p>
<p>or problem is here:
define that function extern not static</p>
| 37,189 |
<p>I have started making a database and I have an 'ordered item' and a 'invoice' table. I would like to find out how I would add up the prices of the items that the customer picks. As well where abouts do you put this 'rule' on the database. </p>
| <p>You want the SQL "Sum()" function. Look, for example, <a href="http://www.techonthenet.com/access/functions/numeric/sum.php" rel="noreferrer">here</a>.</p>
| <p>Basically you would make a query and populate the invoice table with the results of that query. As Coderer said, use a sum() function. If you are using the graphical query editor you will need to enable totals (View->Totals) and then set the total type to "Sum" instead of the default "Group By"</p>
| 28,537 |
<p>When I asked <a href="https://stackoverflow.com/questions/167575/should-a-project-manager-enforce-coding-standards">this question</a> I got almost always a definite yes you should have coding standards. </p>
<p>What was the strangest coding standard rule that you were ever forced to follow?</p>
<p>And by strangest I mean funniest, or worst, or just plain odd. </p>
<p>In each answer, please mention which language, what your team size was, and which ill effects it caused you and your team.</p>
| <p>I <em>hate</em> it when the use of multiple returns is banned.</p>
| <p>Postfixing _ to member variables. e.g.</p>
<pre><code>int numberofCycles_;
</code></pre>
<p>This was in C++ on an open source project with a couple of developers. The main side effect was not knowing that a variable had class scope until getting to the end of the name. Not something I had thought much about before, but clearly backwards.</p>
| 26,834 |
<p>Anyone knows if is possible to have partial class definition on C++ ?</p>
<p>Something like:</p>
<p>file1.h:</p>
<pre>
class Test {
public:
int test1();
};
</pre>
<p>file2.h: </p>
<pre>
class Test {
public:
int test2();
};
</pre>
<p>For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.</p>
<p>I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. </p>
<p>Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:</p>
<pre>
class genericTest {
public:
int genericMethod();
};
</pre>
<p>Then let's say for win32:</p>
<pre>
class win32Test: public genericTest {
public:
int win32Method();
};
</pre>
<p>And maybe:</p>
<pre>
class macTest: public genericTest {
public:
int macMethod();
};
</pre>
<p>Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:</p>
<pre>
#ifdef _WIN32
genericTest *test = new win32Test();
#elif MAC
genericTest *test = new macTest();
#endif
test->genericMethod();
</pre>
<p>Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.</p>
<p>That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.</p>
| <p>This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.</p>
| <p>Declaring a class body twice will likely generate a type redefinition error. If you're looking for a work around. I'd suggest #ifdef'ing, or using an <a href="http://en.wikipedia.org/wiki/Abstract_base_class" rel="nofollow noreferrer">Abstract Base Class</a> to hide platform specific details.</p>
| 17,027 |
<p>I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this:</p>
<pre><code><assignee-id type="integer">38628</assignee-id>
</code></pre>
<p>it can also look like this:</p>
<pre><code><assignee-id type="integer" nil="true"></assignee-id>
</code></pre>
<p>Now, in my class I have the following property that should receive the data:</p>
<pre><code>[XmlElementAttribute("assignee-id")]
public int AssigneeId { get; set; }
</code></pre>
<p>This works fine for the first xml element example, but the second fails. I've tried changing the property type to be int? but this doesn't help. I'll need to serialize it back to that same xml format at some point too, but I'm trying to use the built in serialization support without having to resort to rolling my own. </p>
<p>Does anyone have experience with this kind of problem?</p>
| <p>It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace.</p>
<p>What you could do is process these with XSLT to turn this:</p>
<pre><code><assignees>
<assignee>
<assignee-id type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id type="integer" nil="true"></assignee-id>
</assignee>
</assignees>
</code></pre>
<p>into this:</p>
<pre><code><assignees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<assignee>
<assignee-id xsi:type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id xsi:type="integer" xsi:nil="true" />
</assignee>
</assignees>
</code></pre>
<p>This would then be handled correctly by the XmlSerializer without needing any custom code. The XSLT for this is rather trivial, and a fun exercise. Start with one of the many "copy" XSLT samples and simply add a template for the "type" and "nil" attributes to ouput a namespaced attribute.</p>
<p>If you prefer you could load your XML document into memory and change the attributes but this is not a good idea as the XSLT engine is tuned for performance and can process quite large files without loading them entirely into memory.</p>
| <p>XmlSerializer uses xsi:nil - so I expect you'd need to do custom IXmlSerializable serialization for this. Sorry.</p>
| 23,487 |
<p>I am just starting out with DI & unit testing and have hit a snag which I am sure is a no brainer for those more experienced devs :</p>
<p>I have a class called MessageManager which receives data and saves it to a db. Within the same assembly (project in Visual Studio) I have created a repository interface with all the methods needed to access the db.
The concrete implementation of this interface is in a separate assembly called DataAccess.</p>
<p>So DataAccess needs a project reference to MessageManager to know about the repository interface.
And MessageManager needs a project reference to DataAccess so that the client of MessageManager can inject a concrete implementation of the repository interface.
This is of courser not allowed</p>
<p>I could move the interface into the data access assembly but I believe the repository interface is meant to reside in the same assembly as the client that uses it</p>
<p>So what have I done wrong?</p>
| <p>You only have two choices: add an assembly to hold the interface or move the interface into the DataAccess assembly. Even if you're developing an architecture where the DataAccess class may someday be replaced by another implementor (even in another assembly) of the repository interface, there's no reason to exclude it from the DataAccess assembly.</p>
| <p>You could leave the structure as you currently have it (without the dependency from MessageManager to DataAccess that causes the problem) and then have <code>MessageManager</code> dynamically load the concrete implementation required at runtime using the <code>System.Reflection.Assembly</code> class.</p>
| 11,538 |
<p>What's the most common way to deal with a series of block elements that need to be on a line (if javascript needs to be able to modify their widths, for example)? What are the pros and cons to applying float:left to each of them vs. using positioning to place them?</p>
| <p>Floating would be my choice, but it really depends on what you wish to achieve. If you can provide a more specific example I would be able to give you a clear reason as to what and why I think you should use. However here is a brief set of pros and cons that I have come accross (I'm assuming that by positioning you mean absolute positioning):</p>
<p>Positioning pros:</p>
<ul>
<li>very precise positioning in relation to the next ancestor marked as position relative - allows for great flexibility</li>
<li>allows for elements to be in a different order visually than they are in the DOM</li>
</ul>
<p>Positioning cons:</p>
<ul>
<li>Harder to line up with other elements since the positioned element is no longer in the document flow and also because of the level of precision required. </li>
<li>Other elements ignore the absolutely positioned element which means you could have a potential overlap, unless you account for the minimum and maximum size of the positioned element</li>
<li>harder to implement a footer if you are using absolute positioning for your columns.</li>
</ul>
<p>Float pros:</p>
<ul>
<li>really easy to construct simple and advanced layouts</li>
<li>no footer problem</li>
<li>no worrying about precision, browser takes care of that for you</li>
<li>parent container stretches</li>
</ul>
<p>Float cons:</p>
<ul>
<li>Lots of pitfalls for those less experienced with float layouts that may lead to many questions being asked on SO :)</li>
</ul>
<p>As to the clear:both element that Sebastian mentioned, There's a simple way around that. Lets say you have a container div and 2 floated divs inside.</p>
<p>Html:</p>
<pre><code><div id="con">
<div class="float"></div>
<div class="float"></div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#con { background:#f0f; }
.float { float:left; width:100px; height:100px; background:#0ff; }
</code></pre>
<p>if you were to run this code you would notice that the container div (the magenta coloured one) is only a single pixel high whereas the floated divs were correct - which is the problem Sebastian mentioned. Now you could take his advice and add a br or float the container which would not be very semantic - so here is a slightly more elegant solution. Just add overflow:hidden; to the container div like so:</p>
<pre><code>#con { background:#f0f; overflow:hidden; }
</code></pre>
<p>Now your container should wrap the floated divs properly.</p>
| <p>Only disadvantage to float in situations like this for me has been that you'll either need to left justify them or right justify them -- centering is not an option. However you've mentioned you're using absolute values for widths, so you could just nest all the floated elements in a DIV element and add either margin-right or margin-left to the parent DIV to simulate center alignment.</p>
| 39,910 |
<p>I'm looking at rewriting an eMbedded Visual Basic app I wrote years ago. I'm unsatisified with it because of various problems clients keep having with it now and then over the years, mostly along the lines of the app not loading anymore because a required dll/activex control has gone missing! This is so frustrating and naturally difficult to debug when a client is using it far away. In alot of cases reinstalling the app doesn't fix the problem.</p>
<p>My preference would be to rewrite it in C# since I'm comfortable with C# and DotNet, but I'm also open to other platforms like blackberry or iTouch/iPhone so long as the platform can support maps and GPS. I'd start rewriting it in C# now but I can't be sure that I won't have the same problems in .net.</p>
<p>Has anyone else had similar problems with eVB apps which have gone away/persisted when moving to CF DotNet? Or would you suggest a different platform again?</p>
<p>Edit: Note that I wish to move away from eVB anyway, but if I move to CF DotNet I want to make sure I won't have the same missing dll/control problems.</p>
| <p>I recommend .NET CF strongly, especially if you already know C# and .NET. Mono has been ported to the iPhone, so it is possible to write apps that will run on Windows Mobile and the iPhone. No Mono for Blackberry (yet, if ever), so that's a definite limitation. I personally can't stand Blackberries (I have both a Blackberry and a WM smartphone and the Blackberry makes me want to hang myself), but they do have a huge user base.</p>
| <p>I suggest you take it one step further and look at Silverlight. One of the premises is that it's a more long-term-stable, portable, lightweight download and install, and it hasn't gotten krufty yet.</p>
<p>I think it has the potential to be the next VB for embedded. One of the difficulties with CF is that I've found it to be an insufficient subset of the real thing.</p>
| 42,387 |
<p>Given the following domain classes:</p>
<pre><code>class Post {
SortedSet tags
static hasMany = [tags: Tag]
}
class Tag {
static belongsTo = Post
static hasMany = [posts: Post]
}
</code></pre>
<p>From my understanding so far, using a <code>hasMany</code> will result in hibernate <code>Set</code> mapping.
However, in order to maintain uniqueness/order, Hibernate needs to load the entire set from the database and compare their hashes.</p>
<p>This could lead to a significant performance problem with adding and deleting posts/tags
if their sets get large. What is the best way to work around this issue?</p>
| <p>There is no order ensured by Hibernate/GORM in the default mapping. Therefore, it doesn't have to load elements from the database in order to do the sorting. You will have your hands on a bunch of ids, but that's that extent of it.</p>
<p>See 19.5.2:
<a href="http://www.hibernate.org/hib_docs/reference/en/html/performance-collections.html" rel="nofollow noreferrer">http://www.hibernate.org/hib_docs/reference/en/html/performance-collections.html</a></p>
<p>In general, Hibernate/GORM is going to have better performance than you expect. Unless and until you can actually prove a real-world performance issue, trust in the framework and don't worry about it.</p>
| <p>The ordering of the set is guaranteed by the <code>Set</code> implementation, ie, the <code>SortedSet</code>. Unless you use a <code>List</code>, which keeps track of indexes on the db, the ordering is server-side only.</p>
<p>If your domain class is in a <code>SortedSet</code>, you have to implement <code>Comparable</code> in order to enable the proper sorting of the set.</p>
<p>The question of performance is not really a question per se. If you want to access a single <code>Tag</code>, you should get it by its <strong>Id</strong>. If you want the sorted tags, well, the sort only makes sense if you are looking at all <code>Tags</code>, not a particular one, so you end up retrieving all <code>Tags</code> at once. Since the sorting is performed server-side and not db-side, there is really not much difference between a <code>SortedSet</code> and a regular <code>HashSet</code> in regards to Db.</p>
| 36,806 |
<p>I've got a unidirectional tree of objects, in which each objects points to its parent. Given an object, I need to obtain its entire subtree of descendants, as a collection of objects. The objects are not actually in any data structure, but I can easily get a collection of all the objects.</p>
<p>The naive approach is to examine each object in the batch, see if the given object is an ancestor, and keep it aside. This would not be too efficient... It carries an overhead of O(N*N), where N is the number of objects.</p>
<p>Another approach is the recursive one, meaning search for the object's direct children and repeat the process for the next level. Unfortunately the tree is unidirectional... there's no direct approach to the children, and this would be only slightly less costly than the previous approach.</p>
<p>My question: Is there an efficient algorithm I'm overlooking here?</p>
<p>Thanks,</p>
<p>Yuval =8-)</p>
| <p>As others have mentioned, build a hashtable/map of objects to a list of their (direct) children.</p>
<p>From there you can easily lookup a list of direct children of your "target object", and then for each object in the list, repeat the process.</p>
<p>Here's how I did it in Java and using generics, with a queue instead of any recursion:</p>
<pre><code>public static Set<Node> findDescendants(List<Node> allNodes, Node thisNode) {
// keep a map of Nodes to a List of that Node's direct children
Map<Node, List<Node>> map = new HashMap<Node, List<Node>>();
// populate the map - this is O(n) since we examine each and every node
// in the list
for (Node n : allNodes) {
Node parent = n.getParent();
if (parent != null) {
List<Node> children = map.get(parent);
if (children == null) {
// instantiate list
children = new ArrayList<Node>();
map.put(parent, children);
}
children.add(n);
}
}
// now, create a collection of thisNode's children (of all levels)
Set<Node> allChildren = new HashSet<Node>();
// keep a "queue" of nodes to look at
List<Node> nodesToExamine = new ArrayList<Node>();
nodesToExamine.add(thisNode);
while (nodesToExamine.isEmpty() == false) {
// pop a node off the queue
Node node = nodesToExamine.remove(0);
List<Node> children = map.get(node);
if (children != null) {
for (Node c : children) {
allChildren.add(c);
nodesToExamine.add(c);
}
}
}
return allChildren;
}
</code></pre>
<p>The expected execution time is something between O(n) and O(2n), if I remember how to calculate that right. You're guaranteed to look at every node in the list, plus a few more operations to find all of the descendants of your node - in the worst case (if you run the algorithm on the root node) you are looking at every node in the list twice.</p>
| <p>Your question is a little abstract, but <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">nested sets</a> (scroll down, might be a little too mysql-specific) might be an option for you. It's extremely fast for read operations, though any modifications are quite complex (and have to modify half the tree on average).</p>
<p>That requires the ability to modify your data structure, though. And I guess if you can modify the structure, you could just as well add references to child objects. If you can't modify the structure, I doubt there's anything faster than your ideas.</p>
| 25,680 |
<p>Previously, settings for deployments of an ASP.NET application were stored in multiple configuration files under the Web.config config sections using a KEY/VALUE format. We are moving these 'site module options' to the database for a variety of reasons. </p>
<p>Here are the two options we are mulling over at the moment:
<br> 1. A single table with the applicationId, moduleId, and key as a Primary Key with a Value field.
<br><strong>Pros:</strong>
<br> - This mimics the file access.
<br> - It is easy to select entire sections to cache in hashtables/value objects.
<br><strong>Cons:</strong>
<br> - More difficult to update since each key needs to be updated individually.
<br> - Must cast each value if it's not a string. </p>
<p><br> 2. Individual tables for each section which separate stored procedures, classes, etc.
<br><strong>Pros:</strong>
<br> - Data is guaranteed to be consistent since the column and object types are typed.
<br> - Updating is done in one trip to the database through an explicit interface.
<br><strong>Cons:</strong>
<br> - Must change the application interface to access the
<br> - Must update the objects, database tables, and stored procedures each time something changes. </p>
<p>Do either of these sound like good ideas or is there another way I may have overlooked? </p>
| <p>If I understand what you are proposing correctly. I would do the first approach. It leverages what you have already built. I would use the hash tables for caching inside of wrapper classes that can provide stongly typed interfaces for the properties.</p>
<p>For example:</p>
<pre><code>/// <summary>
/// The time passwords expire, in days, if ExpirePasswords is on
/// </summary>
public int PasswordExpirationDays {
get { return ParseUtils.ParseInt(this["PasswordExpirationDays"], PW_MAX_AGE);}
set { this["PasswordExpirationDays"] = value.ToString(); }
}
</code></pre>
| <p>Another option is to group like settings together into their own classes, and then use XML serialization/deserialization to store and retrieve instances of these settings classes to and from the database.</p>
<p>This doesn't specifically provide advantages above and beyond a key/value pair other than you don't have to yourself perform any type conversions (this is done behind the scenes as part of the serialization/deserialization process - so it still does happen). I find this sort of approach ideally suited for solving configuration issues such as you are facing. Its clean, quick to implement, very easy to expand, and very easy to test. You don't have to spend time creating a feature rich API to get at your settings, especially if you've already got your configuration subclassed out.</p>
<p>Also in a pinch you can direct your settings to come from database tables or the file system without altering your serialization/deserialization code (this is very nice during development).</p>
<p>Finally if you are using SQL Server (and likely Oracle, though I have no experience with Oracle and XML) and you think about the design of your settings class up front, you can define an XML schema for your serialized configuration object instances so you can use XQuery to quickly get a configuration setting's value without having to fully deserialize.</p>
| 27,085 |
<p>I have a JavaScript request going to a ASP.Net (2.0) HTTP handler which passes the request to a java web service. In this system special characters, such as those with an accent do not get passed on correctly.</p>
<p>E.G.</p>
<ul>
<li>Human input: <code>Düsseldorf</code></li>
<li>becomes a JavaScript asynch request to <code>http://site/serviceproxy.ashx?q=D%FCsseldorf</code>, which is valid in ISO-8859-1 as well as in UTF-8 as far as I can tell. (unless it's %c3%bc in UTF-8)</li>
<li><code>HttpContext.Current.Request.QueryString.Get("q")</code> returns <code>D�sseldorf</code> which is where trouble begins.</li>
<li>but <code>HttpUtility.UrlEncode(HttpContext.Current.Request.QueryString.Get("q"), Encoding.GetEncoding("ISO-8859-1"))</code> returns <code>D%3fsseldorf</code> (a '?')</li>
<li>and <code>HttpUtility.UrlEncode(HttpContext.Current.Request.QueryString.Get("q"), Encoding.UTF8)</code> returns <code>D%ef%bfsseldorf</code></li>
</ul>
<p>So it the value doesn't get decoded nor re-encoded correctly to be passed on to the java service.</p>
<ul>
<li>Notice <code>HttpContext.Current.Request.Url.Query</code> is <code>?q=D%FCsseldorf&output=json&from=1&to=10</code></li>
<li>while <code>HttpContext.Current.Request.QueryString.ToString()</code> is <code>q=D%ufffdsseldorf&output=json&from=1&to=10</code></li>
</ul>
<p>Why is this, and how can I tell the <code>HttpContext</code> to honor the request headers which include:</p>
<pre><code>Content-Type=application/x-www-form-urlencoded;+charset=UTF-8
</code></pre>
<p>and decode the URL's <code>QueryString</code> using the UTF-8 charset.</p>
<p>Addendum: As the answer notes, the trouble lies not so much in the decoding as the encoding; using <code>escape()</code> in JavaScript does not escape according to UTF-8, while using <code>encodeURIComponent()</code> does.</p>
| <p>I don't know what the default character encoding used by your server (IIS?) is, or if it can be changed, but I can tell you a few things that might help.</p>
<p>0xFC is the ISO-8859-1 encoding for ü. While the Unicode code point is U+00FC, when encoded with UTF-8, this requires two bytes, and becomes 0xC3 0xBC.</p>
<p>If a UTF-8 decoder were to see the illegal byte sequence 0xFC, it would decode it as a Unicode "replacement character", U+FFFD, and pick up where it saw the beginning of another valid byte sequence, in this case 's'.</p>
<p>The reason you get <code>%3f</code> is that '?' is the "replacement character" for the Latin character set, similar to � in the Unicode character set.</p>
<p>I believe what you're seeing is the client encoding with ISO-8859-1, but the server is decoding with UTF-8. As soon as it hits the server, your data is corrupted. I recommend that you modify the client to use UTF-8 encoding; it should be requesting <code>http://site/serviceproxy.ashx?q=D%C3%BCsseldorf</code> </p>
<p>It sounds like you are constructing these URLs from JavaScript, so you should use the <code>encodeURI</code> and <code>encodeURIComponent</code> functions, not <code>escape</code>.</p>
| <p>I am getting the same problem with an ASP.NET generic handler when the URL is typed directly into IE8. Characters are being sent through as char 65533, and yet I do have IE8 set to </p>
<pre>[x] Send UTF-8 URLs.</pre>
<p>In my scenario, I'm debugging an HTTP handler in Visual Studio and typing the address of the handler directly into the browser: </p>
<pre> http://localhost/myHandler.ashx?term=xxxxxx</pre>
<p>and then stepping through the code. The client will be passing UTF-8 encoded URLs, but is there a way to debug the code when IE8 running on the development machine is the client?</p>
| 41,253 |
<p>Some of you may recognize this as Project Euler's problem number 11. The one with the grid.</p>
<p>I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why</p>
<pre><code>grid = [
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ],
[ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ],
[ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ],
...
</code></pre>
<p>And I get this error:</p>
<pre>
File "D:\development\Python\ProjectEuler\p11.py", line 3
[ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ],
^ SyntaxError: invalid token
</pre>
<p>Why is it throwing an error before the comma?</p>
| <p>I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.</p>
| <p>Just remove leading zeros.</p>
<p>First zero makes number octal.</p>
| 43,612 |
<p>See the question. I want to see the methods and classes offered by a DLLs library.</p>
| <p>This is exactly what the Object Browser is for.</p>
<ul>
<li>Add a reference to the DLL.</li>
<li>Right click it in the list.</li>
<li>Click <em>View in Object Browser</em>.</li>
</ul>
| <p>In Visual Studio 2022 (and without creating or opening a solution) you can view a DLL's members.</p>
<ol>
<li>Open the Object Browser Tool Window (from the View option in the Main Menu).</li>
<li>In that window it'll probably show a list of .NET components, but near the top there's a browse button (three dots). Click this.</li>
<li>Here you'll add any DLLs you want to create a "Custom Component Set". Once you select and Add your DLL, then click OK.</li>
</ol>
<p>You should see your DLL members in the Object Browser now.</p>
| 16,006 |
<p>I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?</p>
<p>So, given an XQuery method:</p>
<pre><code>define function foo($bar as node()*) as node() {
(: unimportant details :)
}
</code></pre>
<p>I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.</p>
| <p><strong>MarkLogic solutions:</strong></p>
<p>The best way to convert a string into a node is to use:</p>
<pre><code>xdmp:unquote($string).
</code></pre>
<p>Conversely if you want to convert a node into a string you would use: </p>
<pre><code>xdmp:quote($node).
</code></pre>
<p><strong>Language agnostic solutions:</strong> </p>
<p>Node to string is:</p>
<pre><code>fn:string($node)
</code></pre>
| <p>you also can use <code>fn:parse-xml(xs:string)</code> to convert your current valid XML string into a document.</p>
| 14,746 |
<p>I'm writing an app that will need to make use of <code>Timer</code>s, but potentially very many of them. How scalable is the <code>System.Threading.Timer</code> class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a <code>Timer</code>, or does each <code>Timer</code> have its own thread? </p>
<p>I guess another way to rephrase the question is: How is <code>System.Threading.Timer</code> implemented?</p>
| <p>I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: <a href="http://www.codeplex.com/NetMassDownloader" rel="noreferrer">http://www.codeplex.com/NetMassDownloader</a></p>
<p>Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it...</p>
<p>They definitely use pool threads rather than a thread-per-timer, though.</p>
<p>The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list.</p>
<p>Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers.</p>
<p>Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running.</p>
| <p>^^ as DannySmurf says : Consolidate them. Create a timer service and ask that for the timers. It will only need to keep 1 active timer (for the next due call) and a history of all the timer requests and recalculate this on AddTimer() / RemoveTimer().</p>
| 5,154 |
<p>Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.</p>
<p>Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the right JVM installed? Do you have bad experiences using Web Start? If yes, which? What are you recommendations when using Web Start for distributing applications?</p>
| <p>In my company we used Java Web Start to deploy Eclipse RCP applications. It was a pain to setup, but it works very well once in place. So the only recommendation I could make is to start small, to get the hang of it. Deploying one simple application first. Trying to deploy a complete product that is already made without experience with JWS gets complicated rather quickly.</p>
<p>Also, learning how to pass arguments to the JWS application was invaluable for debugging. Setting the Environment variable JAVAWS_VM_ARGS allows setting any arbitrary property to the Java Virtual machine. In my case:</p>
<p>-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=4144</p>
<p>Helpful when you need to check problems during start-up (suspend=y)</p>
<p>I think the main problem for the acceptance of Java Web Start is that it is relatively difficult to setup. Also, somehow there is this dissonance: When you have a desktop application, people expects a installer they can double click. When you have a web application, people expects they can use it right from the browser. Java Web Start is neither here not there...</p>
<p>It is widely used in intranets, though.</p>
| <p>My experience:<br>
I used it ca 2006, intranet application for a bank.</p>
<p>First download was fine,
however when wanting to push out a new version,
the caching of the jar files did not work,
so the new files were not pushed to the client.</p>
<p>Spent a week trying to fix this without success.</p>
| 15,356 |
<p>I have an application that behaves oddly, and just to verify, I'd like to see which security zone it is currently running under.</p>
<p>I've found the System.Security.SecurityZone enum, but can't seem to find anything that will return which of these I'm running under.</p>
<p>Does anyone have any tips?</p>
<p>Basically I want to find out if my application is running in MyComputer, Intranet, Internet, Untrusted, Trusted, etc.</p>
<hr>
<p><strong>Edit:</strong> Here's the minor test-app I wrote to find this code, thanks to <a href="https://stackoverflow.com/users/2525/blowdart">@blowdart</a>.</p>
<pre><code>using System;
using System.Reflection;
namespace zone_check
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(".NET version: " + Environment.Version);
foreach (Object ev in Assembly.GetExecutingAssembly().Evidence)
{
if (ev is System.Security.Policy.Zone)
{
System.Security.Policy.Zone zone = (System.Security.Policy.Zone)ev;
Console.WriteLine("Security zone: " + zone.SecurityZone);
break;
}
}
}
}
}
</code></pre>
| <p>You need to look at the CAS evidence for the current assembly;</p>
<p>this.GetType().Assembly.Evidence</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.evidence.aspx" rel="noreferrer">Assembly.Evidence</a> is a property <a href="http://msdn.microsoft.com/en-us/library/system.security.policy.evidence.aspx" rel="noreferrer">Evidence</a> object. From this you can <a href="http://www.improve.dk/blog/2008/06/11/analyzing-assembly-evidence" rel="noreferrer">enumerate the evidence</a> and look for the zone which appears as a <System.Security.Policy.Zone> element.</p>
| <p>You can also use </p>
<pre><code>Evidence e = Thread.CurrentThread.GetType().Assembly.Evidence;
</code></pre>
<p>instead of</p>
<pre><code>this.GetType().Assembly.Evidence
</code></pre>
| 29,630 |
<p>I have a new Tevo Tornado, which I have completed two good prints with, a 20x20 test cube from the supplied SD and the spool holder also from the SD. I say this to note that the printer was capable of producing a good print.</p>
<p>Print 3 was a design I created in Fusion and it printed badly, very disappointing holes missing. Stringing gaps between material just rubbish. I downloaded a simple print from Thingiverse just to see if it was my poor design skills or the printer and that came out just as poorly: lots of strings between details. Both of these were sliced in Cura. As that doesn't have a tornado driver, I downloaded one from the support group and the prints have not even started properly, see pictures for example.</p>
<p>I might be going down rabbit holes here but this is what I have found and tried:</p>
<ul>
<li>1 relieved bed - done to ridiculous degree of accuracy, cold gross levelling then bed and nozzle at PLA working temp using feeler gauges. I have done 0.1 mm, 0.15 mm, 0.2 mm </li>
</ul>
<p>Now I have added to the suspicion the z axis coupler see images below: </p>
<p><a href="https://i.stack.imgur.com/KX2DWm.jpg" rel="nofollow noreferrer" title="z axis flexible coupling#1"><img src="https://i.stack.imgur.com/KX2DWm.jpg" alt="z axis flexible coupling#1" title="z axis flexible coupling#1"></a><a href="https://i.stack.imgur.com/KAWNmm.jpg" rel="nofollow noreferrer" title="z axis flexible coupling#2"><img src="https://i.stack.imgur.com/KAWNmm.jpg" alt="z axis flexible coupling#2" title="z axis flexible coupling#2"></a></p>
<p><a href="https://i.stack.imgur.com/djWvKm.jpg" rel="nofollow noreferrer" title="z axis flexible coupling#3"><img src="https://i.stack.imgur.com/djWvKm.jpg" alt="z axis flexible coupling#3" title="z axis flexible coupling#3"></a></p>
<p>YouTube videos, that I have seen, show couplers that are not a spring - any thoughts? I would certainly appreciate the time anyone has to impart their knowledge.</p>
<p><strong>EDIT 1</strong>: (Additional information posted as comment, now moved to question)</p>
<p><em>The print bed is brand new from Tevo the unit has only done a few prints most aborted, and I also thought perhaps a residue from the feeler gauges had contaminated the bed, but I have cleaned it with alcohol wipes and also tried putting prints on to unused parts of the bed. You are right the g-code from the test print was from an unknown slicer, no doubt tuned by the manufacturer the part I designed in Fusion was sliced by cura. I have since tried the original test piece and it fouls the extruder nozzle almost straight away.</em> </p>
<p><em>The main differences and there are not many between the set up parts, are that the Cura code does a G92 E0 G1 F1500 E-3.5 before starting layer 0 (both set z0,3). The test piece just does a G92 E0 G1 F7200 the feed rates are different the cura print sets M204 S500 and the test sample sets no acceleration. I assume there is a default in the Marlin firmware.. there is no doubt some globs of PLA stick like in dots between the strings, but the extrusion between direction changes do not kind of like join the dots where dots stick and joins don't.</em> </p>
<p><em>I am going to change the coupler because, well, I don't know what else to do. Replacing it with a better one can't help. Other things I have thought about - PLA temps - I have gone up the whole range according to the manufacturers bandwidth in 5 degree increments no difference I have also done some bed changes but neither hotter nor colder (it's 30°C and humid at the moment, so maybe a materials property issue, but then again no difference in conditions between a successful first test and all the messes). I am storing the PLA in a gel bead box to reduce humidity. still basically stumped!</em></p>
<p><strong>EDIT 2</strong>: (Additional information posted as comment, now moved to question)</p>
<p><em>Thanks for your observation, it's a new bed and I clean down with alcohol wipes ( isopropyl) I don't think I have ever put a finger on the bed - very aware of that. While I don't know what I am talking about on the one hand I am semi convinced it is not the bed, anyway I am going to get a glass bed in part to deal with the protruding screw head issue.</em></p>
| <p>The "springs" connected to the stepper motors aren't a problem. They are special shaft couplers which allow some relief if the motor mounts are not strictly perpendicular to the lead screws. They are very rotationally stiff and allow just a little bit of misalignment between the shafts.</p>
<p>The first two prints were from the SD card. You didn't talk about slicing from an STL file, so it is possible that they were pre-sliced for this machine. Every G-code file has introductory code that initializes some aspects of the operation. Check the "preamble" code at the front of the files you have sliced. Are there commands that look different? Is the Z parameter for the first layer different from the pre-sliced files? Are there G-codes missing from the files you sliced?</p>
<p>If you are trying to understand what the G-codes do, <a href="http://reprap.org/wiki/G-code" rel="nofollow noreferrer">this resource</a> may be helpful. Some possible commands could be commands to limit acceleration, jerk, speed, or introduce offsets. Also check that the temperatures are being set correctly in the G-code you generated.</p>
<p>If you had sliced the files on the SD card, then double check that the parameters were the same. Try re-slicing the object and comparing the G-code that is generated.</p>
| <p>What it may useful to improve your prints, are the following elements, according to my personal experience with the Tevo Tornado:
1) level the bed when it's warm.
2) print a cylinder that should measure 100 mm, afterwards measure it with a caliper: regulate the steps per mm according to the difference (many guides for calibration are available, for example: <a href="https://youtu.be/Wk3qYOB4E9I" rel="nofollow noreferrer">https://youtu.be/Wk3qYOB4E9I</a>)
3) print this object to be installed on the z axis and regulated with an M5 screw and nut: <a href="https://www.thingiverse.com/thing:2827664" rel="nofollow noreferrer">https://www.thingiverse.com/thing:2827664</a>
4) Print a test for temperatures, like this: <a href="https://www.thingiverse.com/thing:2131069" rel="nofollow noreferrer">https://www.thingiverse.com/thing:2131069</a>
I hope it helps. Happy printing.</p>
| 974 |
<p>What is a strongly typed dataset? (.net)</p>
| <p>A strongly typed dataset is one that has specific types for the tables and their columns.</p>
<p>You can say</p>
<pre><code>EmployeeDataset ds = ...
EmployeeRow row = ds.Employees.Rows[0];
row.Name = "Joe";
</code></pre>
<p>instead of:</p>
<pre><code>DataSet ds = ...
DataRow row = ds.Tables["Employees"].Rows[0];
row["Name"] = "Joe";
</code></pre>
<p>This helps because you catch mistakes in naming at compile time, rather than run time and also enforces types on columns.</p>
| <p>Short answer: A dataset which is guaranteed (by the compiler) to hold a specific type.</p>
| 30,109 |
<p>I am asking this question from an educational/hacking point of view, (I wouldn't really want to code like this).</p>
<p>Is it possible to implement a while loop only using <strong>C</strong> preprocessor directives. I understand that macros cannot be expanded recursively, so how would this be accomplished?</p>
| <p>If you want to implement a while loop, you will need to use recursion in the preprocessor. The easiest way to do recursion is to use a deferred expression. A deferred expression is an expression that requires more scans to fully expand:</p>
<pre><code>#define EMPTY()
#define DEFER(id) id EMPTY()
#define OBSTRUCT(id) id DEFER(EMPTY)()
#define EXPAND(...) __VA_ARGS__
#define A() 123
A() // Expands to 123
DEFER(A)() // Expands to A () because it requires one more scan to fully expand
EXPAND(DEFER(A)()) // Expands to 123, because the EXPAND macro forces another scan
</code></pre>
<p>Why is this important? Well when a macro is scanned and expanding, it creates a disabling context. This disabling context will cause a token, that refers to the currently expanding macro, to be painted blue. Thus, once its painted blue, the macro will no longer expand. This is why macros don't expand recursively. However, a disabling context only exists during one scan, so by deferring an expansion we can prevent our macros from becoming painted blue. We will just need to apply more scans to the expression. We can do that using this <code>EVAL</code> macro:</p>
<pre><code>#define EVAL(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))
#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))
#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))
#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))
#define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__)))
#define EVAL5(...) __VA_ARGS__
</code></pre>
<p>Next, we define some operators for doing some logic(such as if, etc):</p>
<pre><code>#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__
#define CHECK_N(x, n, ...) n
#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)
#define NOT(x) CHECK(PRIMITIVE_CAT(NOT_, x))
#define NOT_0 ~, 1,
#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)
#define COMPL_0 1
#define COMPL_1 0
#define BOOL(x) COMPL(NOT(x))
#define IIF(c) PRIMITIVE_CAT(IIF_, c)
#define IIF_0(t, ...) __VA_ARGS__
#define IIF_1(t, ...) t
#define IF(c) IIF(BOOL(c))
</code></pre>
<p>Now with all these macros we can write a recursive <code>WHILE</code> macro. We use a <code>WHILE_INDIRECT</code> macro to refer back to itself recursively. This prevents the macro from being painted blue, since it will expand on a different scan(and using a different disabling context). The <code>WHILE</code> macro takes a predicate macro, an operator macro, and a state(which is the variadic arguments). It keeps applying this operator macro to the state until the predicate macro returns false(which is 0).</p>
<pre><code>#define WHILE(pred, op, ...) \
IF(pred(__VA_ARGS__)) \
( \
OBSTRUCT(WHILE_INDIRECT) () \
( \
pred, op, op(__VA_ARGS__) \
), \
__VA_ARGS__ \
)
#define WHILE_INDIRECT() WHILE
</code></pre>
<p>For demonstration purposes, we are just going to create a predicate that checks when number of arguments are 1:</p>
<pre><code>#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)
#define IS_1(x) CHECK(PRIMITIVE_CAT(IS_1_, x))
#define IS_1_1 ~, 1,
#define PRED(x, ...) COMPL(IS_1(NARGS(__VA_ARGS__)))
</code></pre>
<p>Next we create an operator, which we will just concat two tokens. We also create a final operator(called <code>M</code>) that will process the final output:</p>
<pre><code>#define OP(x, y, ...) CAT(x, y), __VA_ARGS__
#define M(...) CAT(__VA_ARGS__)
</code></pre>
<p>Then using the <code>WHILE</code> macro:</p>
<pre><code>M(EVAL(WHILE(PRED, OP, x, y, z))) //Expands to xyz
</code></pre>
<p>Of course, any kind of predicate or operator can be passed to it.</p>
| <p>I found this scheme useful when the compiler got cranky and wouldn't unroll certain loops for me</p>
<blockquote>
<p>#define REPEAT20(x) { x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;}</p>
<p>REPEAT20( val = pleaseconverge(val) );</p>
</blockquote>
<p>But IMHO, if you need something much more complicated than that, then you should write your own pre-preprocessor. Your pre-preprocessor could for instance generate an appropriate header file for you, and it is easy enough to include this step in a Makefile to have everything compile smoothly by a single command. I've done it.</p>
| 41,285 |
<p>Like many SO people, I'm in front of a computer almost all day. I like having a dark theme for Visual Studio (easier on the eyes), but since the rest of Windows and apps (explorer, dialogs, Outlook), have the full white background, it's even harder to switch between nice dark VS and sunshine bright Windows.</p>
<p>I tried a UXTheme.dll patch but couldn't find any dark themes that worked across Visual Studio and Windows apps in general. Any suggestions?</p>
<p>Edit: To be clear, I'd like no or almost no white. No scrollbars, menus, etc. </p>
| <p>I don't think you're going to find a Windows theme that can accomplish your task. Many software applications do not adhere to colors specified in Windows preferences and are not at all customizable--Notepad, for example, is black text on a white background, end of story.</p>
<p>For themes in general, Microsoft has released two official XP themes within the last year that may be worth looking at:</p>
<ul>
<li><a href="http://go.microsoft.com/fwlink/?LinkID=75078" rel="nofollow noreferrer">Zune</a></li>
<li><a href="http://www.mediafire.com/download.php?aywudxvynnq" rel="nofollow noreferrer">Embedded</a></li>
</ul>
<p>If you are planning on using a <a href="http://lifehacker.com/5056544/how-to-use-custom-windows-visual-styles" rel="nofollow noreferrer">modified uxtheme.dll</a> file, you can check out <a href="http://gelosea.deviantart.com/art/Luna-Element-v5-1-Black-57571128" rel="nofollow noreferrer">Luna Element Black</a>, which is one I have used for well over a year now.</p>
<p>If you are this passionate about not having white areas visible in some of the programs you use, perhaps you need to find new applications that provide similar features but also offer customization in terms of fonts and colors--for example, using <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="nofollow noreferrer">Notepad++</a> instead of Notepad, which gives you an almost exhaustive amount of customization possibilities.</p>
| <p>May be not exactly what you are looking for, but <a href="http://www.mohundro.com/blog/CommentView,guid,0a1943d0-c755-41bc-bc1a-246d0f38b6a1.aspx" rel="nofollow noreferrer">this is a dark color scheme</a> for visual Studio (2005 or 2008) you may use in complement of UXTheme.</p>
<p>Off course, they are other dar color schemes for Visual studio, like <a href="http://www.agileprogrammer.com/dotnetguy/archive/2006/09/07/19030.aspx" rel="nofollow noreferrer">this one</a> (Jeff <a href="http://www.codinghorror.com/blog/archives/000682.html" rel="nofollow noreferrer">has one also</a>).</p>
<p>But I am not sure there is <em>one</em> tool that applies to all windows, including Visual Studio.</p>
| 30,517 |
<p>First, let me use one sentence to let out some frustration: My god, developing for SharePoint is a f-ing mess!</p>
<p>OK, sorry, let me focus in on 1 specific scenario. I've developed (VS2005) some functionality that works if I deploy it as a DLL on a SharePoint (MOSS2007) server. Now I'm trying to identify the best way to package it as a deployable Feature.</p>
<p>Based on search results, you'd think no one has ever successfully done this in a repeatable manner! Each article contradicts the next, or documents a technique that patches some problem with someone else's techniques, and in turn is probably updated in yet another article. Many seem based on legacy methods for 2003, WSS, etc. Some recommend using MSBuild tasks to deploy to your code, copying files manually into directories with names like "12", or using tools like SharePoint Designer or to make modifications directly to a server. These sound like hacks that developers would use to install on a test server. Has anyone ever created a project that, after a successful build, can be taken to another machine and deployed with an installer or single command line instruction via STSADM?</p>
<p>I admit that I only have a beginner's knowledge of SharePoint administration, but it must be easier than it seems. I think I understand the basic concepts at <a href="http://msdn.microsoft.com/en-us/library/ms413687.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms413687.aspx</a> but isn't there a way to automate that? There must be <em>one</em> recommended practice for packaging features to be deployed on a 2007 server.. but for the life of me I can't figure out which one it is. (My best guess is that it's something like this: <a href="http://www.codeplex.com/sptemplateland" rel="nofollow noreferrer">http://www.codeplex.com/sptemplateland</a>, but that hasn't been updated since Feb 2007.)</p>
<p>Can anyone help? Thanks so much!</p>
| <p>The 'talk on the street' usually revolves around three options for SharePoint development. </p>
<ol>
<li><a href="http://blogs.msdn.com/sharepoint/archive/2008/06/04/announcing-the-vsewss-version-1-2.aspx" rel="nofollow noreferrer">VSeWSS, Microsoft's own extentions for Visual Studio</a>.</li>
<li><a href="http://www.codeplex.com/stsdev" rel="nofollow noreferrer">STSDEV</a>, pre-creates a VS solution based on your specs</li>
<li><a href="http://codeplex.com/wspbuilder" rel="nofollow noreferrer">WSPBuilder</a>, my preference because of its VS integration</li>
</ol>
<p>All have strengths and weaknesses and I advice you to try out all three to find your preference. </p>
<p>.b</p>
| <p>Having used VSeWSS 1.2 I would recommend creating an STSDEV solution that wraps up the code and copies the webpart to the correct place.</p>
<p><strong>Update</strong>
However, VSeWSS 1.3 is now the "official" MS take on things and will be supported in future versions of Visual Studio, so that is probably the route to take now.</p>
<p>Unfortunately you are still going to need to know where every thing has to fit go into SharePoint to get it to work. Under the hood, the solution and the feature still use gnarly XML formats to control the direction all the bits of the solution go.</p>
<p>After a while the acute pain you feels dulls to a low throb.</p>
| 46,730 |
<p>Where can I find a good Rails newbie-friendly reference about generating rails models with foreign key relationships? </p>
<p>I've found some pages indicating that you should add <code>has_many</code> and <code>belongs_to</code> to the relevant models to specify these relationships, but haven't seen any instructions for getting the scaffolds to generate the correct controller and view code that would reflect these relationships.</p>
| <p><a href="http://ruby.railstutorial.org/ruby-on-rails-tutorial-book" rel="nofollow">http://ruby.railstutorial.org/ruby-on-rails-tutorial-book</a></p>
<p>and check Chap 11 and 12 for Rails 3 and Rails 3.2 I hope you like those chaps and it is very nice concept for foreign key relationships</p>
| <p>There are a bunch of StackOverflow questions asking for newbie reference materials. I recommend that you start with the two Peepcode screencasts:</p>
<ul>
<li><a href="http://peepcode.com/products/rails-from-scratch-part-i" rel="nofollow noreferrer">Rails From Scratch Part I</a></li>
<li><a href="http://peepcode.com/products/rails-from-scratch-part-ii" rel="nofollow noreferrer">Rails From Scratch Part II</a></li>
</ul>
<p>They do a great job of visually introducing you to Rails 2 development. Then, I'd recommend you pick up the Rails 2.1 PDF by Ryan Daigle, to get the hang of the 2.1 features not covered in the screencasts. </p>
<p>I'm not sure what you're driving at with your question. What are you expecting the scaffolding to do? Create multi-object relationship links automatically? That's something you have to start layering in yourself....and as you do so, the scaffolding starts to be replaced with a real application. The scaffolding is just a starting point: it's not meant to guess what your inter-object relationships are going to look like in the application. </p>
| 19,803 |
<p>One of the most common dilemmas I have when commenting code is how to mark-up argument names. I'll explain what I mean:</p>
<pre><code>def foo(vector, widht, n=0):
""" Transmogrify vector to fit into width. No more than n
elements will be transmogrified at a time
"""
</code></pre>
<p>Now, my problem with this is that the argument names <code>vector</code>, <code>width</code> and <code>n</code> are not distinguished in that comment in any way, and can be confused for simple text. Some other options:</p>
<blockquote>
<p>Transmogrify 'vector' to fit into
'width'. No more than 'n'</p>
</blockquote>
<p>Or maybe:</p>
<blockquote>
<p>Transmogrify -vector- to fit into
-width-. No more than -n-</p>
</blockquote>
<p>Or even:</p>
<blockquote>
<p>Transmogrify :vector: to fit into
:width:. No more than :n:</p>
</blockquote>
<p>You get the point. Some tools like Doxygen impose this, but what if I don't use a tool ? Is this language dependent ? </p>
<p>What do <strong>you</strong> prefer to use ?</p>
| <p>I personally prefer single quotes--your first example. It seems closest to how certain titles / named entities can be referenced in English text when neither underlining nor italics are available.</p>
| <p>I agree with Reuben: The first example is the most readable. </p>
<p>Of course that depends on your personal reading habits - If you got used to read comments in the style of your third example, you may find that style the most readable.</p>
<p>But the first style is closest to the way we read and write text in day-to-day life (newspapers, book). Therefore it is the one that will be easiest to read for someone who has no prior experience to reading your comments. </p>
| 49,860 |
<p>I'm using an XYPlot in JFreeChart. All the lines on it are XYSeries objects. Both axes are NumberAxis objects. The Y-Axis range is from 0-1, with ticks every .1. Along with displaying the numbers though, I'd like to display text on the Y-Axis, like High/Medium/Low. High would cover .7-1, etc. What is the best way to go about doing this? </p>
| <p>I have some JFreeChart experience, and after a little research I don't have an answer for adding the three labels to the axis.</p>
<p>However, as an alternative approach, you should be able to delineate these three areas on the plot with colors by setting a <a href="http://www.jfree.org/jfreechart/api/gjdoc/org/jfree/chart/axis/MarkerAxisBand.html" rel="nofollow noreferrer">MarkerAxisBand</a> for the NumberAxis (using <a href="http://www.jfree.org/jfreechart/api/gjdoc/org/jfree/chart/axis/NumberAxis.html#setMarkerBand:MarkerAxisBand" rel="nofollow noreferrer">this method</a>).</p>
<p>You could then add interval markers to the MarkerAxisBand to highlight the three areas.</p>
| <p>try this ... it can give similare result </p>
<p><a href="https://stackoverflow.com/questions/12262947/jfreechart-text-annotations-not-working">JFreeChart Text Annotations not Working?</a></p>
<pre><code>XYTextAnnotation textAnnotaion = new XYTextAnnotation(description, xMid, yMid);
plot.addAnnotation(textAnnotaion);
textAnnotaion.setRotationAngle(90.0);
</code></pre>
| 17,470 |
<p>I am writing a C# Windows Forms application which calls Oracle stored procedures.</p>
<p>I chose to use typed datasets in the application, these correctly populate various datagrids, but I am having trouble when invoking the UpdateCommand or the InsertCommand. I have manually coded these commands because a) I am using Oracle stored procedures and b) I don't trust CommandBuilder ;)</p>
<p>I am using VS2008 and Oracle 9i</p>
<p>I don't have trouble executing stored procedures in SQL Server or Oracle when simply calling them from the .ExecuteNonQuery command; neither do I have problems executing SQL statements directly and updating the database. The problems only arise when executing the changed rows with OracleDataAdapter.Update(). I am specifying the correct set of rows (added, changed etc.) </p>
<p>The main error I am getting (after a lot of experimentation with increasingly simpler SPs finishing with just one int parameter) is "PLS-00306: wrong number or type of arguments in call to 'PROCNAME'"</p>
<p>I have tried prefixing the Oracle parameter both with ':' and without.</p>
<p>Suffice to say I am losing the will to live. Has anyone any more ideas I could try next?</p>
<p>Thanks</p>
| <p>Are you using Oracle's ODBC driver, or Microsoft? </p>
<p>Stick with the Oracle driver. </p>
<p>Try using your simple test case with a text parameter instead of an integer. Without seeing your code, it could be that you need to pass in a long int to the procedure. Trying a simple text parameter could verify that the problem is in variable typing.</p>
| <p>thanks for the reply, its the Oracle 9.02.0.0 driver, SQORA32.DLL.
It has always worked fine for everything else I have done... guess you have put a seed of doubt in my mind!</p>
| 29,495 |
<p>Is it possible to write a <code>doctest</code> unit test that will check that an exception is raised?<br />
For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x < 0</code>, how would I write the <code>doctest</code> for that?</p>
| <p>Yes. You can do it. The <a href="https://docs.python.org/3/library/doctest.html" rel="noreferrer">doctest module documentation</a> and Wikipedia has an <a href="http://en.wikipedia.org/wiki/Doctest#Example_2:_doctests_embedded_in_a_README.txt_file" rel="noreferrer">example</a> of it.</p>
<pre><code> >>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
</code></pre>
| <pre><code>>>> import math
>>> math.log(-2)
Traceback (most recent call last):
...
ValueError: math domain error
</code></pre>
<p>ellipsis flag <em># doctest: +ELLIPSIS</em> is not required to use ... in Traceback doctest </p>
| 3,363 |
<p>I have a database where I store objects. I have the following (simplified) schema</p>
<pre><code>CREATE TABLE MyObjects
(
UniqueIdentifier Id;
BigInt GenerationId;
BigInt Value;
Bit DeleteAction;
)
</code></pre>
<p>Each object has a unique identifier ("Id"), and a (set of) property ("Value"). Each time the value of the property for an object is changed, I enter a new row into this table with a new generation id ("GenerationId", which is monotonically increasing). If an object is deleted, then I record this fact by setting the "DeleteAction" bit to true.</p>
<p><strong>At any point in time (generation), I would like to retrieve the state of all of my active objects!</strong></p>
<p>Here's an example:</p>
<pre><code>Id GenerationId Value DeleteAction
1 1 99 false
2 1 88 false
1 2 77 false
2 3 88 true
</code></pre>
<p>Objects in generations are:</p>
<pre><code> 1: 1 {99}, 2 {88}
2: 1 {77}, 2 {88}
3: 1 {77}
</code></pre>
<p>The key is: how can I find out the row for each unique object who's <strong>generation id is closest (but not exceeding) to a given generation id</strong>? I can then do a post-filter step to remove all rows where the DeleteAction field is true.</p>
| <p>This works in MS SQL</p>
<pre><code>SELECT id,value
FROM Myobjects
INNER JOIN (
SELECT id, max(GenerationID) as LastGen
FROM MyObjects
WHERE GenerationID <= @Wantedgeneration
Group by ID)
On GenerationID = LastGen
WHERE DelectedAction = false
</code></pre>
| <p>Not sure whether that's standard SQL, but in Postgres, you can use the LIMIT flag:</p>
<pre><code> select GenerationId,Value,DeleteAction from MyObjects
where Id=1 and GenerationId < 3
order by GenerationId
limit 1;
</code></pre>
| 43,084 |
<p>I've installed an OpenType font on my development machine expecting to then be able to choose that font for a label on a form.</p>
<p>The font is available in MS Word so I'm reasonably confident it was installed ok, but I can't see the font in the font-picker dialog for the label in Visual Studio. I also checked the font settings in Tools > Options and it isn't there either. Running the code from <a href="https://stackoverflow.com/questions/106712/how-to-make-sure-a-font-exists-before-using-it-with-net#106724">this answer</a> doesn't list the font. I've tried restarting VS.Net.</p>
<p>What else can I do to make this font show up in Visual Studio? </p>
| <p>GDI+ doesn't support OpenType, only TrueType.</p>
| <p>If you haven't tried restarting Visual Studio yet, I'd give that a try.</p>
<p>Assuming you did that already, is the font listed in c:\windows\fonts\ okay? If it is, you might want to try removing it and then re-installing that font via the File > Install New Font... menu when you've got that window open.</p>
<p>Just some ideas and things to try. Hope it helps!</p>
| 33,800 |
<p>Does anyone know how to auto-mount an <a href="http://aws.amazon.com/ebs/" rel="nofollow noreferrer">Elastic Block Storage</a> (EBS) volume when starting a Windows 2003 instance in Amazon's <a href="http://aws.amazon.com/ec2/" rel="nofollow noreferrer">Elastic Compute Cloud</a> (EC2)?</p>
| <p>Setup:</p>
<ul>
<li>Make sure the EBS volume is formatted and labeled (in the example I used the label PDRIVE). </li>
<li>Setup a drive mapping using Ec2ConfigServiceSettings.exe</li>
<li>Install Java on the instance</li>
<li>Install the EC2 API command line tools</li>
<li>Install a copy of your cert and private key</li>
<li>Install a copy of curl.exe (open source tool)</li>
</ul>
<p>You can use the group policy editor to set this script as your startup script. See <a href="http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx</a> for more information.</p>
<pre><code>REM @echo off
REM setlocal ENABLEDELAYEDEXPANSION
C:\WINDOWS\system32\eventcreate /l SYSTEM /t information /id 100 /so AttachEbsBoot /d "Starting attach-ebs-boot.cmd"
REM local variables
REM Make sure you include the directory with curl.exe and the EC2 command line tools in the path
set path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;c:\Utils;C:\ebin\ec2\bin
set JAVA_HOME=c:\java
set EC2_HOME=c:\ebin\ec2
set EC2_CERT=<your_cert>
set EC2_PRIVATE_KEY=<your_private_key>
REM Please note: you should use the Ec2 Config Serive Settings application to ensure
REM that your EBS volume is mapped to a particular drive letter.
REM
REM edit as needed
set EBS_DRIVE=P:
set EBS_DEVICE=xvdp
REM Test to see if the drive is already attached. If it is then we're done.
if exist %EBS_DRIVE%\nul (goto done)
REM get the EBS volume ID from the user data and the instance ID from the meta-data
for /f "delims=" %%a in ('curl http://169.254.169.254/latest/user-data') do (set EBS_VOLUME=%%a)
for /f "delims=" %%b in ('curl http://169.254.169.254/latest/meta-data/instance-id') do (set INSTANCE_ID=%%b)
C:\WINDOWS\system32\eventcreate /l SYSTEM /t information /id 102 /so AttachEbsBoot /d "Volume == %EBS_VOLUME%"
C:\WINDOWS\system32\eventcreate /l SYSTEM /t information /id 103 /so AttachEbsBoot /d "Instance == %INSTANCE_ID%"
REM attach the volume
REM
REM Use a series of set command to build the command line
SET COMMAND_LINE=%EBS_VOLUME%
SET COMMAND_LINE=%COMMAND_LINE% -i
SET COMMAND_LINE=%COMMAND_LINE% %INSTANCE_ID%
SET COMMAND_LINE=%COMMAND_LINE% -d
SET COMMAND_LINE=%COMMAND_LINE% %EBS_DEVICE%
C:\WINDOWS\system32\eventcreate /l SYSTEM /t information /id 104 /so AttachEbsBoot /d "calling ec2attvole %COMMAND_LINE%"
call ec2attvol.cmd %COMMAND_LINE%
:DONE
C:\WINDOWS\system32\eventcreate /l SYSTEM /t information /id 101 /so AttachEbsBoot /d "Exiting attach-ebs-boot.cmd"
REM Events logged in the System event log
REM source === AttachEbsBoot
REM
REM Event 100 - Script start
REM Event 101 - Script end
REM Event 102 - Volume ID
REM Event 103 - Instance ID
REM Event 104 - Command line for ec2attvol
</code></pre>
| <p>I found the following Ruby code at <a href="http://www.ioncannon.net/system-administration/199/automounting-amazon-ebs-volumes-on-ec2-instances/" rel="nofollow noreferrer">http://www.ioncannon.net/system-administration/199/automounting-amazon-ebs-volumes-on-ec2-instances/</a> courtesy of Carson McDonald. It's for Linux/Unix but maybe you can re-swizzle this for Ruby on Windows 2003 or have it serve as a model for doing it in some other scripting language.</p>
<p>Note that you could pass things into your image as user data such as the ECS EBS volume ID and the device name (e.g., /dev/sdh in the following example or whatever it would be in Windows for your case). You can access the user data from the instance itself as meta-data as is roughly done below to get the instance-id. More specifically, you'd access <a href="http://169.254.169.254/1.0/user-data" rel="nofollow noreferrer">http://169.254.169.254/1.0/user-data</a> to get to the user-data.</p>
<pre><code>#!/usr/bin/ruby
require 'rubygems'
require 'right_aws'
require 'net/http'
url = 'http://169.254.169.254/2008-02-01/meta-data/instance-id'
instance_id = Net::HTTP.get_response(URI.parse(url)).body
AMAZON_PUBLIC_KEY='your public key'
AMAZON_PRIVATE_KEY='your private key'
EC2_LOG_VOL='the volume id'
ec2 = RightAws::Ec2.new(AMAZON_PUBLIC_KEY, AMAZON_PRIVATE_KEY)
vol = ec2.attach_volume(EC2_LOG_VOL, instance_id, '/dev/sdh')
puts vol
# It can take a few seconds for the volume to become ready.
# This is just to make sure it is ready before mounting it.
sleep 20
system('mount /dev/sdh /mymountpoint')
</code></pre>
| 42,628 |
<p>I want to get an overview of files that are updated in TFS (that someone else checked in) that I don't have the latest version for.</p>
| <p>In Visual Studio Source Control Explorer, right click on the directory you want to compare, and select "Compare". It will pop up a dialog with a couple of filtering options, and then show you what's out of date. </p>
| <p>if they checked them in as part of a single changeset then you can find them that way. </p>
<p>(right click file in solution explorer, view history, double-click on the relevant changeset and you'll see all the related files for that checkin)</p>
<p>Is your question about finding this info via the TFS API via the website, or via the visual studio interface? </p>
| 5,445 |
<p>I normally run VS 2008 at home and LINQ is built in. At work we are still using VS 2005 and I have the opportunity to start a new project that I would like to use LINQ to SQL.</p>
<p>After doing some searching all I could come up with was the MAY 2006 CTP of LINQ would have to be installed for LINQ to work in VS 2005.</p>
<p>Does someone know the proper add ins or updates I would need to install to use LINQ in VS 2005 (preferably without having to use the CTP mentioned above).</p>
| <p>A few possible explanations:</p>
<ol>
<li><p>Are you running this script on a multi-core processor or multi-processor machine? If you only have one CPU only one thread can use it at any time.</p></li>
<li><p>Are there transactions or locks involved with steps 1-6 that would prevent it from being done concurrently?</p></li>
<li><p>Are you certain you are using multiple connections to the database and not sharing a single one between threads?</p></li>
</ol>
| <p>Check your database settings. You may find that it is set up in a conservative manner. That would cause even minor reads to block all access to that information.</p>
<p>You may also need to call <code>threads::yield</code>.</p>
| 11,177 |
<p>i have little problem with boost::asio library. My app receive and process data asynchronously, it create threads and run io_service.run() on each of them.</p>
<pre><code>boost::asio::io_service io;
boost::thread_group thread_pool;
...
int cpu_cnt = get_cpu_count();
for (int i = 0; i < cpu_cnt; ++i)
{
thread_pool.create_thread( boost::bind(&run_service, &io) );
}
void run_service(boost::asio::io_service* io)
{
try
{
io->run();//make fun
}
catch(const std::exception& e)
{ //process error
}
catch(...)
{ //process error
}
}
</code></pre>
<p>Time after time, my application receives message(across windows messaging system) from some supervisor application that checks is my program alive or not. If my application wont reply, it will be restarted. The tricky part here is to check, that threads is running and not deadlocked. I can post handler to io_service like this:</p>
<pre><code>io.post( &reply_to_supervisor );
</code></pre>
<p>but this method affects only one thread.
How can i check that all threads is running and not deadlocked?</p>
| <p>I may be wrong, but would the use an io_service per thread solve your problem?</p>
<p>Another idea: post <code>cpu_cnt</code> times <code>reply_to_supervisor</code> calls that use a little <code>sleep()</code> - not nice, but should work</p>
| <p>I'm going to assume your io->run() does some sort of loop to wait for the asio to complete. I'm also going to assume you have a timeout on this asio operation. A dirty way to check is to have a status thread run and check that either the asio thread has timed out on waiting for the asio to complete or that an asio event has been posted. Either way, you would set some sort of variable or handle to know your thread is "alive" and looping. Your status thread would then check that each variable/handle and reset them after checking.</p>
<p>Mind you, I'm sure there are other ways but this is what came to mind as of right now... =)</p>
| 46,408 |
<p><em>Let's say I have download links for files on my site.</em> </p>
<p>When clicked these links send an AJAX request to the server which returns the URL with the location of the file. </p>
<p>What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?</p>
| <p>We do it that way:
First add this script.</p>
<pre><code><script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
</code></pre>
<p>Place this where you want the download button(here we use just a link):</p>
<pre><code><iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
</code></pre>
<p>The file 'download.php' (needs to be put on your server) simply contains:</p>
<pre><code><?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
</code></pre>
<p>So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!</p>
<p>It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.</p>
| <p>I'd suggest <code>window.open()</code> to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).</p>
| 47,752 |
<p>I have a master page which all my views inherit from. The issue I am having is with the form tag which is created in the master page and then the form tag which is created in view.</p>
<p>Because of the form being inside the master page form, all my postbacks are sent to the controllers Index method and its forcing me to create a new method Index which forces an HttpPost.</p>
<p>Further this is causing problems with routes like: /projects/add/ and /projects/delete/1 where everything is router to the Index Method.</p>
<p>WTF? Am i missing something here?</p>
<p>Thanks anyone</p>
| <p>Remove the form from the master page.</p>
<p>Check some sample videos <a href="http://www.asp.net/learn/mvc-videos/" rel="nofollow noreferrer">here</a> to better understand the MVC philosophy.</p>
<p>BTW: In ASP.NET MVC, there is no postback.</p>
| <p>ASP.NET MVC isn't supposed to do "PostBacks"... that's completely missing the point. Remove any "largely-encompasing-form-tags" you have out there, and only put a "form" tag around input fields that are meant (for a specific purpose) to POST to some sort of action.</p>
<p>The fact that you have an all-encompasing form tag (as is true with traditional asp.net) means that you don't have a defined reason for that form, and that is (again) missing the point of MVC.</p>
<p>This is an older article, but it can help with the differences between traditional, and MVC: <a href="http://www.singingeels.com/Articles/ASPNET_MVC_in_the_Real_World.aspx" rel="nofollow noreferrer">ASP.NET MVC in the Real World</a></p>
| 42,649 |
<p>From my understanding the XMPP protocol is based on an always-on connection where you have no, immediate, indication of when an XML message ends.</p>
<p>This means you have to evaluate the stream as it comes. This also means that, probably, you have to deal with asynchronous connections since the socket can block in the middle of an XML message, either due to message length or a connection being slow.</p>
<p>I would appreciate one source per answer so we can mod them up and see what's the favourite.</p>
| <p>Are you wanting to deal with multiple connections at once? Good asynch socket processing is a must in that case, to avoid one thread per connection.</p>
<p>Otherwise, you just need an XML parser that can deal with a chunk of bytes at a time. <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">Expat</a> is the canonical example; if you're in Java, try <a href="http://www.jclark.com/xml/xp/" rel="nofollow noreferrer">XP</a>. These types of XML parsers will fire events as possible, and buffer partial stanzas until the rest arrives.</p>
<p>Now, to address your assertion that there is no notification when a <em>stanza</em> ends, that's not really true. The important thing is not to process the XML stream as if it is a sequence of documents. Use the following pseudo-code:</p>
<pre><code>stanza = null
while parser has more:
switch on token type:
START_TAG:
elem = create element from parser state
if stanza is not null:
add elem as child of stanza
stanza = elem
END_TAG:
parent = parent of stanza
if parent is not null:
fire OnStanza event
stanza = parent
</code></pre>
<p>This approach should work with an event-based or pull parser. It only requires holding on to one pointer worth of state. Obviously, you'll also need to handle attributes, character data, entity references (like &amp; and the like), and special-purpose the stream:stream tag, but this should get you started.</p>
| <p>Igniterealtime.org provides an open source XMPP-server and client written in java</p>
| 13,317 |
<p>I want to use the new report builder 2.0, rather than the old VS2005 integrated report builder for the new features and ease of use, but source control integration is a must.</p>
<p>I don't see any ability to use TFS natively, and I have installed the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=FAEB7636-644E-451A-90D4-7947217DA0E7&displaylang=en" rel="nofollow noreferrer">TFS MSSCCI Provider</a>, all with no love.</p>
<p>Does anyone know how to get them to play well, or am I looking at this from the wrong angle. </p>
<p>How do you version control your SQL reports?</p>
| <p>If you are using the Report Builder you can just open RDL files from the filesystem but yes, it doesnt integrate with TFS directly or any source control package. You need to VS I'm affraid. So you can checkout, open in report builder.. save then check back in. </p>
| <p>RB2 doesnt use a traditional file system interface but instead uses the reportserver web service to communicate with files on the report server. Because of this disconnect you wont find any simple answers - but one suggestion. If you are running in sharepoint integrated mode you could possibly get some level of change tracking.</p>
| 36,044 |
<p>I want to clear the list of projects on the start page...how do I do this? I know I can track it down in the registry, but is there an approved route to go?</p>
| <p>There is an MSDN article <a href="http://msdn.microsoft.com/en-us/library/aa991991.aspx" rel="noreferrer">here</a> which suggests that you just move the projects to a new directory.</p>
<p>However, as you mentioned, the list of projects is kept in the registry under this key:</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\ProjectMRUList
</code></pre>
<p>and the list of recent files is kept in this key:</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\<version>\FILEMRUList
</code></pre>
<p><strong>Note For Visual Studio 2015:</strong><br/>
The location has changed. You can check out <a href="https://stackoverflow.com/a/33945037/62195">this answer</a> for details.</p>
<p>Some people have automated clearing this registry key with their own tools:<br/>
<a href="http://www.codeplex.com/vsrecentfiles" rel="noreferrer">Visual Studio Most Recent Files Utility</a> <br />
<a href="http://code.msdn.microsoft.com/CleanRecentListAddIn" rel="noreferrer">Add-in for cleaning Visual Studio 2008 MRU Projects list</a></p>
| <p>Try Recently Used Files: a free addin for Visual Studio that manages MRU files on a per-project basis:
Supported for VS 2010, 2012, 2013.</p>
<p>For Visual Studio 2012, 2013:
<a href="http://visualstudiogallery.msdn.microsoft.com/a61cbd1d-b5a2-490b-a6bb-f0ea3ecf214a" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/a61cbd1d-b5a2-490b-a6bb-f0ea3ecf214a</a></p>
<p>For Visual Studio 2010:
<a href="http://visualstudiogallery.msdn.microsoft.com/45283881-5a62-4dc1-8ffb-4cbc02709947" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/45283881-5a62-4dc1-8ffb-4cbc02709947</a></p>
| 10,836 |
<p>So I just spent 5 hours troubleshooting a problem which turned out to be due not only to the <a href="https://web.archive.org/web/20141209040727/http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html" rel="nofollow noreferrer">old unreliable</a> <code>ISNUMERIC</code> but it looks like my problem only appears when the UDF in which <code>ISNUMERIC</code> is declared <code>WITH SCHEMABINDING</code> and is called within a stored proc (I've got a lot of work to do to distill it down into a test case, but my first need is to replace it with something reliable).</p>
<p>Any recommendations on good, efficient replacements for <code>ISNUMERIC()</code>. Obviously there really need to be variations for <code>int</code>, <code>money</code>, etc., but what are people using (preferably in T-SQL, because on this project, I'm restricted to SQL Server because this is a high-volume SQL Server to SQL Server data processing task)?</p>
| <p>You can use the T-SQL functions TRY_CAST() or TRY_CONVERT() if you're running SQL Server 2012 as Bacon Bits mentions in the comments:</p>
<pre><code>SELECT CASE WHEN TRY_CAST('foo' AS INT) IS NULL THEN 0 ELSE 1 END
SELECT CASE WHEN TRY_CAST(1 AS INT) IS NULL THEN 0 ELSE 1 END
</code></pre>
<p>If you're using SQL 2008 R2 or older, you'll have to use a .NET CLR function, and wrap System.Decimal.TryParse().</p>
| <p>IsNumeric() seems to have problems with spaces, 'D', 'E', dollar signs and all sorts of other characters. What we typically want is something that tells us whether a CAST or CONVERT will succeed. This UDF, while not the fastest solution, has worked very well for me.</p>
<pre><code>create function dbo.udf_IsNumeric(@str varchar(50))
returns int
as
begin
declare @rtn int
select @rtn =
case
when ltrim(rtrim(@str)) in('.', '-', '-.', '+', '+.') then 0
when ltrim(rtrim(@str)) like '%[^-+.0-9]%' then 0
else isnumeric(@str)
end
return @rtn
end
</code></pre>
| 40,216 |
<p>When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change. </p>
<p>MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated.</p>
<p>(Note that I'm <em>not</em> talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level)</p>
<p>This has been discussed in other posts here on Stack Overflow. [todo - links]</p>
<p>I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC.</p>
| <p>I might consider implementing the MVCC tier purely in the DB, using stored procs and views to handle my data operations. Then you could present a reasonable API to any ORM that was capable of mapping to and from stored procs, and you could let the DB deal with the data integrity issues (since it's pretty much build for that). If you went this way, you might want to look at a more pure Mapping solution like IBatis or IBatis.net.</p>
| <p>I always figured you'd use a db trigger on update and delete to push those rows out into a TableName_Audit table.</p>
<p>That'd work with ORMs, give you your history and wouldn't decimate select performance on that table. Is that a good idea or am I missing something?</p>
| 6,889 |
<p>I have a nested class. I want to access the outer and nested classes in other class.
How to access both class properties and methods and my condition is i want to create object for only one class
plz provide the code snippet</p>
| <p>You can learn about Nested Types <a href="http://msdn.microsoft.com/en-us/library/ms173120.aspx" rel="nofollow noreferrer">here</a>.</p>
| <p>Your question isn't very clear. However, I guess you're from a Java background. C#'s and VB's nested classes behave much different from Java's nested classes. In fact, they behave much like Java's static nested classes, i.e. they don't belong to an instance of the outer class. Therefore, instances of the inner class can't access nonstatic fields in the outer class (at least not without being given an instance explicitly).</p>
| 17,020 |
<p>I have the following code fragment that starts a <a href="http://en.wikipedia.org/wiki/Google_Earth" rel="nofollow noreferrer">Google Earth</a> process using a hardcoded path:</p>
<pre><code>var process =
new Process
{
StartInfo =
{
//TODO: Get location of google earth executable from registry
FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe",
Arguments = "\"" + kmlPath + "\""
}
};
process.Start();
</code></pre>
<p>I want to programmatically fetch the installation location of <em>googleearth.exe</em> from somewhere (most likely the registry).</p>
| <p>Obviously if you're opening a specific file associated with the program then launching it via the file is preferable (for instance, the user might have a program associated with the file type they prefer to use).</p>
<p>Here is a method I've used in the past to launch an application associated with a particular file type, but without actually opening a file. There may be a better way to do it.</p>
<pre><code>static Regex pathArgumentsRegex = new Regex(@"(%\d+)|(""%\d+"")", RegexOptions.ExplicitCapture);
static string GetPathAssociatedWithFileExtension(string extension)
{
RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension);
if (extensionKey != null)
{
object applicationName = extensionKey.GetValue(string.Empty);
if (applicationName != null)
{
RegistryKey commandKey = Registry.ClassesRoot.OpenSubKey(applicationName.ToString() + @"\shell\open\command");
if (commandKey != null)
{
object command = commandKey.GetValue(string.Empty);
if (command != null)
{
return pathArgumentsRegex.Replace(command.ToString(), "");
}
}
}
}
return null;
}
</code></pre>
<p>Sometimes though there are cases when you want to launch a specific program without opening a file. Usually (hopefully) the program has a registry entry with the install location. Here is an example of how to launch Google Earth in such a manner.</p>
<pre><code>private static string GetGoogleEarthExePath()
{
RegistryKey googleEarthRK = Registry.CurrentUser.OpenSubKey(@"Software\Google\Google Earth Plus\");
if (googleEarthRK != null)
{
object rootDir = googleEarthRK.GetValue("InstallLocation");
if (rootDir != null)
{
return Path.Combine(rootDir.ToString(), "googleearth.exe");
}
}
return null;
}
</code></pre>
| <p>Here's a C++ version I just had to write. Taken directly from ICR's C# version.</p>
<pre><code>void PrintString(CString string)
{
std::wcout << static_cast<LPCTSTR>(string) << endl;
}
CString GetClassesRootKeyValue(const wchar_t * keyName)
{
HKEY hkey;
TCHAR keyNameCopy[256] = {0};
_tcscpy_s(keyNameCopy, 256, keyName);
BOOL bResult = SUCCEEDED(::RegOpenKey(HKEY_CLASSES_ROOT, keyNameCopy, &hkey));
CString hkeyValue = CString("");
if (bResult) {
TCHAR temporaryValueBuffer[256];
DWORD bufferSize = sizeof (temporaryValueBuffer);
DWORD type;
bResult = SUCCEEDED(RegQueryValueEx(hkey, _T(""), NULL, &type, (BYTE*)temporaryValueBuffer, &bufferSize)) && (bufferSize > 1);
if (bResult) {
hkeyValue = CString(temporaryValueBuffer);
}
RegCloseKey(hkey);
return hkeyValue;
}
return hkeyValue;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
CString dwgAppName = GetClassesRootKeyValue(_T(".dwg"));
PrintString(dwgAppName);
dwgAppName.Append(_T("\\shell\\open\\command"));
PrintString(dwgAppName);
CString trueViewOpenCommand = GetClassesRootKeyValue(static_cast<LPCTSTR>(dwgAppName));
PrintString(trueViewOpenCommand);
// Shell open command usually ends with a "%1" for commandline params. We don't want that,
// so strip it off.
int firstParameterIndex = trueViewOpenCommand.Find(_T("%"));
PrintString(trueViewOpenCommand.Left(firstParameterIndex).TrimRight('"').TrimRight(' '));
cout << "\n\nPress <enter> to exit...";
getchar();
}
}
</code></pre>
| 23,224 |
<p>What is the best way to dynamically add TableRows and TableCells to an ASP.NET table from Javascript?</p>
<p>Thanks,</p>
<p>Jeff</p>
| <p>Your question is too vague to answer completely, I'm afraid. If you actually want to create TableRow or TableCell objects, you would of course need to post back (no need for JavaScript) or make an AJAX call (JavaScript) to server-side code. Either way, it's not really JavaScript doing the work. If you just want to dynamically add a row to an HTML table presented in the browser, you could accomplish this without any need for TableRow/TableCell abstractions from ASP.NET.</p>
<p>For a more complete answer you'll have to be more specific about what you are trying to accomplish.</p>
| <p>Unless, of course, you're using javascript.net as your serverside scripting language !-)</p>
| 38,155 |
<p>I have a question about variable initialization in MASM's assembly. </p>
<p>How can I initialize 2^32 to a variable and to what kind of variable should I initialize? DWORD or REAL4?</p>
<p>I try to do it like:</p>
<pre><code>val DWORD 2.0E+32
</code></pre>
<p>When I assign var to a register(e.g. mov eax,val) and try to write the value, I see something that is not 2^32. I also tried it with REAL4 type. Result is still same. </p>
<p>So What I am doing wrong here?</p>
<p>Thanks in advance...</p>
| <p>2^32 = 4294967296 = 0x100000000 (that's 8 zeroes).</p>
<p><strong><code>2.0E+32</code></strong> is 2 * 10^32 = 200000000000000000000000000000000, a <em>completely</em> different number. It's also a floating-point number, whereas <strong><code>0x100000000</code></strong> is an integer.</p>
| <p>2^32 = 4294967296 = 0x100000000 (that's 8 zeroes).</p>
<p><strong><code>2.0E+32</code></strong> is 2 * 10^32 = 200000000000000000000000000000000, a <em>completely</em> different number. It's also a floating-point number, whereas <strong><code>0x100000000</code></strong> is an integer.</p>
| 38,122 |
<blockquote>
<p>UPDATED: on win2k it seems it works OK. Sorry for the confusion.</p>
</blockquote>
<p>MS Windows Vista internal ftp client has a strange behavior.
When redirecting its output and error to a file, the errors do not show up there:</p>
<blockquote>
<p>ftp -n -s:commands.txt host >output.log 2>&1</p>
</blockquote>
<p>When running it from Task Scheduler inside a batch file, I don't get any error messages if connection refused. Even if echo is on or with the -d option.
Do you have a workaround for it?</p>
| <p>Build a Service Layer and expose it over RMI - possibly as EJB3 stateless session beans as you have JBoss, possibly as pure RMI. I wouldn't bother with web services unless you have a specific need. RMI will take case of serialisation for you.</p>
<p>Your service layer needs to expose a method to authenticate users using their credentials entered on startup of the Swing app. All calls for data go through the service layer. No SQL exists in the Swing app.</p>
<p>There are other benfits of this arrangment other than just hiding the database credentials. Not only do you end up with a layered architecture, but you gain efficiencies from sharing prepared statements amongst all your clients by having a single data source on the server.</p>
| <p>So you want users to be able to access the database without knowing the credentials? Your only option is server-side database access. Unfortunately there is no way of hiding the username and password in Java -- if you put it into a properties file and encrypt it, a determined attacker could still attach a debugger and see what values are being held in your code.</p>
<p>Also, unless you're connecting to the DB over a secure connection someone could run a packet sniffer such as tcpdump and get the credentials there.</p>
<p>You say that you're running a JBoss server, what might be best is to set up remote EJBs so that your client application doesn't access the database directly - it has to go via your EJB methods. (It doesn't have to be EJB, by the way, you could do something such as web services if you prefer).</p>
<p>The point is, your server talks to the databas directly, and your client's only access is via a limited set of interfaces you define on the server.</p>
| 21,949 |
<p>I am trying to create a wpf control that will display a map image using google maps. I want to be able to centre the map on a longitude and latitude specified by the application. Ideally, the control will then allow the user to move a map marker and store the latitude/longitude of the marker in the application.</p>
<p>The only way I can think of doing this is to use a WebBrowser control and create a HTML string at runtime that shows a map of the desired location. This seems like an awkward solution and won't allow me to easily retrieve the marker location. Does anyone know of a better way to accomplish this? </p>
| <p>Hosting Google Maps in a Microsoft WPF application using XAML
<a href="http://code.google.com/apis/maps/articles/flashmapinwpf.html" rel="nofollow noreferrer">http://code.google.com/apis/maps/articles/flashmapinwpf.html</a></p>
| <p>There is a nice integration between windows forms and Microsoft Virtual Earth (<a href="http://mtaulty.com/communityserver/blogs/mike_taultys_blog/archive/2005/08/01/5547.aspx" rel="nofollow noreferrer">sample here</a>.) There are licensing considerations for commercial products, but this is certainly more or a "turnkey" option. You would also need to look into the Windows Forms Host to put a Forms control into a WPF app.</p>
| 44,201 |
<p>I'm running a MySQL database locally for development, but deploying to Heroku which uses Postgres. Heroku handles almost everything, but my case-insensitive Like statements become case sensitive. I could use iLike statements, but my local MySQL database can't handle that.</p>
<p>What is the best way to write a case insensitive query that is compatible with both MySQL and Postgres? Or do I need to write separate Like and iLike statements depending on the DB my app is talking to?</p>
| <pre><code>select * from foo where upper(bar) = upper(?);
</code></pre>
<p>If you set the parameter to upper case in the caller, you can avoid the second function call.</p>
| <p>Converting to upper is best as it covers compatible syntax for the 3 most-used Rails database backends. PostgreSQL, MySQL and SQLite all support this syntax. It has the (minor) drawback that you have to uppercase your search string in your application or in your conditions string, making it a bit uglier, but I think the compatibility you gain makes it worthwile.</p>
<p>Both MySQL and SQLite3 have a case-insensitive LIKE operator. Only PostgreSQL has a case-sensitive LIKE operator and a PostgreSQL-specific (per the manual) ILIKE operator for case-insensitive searches. You might specify ILIKE insead of LIKE in your conditions on the Rails application, but be aware that the application will cease to work under MySQL or SQLite.</p>
<p>A third option might be to check which database engine you're using and modify the search string accordingly. This might be better done by hacking into / monkeypatching ActiveRecord's connection adapters and have the PostgreSQL adapter modify the query string to substitute "LIKE" for "ILIKE" prior to query execution. This solution is however the most convoluted and in light of easier ways like uppercasing both terms, I think this is not worh the effort (although you'd get plenty of brownie points for doing it this way).</p>
| 24,887 |
<p>This has been bugging me for a long time -- how do I properly resolve a merge conflict within the SVN properties set on a directory? Say for instance there are two developers working on a project where svn:ignore is set on some directory. If both developers make changes to this property, when the second one updates, they will see a merge conflict.</p>
<p>Unlike file merge conflicts, a single file is generated in the directory called "dir_conflicts.prej", which the second developer must read and manually correct. Usually, what I end up doing is reverting all my changes to the local copy, then re-setting these properties manually with the info in dir_conflicts.prej. However, this is rather cumbersome when dealing with a big list of URLs in an svn:externals property, as many of our projects use.</p>
<p>There has got to be a better way to do this -- does anybody know how?</p>
| <p>Just a quick update after some additional research -- it is <em>not</em> possible to easily merge SVN properties. My originally described method (revert, merge data from .prej files, propset, re-commit) appears to be the best way to deal with this type of problem.</p>
| <p>Just to be clear, SVN appears to use the dir_conflicts.prej file to derive the fact that the directory has a conflict. If you intend to manually address the conflict, you can simply delete the dir_conflicts.prej file and then manually set the svn properties as you want them. (Of course making sure to get what you need from the .prej file before you delete it!)</p>
| 18,445 |
<p>I have some code in .Net to draw some text content using GDI+. I used GraphicsUnit.Point to size the text. It's working wonderfully on-screen, and even if Print it.</p>
<p>I've been asked to make a system that generates a PDF, and I got ComponentOne's PDF control. It has got similar interface to GDI+.</p>
<p>The problem is: Font sizes are not working. If I use GraphicsUnit.Point, the text is much smaller, and I am getting empty space below the text. When I use GraphicsUnit.World, the text is still small, but there's no extra empty space below the text.</p>
<p>I want to understand how to convert GraphicsUnit.World to GraphicsUnit.Point. </p>
<p>All help will be appreciated.</p>
<p>Thanks</p>
| <p>After some Googeling and from what I know from personal experience with GDI+ and String drawing it comes down to DPI (Dots per Inch). Basically the different devices (and as far as GDI+ is concerned, PDF is probably a device) have different DPI values. Displays usually have something like 70 DPI. Printers use 72. I don't know what PDFs use, but it might be 100 (as this is a common value for device independence and would explain the smaller text).<br/> <br/>
Now, Points are defined as being 72 DPI. This is always true. What GDI+ should do, when drawing to a PDF with a different DPI is, to transform the string drawing accordingly. But this does not always work, especially with text. <br/><br/>
The GraphicsUnit.World should (according to some googeling) be device independent and should look the same on all devices. </p>
| <p>You're right, GraphicsUnit.World looks the same on print, and also on screen. My final solution was to use GraphicsUnit.World as the unit of measure, and shun points. I still don't know the conversion ratio, but I approximated the value till the look was okay.</p>
<p>For my purpose this was enough.</p>
| 32,203 |
<p>Something like this is on my mind: I put one or a few strings in, and the algorithm shows me a matching regex.</p>
<p>Is there an "<em>easy</em>" way to do this, or does something like this already exist?</p>
<p><strong><em>Edit 1</em></strong>: Yes, I'm trying to find a way to generate regex. </p>
<p><strong><em>Edit 2</em></strong>: Regulazy is not what I am looking for. The common use for the code I want is to find a correct RegEx; for example, article numbers:<br/></p>
<ul>
<li>I put in <em>123456</em>, the regex should be <code>\d{6}</code></li>
<li>I put in <em>nb-123456</em>, the regex should be <code>\w{2}-\d{6}</code></li>
</ul>
| <p>It sounds like you want an algorithm to generate a regular grammar based on some samples. In a lot of cases, there are many possible grammars for a given set of examples--there can even be infinite possible grammars. Of course, the possibilities can be limited by a second set of required <strong>non</strong>-matches, which can limit it to zero possibilities if the non-matching strings are too inclusive.</p>
<p><strong><a href="http://txt2re.com/" rel="nofollow noreferrer">txt2re</a></strong> does something like this.</p>
| <p>if your input strings are not random strings and they are based on some rules, by using a parser (i.e. jflex), you can create a regex generator which will generate a regex w.r.t. the given strings. </p>
| 21,392 |
<p>I'm looking into both of them, and while I have been quite pleased with NetAdvantage at my previous employer, I find the price point (plus testimonials like at <a href="https://stackoverflow.com/questions/37921/what-is-the-best-winform-ui-component-set">What is the best winform UI component set?</a>) to make me hesitate and consider DXExperience.</p>
<p>That said, I'm wondering: </p>
<ul>
<li>What your experiences are in field with either (or ideally both)? </li>
<li>Would you be willing to spend your <em>own</em> hard earned money on either one? </li>
</ul>
<p>This is for WinForms - and also a last question: </p>
<ul>
<li>Does DXperience have anything analogous to the UltraWinDataGrid? This grid is awesome -- and the absence of a reasonable competitor is a show stopper. </li>
</ul>
<p><strong>Note</strong>: This is not intended to incite a flame war, I am interested in experiences, and <strong>pragmatic</strong> advice.</p>
| <p>We evaluated libraries from Syncfusion, Infragistics, ComponentOne, Xceed, Janus and DevExpress. We decided on DevExpress based on its feature set, grid performance and features and ribbon control features.</p>
<p>Comparing Infragistics and DevExpress Grid control I found that:</p>
<ul>
<li>DevExpress Grid is faster at loading,
and handles more data, than the
Infragistics grid.
<ul>
<li>25K rows * 50 columns: Infragistics load time is 2000ms, DevExpress load
time is 1400ms</li>
<li>50K rows * 500 columns
<ul>
<li>Infragistics 600ms first load, 400ms subsequent </li>
<li>DevExpress 1000ms first load, 250ms subsequent load</li>
</ul></li>
<li>500K rows * 50 columns
<ul>
<li>Infragistsic 3500ms first load, 7000ms subsequent load </li>
<li>DevExpress 2000ms first load, 1700ms subsequent load</li>
</ul></li>
<li>2M rows * 10 columns
<ul>
<li>Infragistics Out of memory exception </li>
<li>DevExpress 8500ms first load, 10000ms subsequent load</li>
</ul></li>
</ul></li>
</ul>
<p>The DevExpress DxGrid control for Windows Forms is fantastic. Inline editors make the UX very nice. The sorting and grouping is easy to use and understand for both the developer and end-user.</p>
<p>Overall I am extremely happy with the library. Their support is excellent. Over the life of this project, I have asked over 20 support questions and have received a good response each time.</p>
<p>I would spend my own money on the DevExpress controls.</p>
| <p>These are proving helpful as well:
<a href="http://www.componentsource.com/products/dxperience-winforms/reviews.html" rel="nofollow noreferrer">http://www.componentsource.com/products/dxperience-winforms/reviews.html</a></p>
<p>and</p>
<p><a href="http://www.componentsource.com/products/netadvantage-net/reviews.html" rel="nofollow noreferrer">http://www.componentsource.com/products/netadvantage-net/reviews.html</a></p>
<p>But not decided yet...</p>
| 43,595 |
<p>I found <a href="https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference">What are mvp and mvc and what is the difference</a> but it didn't really answer this question.</p>
<p>I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on?</p>
<p><strong>Pros</strong></p>
<ol>
<li>Display and Processing are seperated</li>
</ol>
<p><br />
<strong>Cons</strong></p>
<ol>
<li>None so far</li>
</ol>
| <p>MVC is the separation of <b>m</b>odel, <b>v</b>iew and <b>c</b>ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.</p>
<p>For example, while a table grid <em>view</em> should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the <em>model</em>) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the <em>controller</em>.</p>
<p>A 'save file' dialog (<em>view</em>) ultimately passes the path, once picked by the user, on to the <em>controller</em>, which then asks the <em>model</em> for the data, and does the actual saving.</p>
<p>This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.</p>
| <p>Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance. </p>
<p>Here you can see the some more points on <a href="http://javabynataraj.blogspot.in/2009/05/14-advantages-of-mvc-arch.html" rel="nofollow">Main Advantages of MVC Architecture</a>.</p>
| 4,622 |
<p>I'm working on a web app project (in java; not that it matters) and we have a form with drop down lists and input fields. </p>
<p>Obviously drop down lists are provided because we expect a specific value from a set of values. </p>
<p>So my question is this: does it make sense to ensure the submitted value is in the set of expected values? Or is it acceptable to just assume the correct value is coming across?</p>
<p>There aren't any "errors" that would arise from different values being submitted,
but the data store would not be consistent with the business rules/requirements.</p>
| <p>If I understand correctly, you need to auto-size the width so that things show up?
<a href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a3cab53b-8c03-4f43-83ac-808dc3751db9/" rel="nofollow noreferrer">I found a post on how to do that on MSDN.</a></p>
| <p>I understand the question is old, but:</p>
<p>The best solution would be using something like <code>ToolStripDropDownDirection.AboveLeft</code>
<em>But as far as I see from source code there is nothing like this.</em></p>
<p>So another approach could be setting values of DropDownWidth/MaxDropDownItems depending of position of the combobox from the right/bottom side of the screen.
<em>But this does not work because dropdown cannot be smaller than the cell.</em></p>
<p>So you could try</p>
<ul>
<li>using refactoring to fix the control's behavior (low chance);</li>
<li>forbidding moving the window (programmatically) close to the right edge of the screen;</li>
<li>using your own control (override or write your own DataGridViewComboBoxColumn class) or buy custom grid.</li>
</ul>
| 26,163 |
<pre><code><?php
function toconv(string)
{
$gogo = array("a" => "b","cd" => "e");
$string = str_replace(
array_keys( $gogo ),
array_values( $gogo ),
$string
);
return $string;
}
?>
</code></pre>
<p>How can I implement that in JavaScript?</p>
| <p>And to make it in a way, where you can do it directly from an array:</p>
<pre><code><script type="text/javascript">
function toconv(string){
var gogo = {"a":"b", "cd":"e"}, reg;
for(x in gogo) {
reg = new RegExp(x, "g");
string.replace(x, gogo[x]);
}
return string;
}
</script>
</code></pre>
| <p>Convert PHP Function to JavaScript</p>
<pre><code>if (preg_match('/0/', $check) || preg_match('/1/', $check) || preg_match('/2/', $check) || preg_match('/3/', $check) || preg_match('/4/', $check) || preg_match('/5/', $check) || preg_match('/6/', $check) || preg_match('/7/', $check) || preg_match('/8/', $check) || preg_match('/9/', $check))
{
exception("personal info not allowed");
redirect(base_url() . 'edit_profile');
}
else if ((preg_match("~\b@\b~",$check)) || (preg_match("~\b.net\b~",$check)) || (preg_match("~\b.com\b~",$check)) || (preg_match("~\b@\b~",$check)) || (preg_match("~\b.edu\b~",$check)) || (preg_match("~\b.gov\b~",$check)))
{
exception("personal info not allowed");
redirect(base_url() . 'edit_profile');
}
</code></pre>
| 29,241 |
<p>I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.</p>
<p>The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:</p>
<pre><code><error>
<serverVariables>
<item>
<value>
</item>
</serverVariables>
<queryString>
<item name="">
<value string="">
</item>
</queryString>
</error>
</code></pre>
<p>I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a <em>Name : string</em> format.</p>
<p>Any suggestions or am I looking and a custom implementation?</p>
<p>[EDIT] A section of the data that needs to be displayed:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404">
<serverVariables>
<item name="ALL_HTTP">
<value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " />
</item>
<item name="AUTH_TYPE">
<value string="" />
</item>
<item name="HTTPS">
<value string="off" />
</item>
<item name="HTTPS_KEYSIZE">
<value string="" />
</item>
<item name="HTTP_USER_AGENT">
<value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" />
</item>
</serverVariables>
<queryString>
<item name="tid">
<value string="196" />
</item>
</queryString>
</error>
</code></pre>
| <p>You can transform your XML data using <a href="http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html" rel="nofollow noreferrer">XSLT</a><br>
Another option is to use XLinq.<br>
If you want concrete code example provide us with sample data</p>
<p><strong>EDIT</strong>:
here is a sample XSLT transform for your XML file: </p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="//error/serverVariables">
<xsl:text>Server variables:
</xsl:text>
<xsl:for-each select="item">
<xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
<xsl:template match="//error/queryString">
<xsl:text>Query string items:
</xsl:text>
<xsl:for-each select="item">
<xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>You can apply this transform using <a href="http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx" rel="nofollow noreferrer">XslCompiledTransform</a> class.
It should give output like this:</p>
<blockquote>
<p>Server variables:<br>
ALL_HTTP:HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1)<br>
AUTH_TYPE:<br>
HTTPS:off<br>
HTTPS_KEYSIZE:<br>
HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S ) </p>
<p>Query string items:<br>
tid:196 </p>
</blockquote>
| <p>You could try using the <code>DataGridView</code> control. To see an example, load an XML file in DevStudio and then right-click on the XML and select "View Data Grid". You'll need to read the API documentation on the control to use it.</p>
| 5,836 |
<p>Is there a way to easily convert Crystal Reports reports to Reporting Services RDL format?
We have quite a few reports that will be needing conversion soon.</p>
<p>I know about the manual process (which is basically rebuilding all your reports from scratch in SSRS), but my searches pointed to a few possibilities with automatic conversion "acceleration" with several consulting firms. (As described on .... - link broken).</p>
<p>Do any of you have any valid experiences or recomendations regarding this particular issue?
Are there any tools around that I do not know about?</p>
| <p>I have searched previously for this, with no luck. There does not seem to be any tools available for this conversion, the manual method thereby becomes the only method. And yes, there are consulting firms who will do the manual work for you, but they still do it manually.</p>
<p>Crystal Reports and Reporting Services have different architectural styles, making it a difficult task for a conversion tool, so I view it as unlikely that someone will build one anytime soon.</p>
| <p>As suggested by <a href="https://msdn.microsoft.com/en-us/library/aa964127(SQL.90).aspx" rel="nofollow noreferrer">Microsoft</a> you may try any of the following migration tools for SAP Crystal Reports to SSRS conversion:</p>
<ol>
<li>Hitachi Consulting <a href="http://www.hitachiconsulting.com/page.cfm?ID=bi" rel="nofollow noreferrer">http://www.hitachiconsulting.com/page.cfm?ID=bi</a></li>
<li>TCS <a href="http://www.tcs.com/Microsoft2005Launch/download/Microsoft_Recast.pdf" rel="nofollow noreferrer">http://www.tcs.com/Microsoft2005Launch/download/Microsoft_Recast.pdf</a></li>
<li>Sonata Software Ltd. <a href="http://microsoftcc.sonata-software.com/html/mcc_bi.htm" rel="nofollow noreferrer">http://microsoftcc.sonata-software.com/html/mcc_bi.htm</a></li>
<li>KTL Solutions <a href="http://www.ktlsolutions.com/t-crystalconverter.aspx" rel="nofollow noreferrer">http://www.ktlsolutions.com/t-crystalconverter.aspx</a></li>
<li>90DegreeSoftware <a href="http://www.90degreesoftware.com" rel="nofollow noreferrer">http://www.90degreesoftware.com</a></li>
<li>Jeff-Net <a href="http://www.rpttosql.com/index.html" rel="nofollow noreferrer">http://www.rpttosql.com/index.html</a></li>
<li>Neudesic <a href="http://www.neudesic.com" rel="nofollow noreferrer">http://www.neudesic.com</a></li>
<li>PLUS-IT <a href="http://www.plus-it.de" rel="nofollow noreferrer">http://www.plus-it.de</a></li>
</ol>
| 3,708 |
<p>What does "Overloaded"/"Overload" mean in regards to programming?</p>
| <p>It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:</p>
<pre><code>void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
</code></pre>
| <p>Just like in common usage, it refers to something (in this case, a method name), doing more than one job.</p>
| 36,952 |
<p>My team developed a GUI application on Visual Studio 2005, managed C++. Since some deliveries it is not possible to open the form in the designer, even if the source code and the project settings have not been changed. The designer reports this error: </p>
<p><strong>Exception of type 'System.OutOfMemoryException' was thrown.</strong> </p>
<p><em>at Microsoft.VisualStudio.Design.VSDynamicTypeService.ShadowCopyAssembly(String fileName)
at Microsoft.VisualStudio.Design.VSDynamicTypeService.CreateDynamicAssembly(String codeBase)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_Assembly()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.Search(String fullName, String typeName, Boolean ignoreTypeCase, Assembly& assembly, String description)
...</em></p>
<p>We successfully recompiled the project but we still encounter this problem.
Any idea?</p>
| <p>This is how I used to debug these issues, Start a second instance of visual studio, load your project and attach to the first instance which also has the project loaded. Now set a breakpoint in the constructor and Page Load events and also any custom paint events that you may have in the form in the second instance and try to open the designer in the first instance, the breakpoints should get hit and you should be able to see what's going on.</p>
| <p>This is a long shot, but try closing and opening the designer several times in a row. I have had the same kinds of problems with the C# Windows Forms designer (VS2005) : the form usually ended up opening correctly (after 5 tries, quite consistently).</p>
| 19,540 |
<p>I've been hearing a lot about about how the new version of VMWare Fusion can run virtual operating systems in "headless mode". </p>
<p>A Google search makes it clear that other virtualisation products also have similar features, however, I have not been able to find a good description of what this actually means? What is happening when you do this?</p>
| <p>Headless mode means that the virtual machine is running in the background without any foreground elements visible (like the Vmware Fusion application)<br>
You would have no screen to see running the front end; i.e. the screen/console would not be visible, even though the operating system is running, and would typically have to access the machine via SSH.</p>
| <p>For anyone that is interested, you can activate headless mode in VMWare Fusion by running the following command in Terminal.app</p>
<pre><code>defaults write com.vmware.fusion fluxCapacitor -bool YES
</code></pre>
| 20,730 |