instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.</p>
<p><strong>included.xhtml</strong> </p>
<pre><code><ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
</code></pre>
<p><strong>example_containing.xhtml</strong></p>
<pre><code><h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
</code></pre>
<p>How may I determine the ID of the form in the <code>update</code> method at runtime? Or better yet, the ID of the input field directly.</p>
|
<p>Bind the button to your backing bean, then use getParent() until you find the nearest form.</p>
|
<p>Programmatically I would use jsight's method. You can know the id of your elements (unless you let JSF create them, I don't know the means for numbering in the ids) by looking at it. h:form is a naming container so as long as you don't have it wrapped in another naming container it will be containingForm:containedfield The ':' is the naming separator by default is JSF and the ids are created like this, roughly anyway, (parentNamingContainerId:)*componentId</p>
| 14,971
|
<p>I have an application that was developed for Linux x86 32 bits. There are lots of floating-point operations and a lot of tests depending on the results. Now we are porting it to x86_64, but the test results are different in this architecture. We don't want to keep a separate set of results for each architecture.</p>
<p>According to the article <em><a href="http://www.network-theory.co.uk/docs/gccintro/gccintro_70.html" rel="nofollow noreferrer">An Introduction to GCC - for the GNU compilers gcc and g++</a></em> the problem is that GCC in X86_64 assumes <strong>fpmath=sse</strong> while x86 assumes <strong>fpmath=387</strong>. The 387 FPU uses <strong>80 bit internal precision</strong> for all operations and only convert the result to a given floating-point type (float, double or long double) while SSE uses the type of the operands to determine its internal precision.</p>
<p>I can <strong>force -mfpmath=387</strong> when compiling my own code and all my operations work correctly, but whenever I call some library function (sin, cos, atan2, etc.) the results are wrong again. I assume it's because <strong>libm</strong> was compiled without the fpmath override.</p>
<p>I tried to build libm myself (glibc) using 387 emulation, but it caused a lot of crashes all around (don't know if I did something wrong).</p>
<p>Is there a way to force all code in a process to use the 387 emulation in x86_64? Or maybe some library that returns the same values as libm does on both architectures? Any suggestions?</p>
<p>Regarding the question of "Do you need the 80 bit precision", I have to say that this is not a problem for an individual operation. In this simple case the difference is really small and makes no difference. When compounding a lot of operations, though, the error propagates and the difference in the final result is not so small any more and makes a difference. So I guess I need the 80 bit precision.</p>
|
<p>I'd say you need to fix your tests. You're generally setting yourself up for disappointment if you assume floating point math to be accurate. Instead of testing for <em>exact</em> equality, test whether it's close enough to the expected result. What you've found isn't a bug, after all, so if your tests report errors, <em>the tests</em> are wrong. ;)</p>
<p>As you've found out, every library you rely on is going to assume SSE floating point, so unless you plan to compile <em>everything</em> manually, now and forever, just so you can set the FP mode to x87, you're better off dealing with the problem now, and just accepting that FP math is not 100% accurate, and will not in general yield the same result on two different platforms. (I believe AMD CPU's yield slightly different results in x87 math as well).</p>
<p>Do you absolutely <em>need</em> 80-bit precision? (If so, there obviously aren't many alternatives, other than to compile <em>everything</em> yourself to use 80-bit FP.)</p>
<p>Otherwise, adjust your tests to perform comparisons and equality tests within some small epsilon. If the difference is smaller than that epsilon, the values are considered equal.</p>
|
<p>SSE floating point and 387 floating point use entirely different instructions, and so there's no way to convince SSE fp instructions to use the 387. Probably the best way to deal with this is resign your test suite to getting slightly different results, and not depend on results being the same to the last bit.</p>
| 41,777
|
<p>I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.</p>
<p>What has become increasingly frustrating is obtaining references to other movie clips and objects. For example, currently my code to access the submit button of a form looks something like this</p>
<pre><code>var b:Button = _level0.instance4.submitBtn;
</code></pre>
<p>I was hoping there was an instance-retrieval method for AS2 similar to AS3's <code>MovieClip.getChildByName()</code> or even Javascript's <code>document.getElementById()</code>. Because hard-coding the names of these anonymous instances (like <code>instance4</code> in the above) just feel really, really dirty.</p>
<p>But, I can't find anything of the sort at <a href="http://flash-reference.icod.de/" rel="nofollow noreferrer">this AS2 Reference</a>.</p>
|
<p>If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel.</p>
<p>If it was dynamically added, you can also give it a name, and additionally store a reference:</p>
<pre><code>var my_MC=createEmptyMovieClip("instanceName", depth);
</code></pre>
<p>In either case, you can then adress them with <code>_parentClip.instanceName</code> or <code>my_MC.</code></p>
|
<p>You could just write it yourself (code not tested but you get the idea):</p>
<pre><code>MovieClip.prototype.getElementByName = function(name : String) : Object
{
var s : String;
var mc : Movieclip = null;
for( s in this )
{
if( this[s] instanceof MovieClip )
{
if( s == name )
{
mc = this[ s ];
break;
}
mc = this[s].getElementByName( name );
}
}
return( mc );
}
</code></pre>
| 33,373
|
<p>I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this?</p>
<p>Thanks</p>
|
<p>Let's say you have a products table that looks like this:</p>
<pre><code>Products
----------
id
price
Products_Translations
----------------------
product_id
locale
name
description
</code></pre>
<p>Then you just join on product_id = product.id and where locale='en-US'</p>
<p>of course this has an impact on performance, since you now need a join to get the name and description, but it allows any number of locales later on. </p>
|
<p>I beleve that more information on what you are doing would be helpful. CAn you give some samples of the data? And what do you mean by dynamic? That there will be lots of data inserted over time and lots of changes to the data or that the data only needs to be available for a small period of time.</p>
| 16,138
|
<p>I want to accomplish the following scenario in Drupal:</p>
<p>You have 2 content-types. Lets say, an application-form for a lisence, and a content-type for persons.</p>
<p>Then when you go to add a lisence in the "node/add" submission form in Drupal, i would like to add a relative number of persons that would be related to this lisence, and only this lisence. Say you would like to apply for a lisence, and relate 4 persons to this lisence, then insted of creating the lisence and then create the 4 persons and relate them to the lisence, i would like to do this "inline".</p>
<p>So when i add a lisence, there would be a way to add 1 or more persons that would relate to the lisence node. Is this possible, and if so how?</p>
<p>I have been looking at the node reference module, and that manages to reference a node to another, but not to add them inline with the other.</p>
<p>With the web-development framework Django, there is a way to this with something called "inline-editing", where you get the content-type fields inside another content-type creation form. There you bind them togheter with a ForeignKey.</p>
<p>Anybody know of something simular in Drupal, if not, is it another way to achive something simular, that would be as user-friendly?</p>
|
<p>The <a href="http://drupal.org/project/popups_reference" rel="nofollow noreferrer">Popups: Add and Reference</a> module has recently been improved and I think it might do what you are looking to do.</p>
|
<p>I have looked into this, and it doesnt seem to be possible. I have looked at the reference_create module, and searched and posted stuff on drupal.org, and nobody have a nice solution.</p>
<p>So what I just rebuilt the whole thing in Django in about 3 hours; so, tomorrow I will try to convince my employer to go the Django way!</p>
| 48,215
|
<p>Is there a pretty printing function in Clojure that would output data-structures like lists and structs in a human-readable way?</p>
|
<p>clojure-contrib now has a pprint function. </p>
<p>The API documentation is at <a href="http://richhickey.github.com/clojure-contrib/pprint-api.html" rel="noreferrer">http://richhickey.github.com/clojure-contrib/pprint-api.html</a></p>
|
<p>As the others have said, planned but incomplete. When clojure.contrib.pprint is moved into clojure itself, an update will be posted to its <a href="http://www.assembla.com/spaces/clojure/tickets/20" rel="nofollow noreferrer">ticket</a>.</p>
| 37,761
|
<p>I would like to add a simple Gantt chart to my development, was wondering if you could recommend any that seem good to you. I don’t need anything really flash (I’m not trying to reproduce MS Project) just need to plot a number of projects over a 24/7 timeframe. Would appreciate your comments</p>
|
<p><a href="http://www.aditus.nu/jpgraph/features.php" rel="nofollow noreferrer">JpGraph</a> rocks. And it has a Gantt chart module.</p>
|
<p>Hi there is a good control named jSGantt purely written in javascript ,CSS,HTML and can be integrated with any language There is good tutorial based on ASP.net languge here <a href="http://codeglobe.blogspot.com/2009/04/creating-gantt-chart-in-aspnet.html" rel="nofollow noreferrer">CodeGlobe</a></p>
<p>Or you can look at jsGantt website there is a tutorial based on you preferred language PHP</p>
| 47,564
|
<p>I need to add a row to a spreadsheet using VBScript on a PC that does not have Microsoft Office installed.</p>
<p>I tried [<code>Set objExcel = CreateObject("Excel.Application")</code>]</p>
<p>Since Excel does not exist on the PC I cannot create this object.</p>
<p>Is there a way to modify a spreadsheet without Excel?</p>
|
<p>To use the code below, create an Excel workbook named "Test.xls" in the same folder as the vbscript file.</p>
<p>In Test.xls, enter the following data in cells A1 thru B4:</p>
<pre><code>First Last
Joe Smith
Mary Jones
Sam Nelson
</code></pre>
<p>Paste the vbscript code below into a .vbs file:</p>
<pre><code>Const adOpenStatic = 3
Const adLockOptimistic = 3
filename = "Test.xls"
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filename & _
";Extended Properties=Excel 8.0"
query = "Select * from [Sheet1$A1:B65535]"
Set rs = CreateObject("ADODB.Recordset")
rs.Open query, cn, adOpenStatic, adLockOptimistic
rs.AddNew
rs("First") = "George"
rs("Last") = "Washington"
rs.Update
rs.MoveFirst
Do Until rs.EOF
WScript.Echo rs.Fields("First") & " " & rs.Fields("Last")
rs.MoveNext
Loop
</code></pre>
<p>At a command prompt, type:</p>
<pre><code>CSCRIPT Yourfile.vbs
</code></pre>
<p>It will add a name to the spreadsheet and then write out all the names.</p>
<pre><code>Joe Smith
Mary Jones
Sam Nelson
George Washington
</code></pre>
|
<p>I believe the simple answer to your question is no because you need the Excel COM object which is only installed when Excel is installed. This used to be one of the real drawbacks of writing an Office app--the need for the entire application (Excel, Word or whatever) in order for an end-user to use it.</p>
| 31,585
|
<p>Is it possible to select column data using the ordinal_position for a table column? I know using ordinal positions is a bad practice but for a one-off data import process I need to be able to use the ordinal position to get the column data.</p>
<p>So for example </p>
<pre><code>create table Test(
Col1 int,
Col2 nvarchar(10)
)
</code></pre>
<p>instead of using</p>
<pre><code>select Col2 from Test
</code></pre>
<p>can I write</p>
<pre><code>select "2" from Test -- for illustration purposes only
</code></pre>
|
<p>You'd have to do something like </p>
<pre><code>declare @col1 as varchar(128)
declare @col2 as varchar(128)
declare @sq1 as varchar(8000)
select @col1 = column_name from information_schema.columns where table_name = 'tablename'
and ordinal_position = @position
select @col2 = column_name from information_schema.columns where table_name = 'tablename'
and ordinal_position = @position2
set @sql = 'select ' + col1 ',' + col2 'from tablename'
exec(@sql)
</code></pre>
|
<p>If you are using MS SQL 2005 you can use the ROW_NUMBER function.</p>
<p>SELECT Col1, Col2, ROW_NUMBER() OVER(ORDER BY Col1)
FROM Test
WHERE ROW_NUMBER() Over(Order BY Col1) Between @Position AND @Position</p>
<p>That should get you the desired results if I am reading the question correctly.</p>
| 48,112
|
<p>I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!</p>
<p>Does anyone know what it is?</p>
<p>It will do something similar to:</p>
<pre><code>const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)
</code></pre>
|
<p>You're probably thinking of <a href="http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx" rel="noreferrer"><code>AdjustWindowRectEx()</code></a>. Keep in mind, this is intended for use when <em>creating</em> a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use <a href="http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx" rel="noreferrer"><code>GetWindowRect()</code></a>.</p>
|
<p>Is this what you are looking for?</p>
<p>ClientToScreen</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx</a></p>
| 16,976
|
<p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
|
<p>Changing the decimal working precision to 2 digits is <em>not</em> a good idea, unless you absolutely only are going to perform a single operation.</p>
<p>You should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and round to the number of significant digits at each step, errors will accumulate. The decimal module doesn't know whether any particular operation is one in a long sequence, or the final result, so it assumes that it shouldn't round more than necessary. Ideally it would use infinite precision, but that is too expensive so the Python developers settled for 28 digits.</p>
<p>Once you've arrived at the final result, what you probably want is quantize:</p>
<pre>
>>> (Decimal('1.00') / Decimal('3.00')).quantize(Decimal("0.001"))
Decimal("0.333")
</pre>
<p>You have to keep track of significance manually. If you want automatic significance tracking, you should use interval arithmetic. There are some libraries available for Python, including <a href="http://pyinterval.googlecode.com/" rel="noreferrer">pyinterval</a> and <a href="http://code.google.com/p/mpmath/" rel="noreferrer">mpmath</a> (which supports arbitrary precision). It is also straightforward to implement interval arithmetic with the decimal library, since it supports directed rounding.</p>
<p>You may also want to read the <a href="http://speleotrove.com/decimal/decifaq4.html#signif" rel="noreferrer">Decimal Arithmetic FAQ: Is the decimal arithmetic ‘significance’ arithmetic?</a></p>
|
<p>If I undertand Decimal correctly, the "precision" is the number of digits after the decimal point in <em>decimal notation</em>.</p>
<p>You seem to want something else: the number of significant digits. That is one more than the number of digits after the decimal point in <em>scientific notation</em>.</p>
<p>I would be interested in learning about a Python module that does significant-digits-aware floating point point computations.</p>
| 17,394
|
<p>In a Windows program, what is the canonical way to parse the command line obtained from GetCommandLine into multiple arguments, similar to the argv array in Unix? It seems that CommandLineToArgvW does this for a Unicode command line, but I can't find a non-Unicode equivalent. Should I be using Unicode or not? If not, how do I parse the command line?</p>
|
<p>Apparently you can use <a href="https://learn.microsoft.com/lt-lt/cpp/c-runtime-library/argc-argv-wargv?view=msvc-160" rel="nofollow noreferrer"><code>__argv</code></a> outside <code>main()</code> to access the pre-parsed argument vector...</p>
|
<p>The following is about the simplest way I can think of to obtain an old-fashioned argc/argv pair at the top of WinMain. Assuming that the command-line really was ANSI text, you don't actually need any conversions fancier than this.</p>
<pre><code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
int argc;
LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &argc);
char **argv = new char*[argc];
for (int i=0; i<argc; i++) {
int lgth = wcslen(szArglist[i]);
argv[i] = new char[lgth+1];
for (int j=0; j<=lgth; j++)
argv[i][j] = char(szArglist[i][j]);
}
LocalFree(szArglist);
</code></pre>
| 37,167
|
<p>I am trying to find out how to use usercontrols in asp.net mvc. I know how to add a usercontrol to a view and how to pass data to it. What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?</p>
<p>For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?</p>
<p>I'm not sure if this makes sense or not. Is there a better or recommended way to handle an "island" of data that you want to display on several pages?</p>
<p>I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.</p>
|
<p>There are multiple ways to do it. </p>
<p>The basic approach is </p>
<ul>
<li>Populate the data for the view in the BaseController (OnActionExecuting event)</li>
<li>Writing a custom action filter</li>
<li>Writing an Application Controller (the eg. is in the below links).</li>
</ul>
<p>An example of OnActionExecuting will be </p>
<pre><code> [HandleError]
public class BaseController : Controller
{
CourseService cs = new CourseService();
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
List<Tag> tags = cs.GetTags();
ViewData["Tags"] = tags;
}
}
</code></pre>
<p>You can use the "tags" view data on any view. This is just an example of usercontrol being rendered as side content.</p>
<pre><code><div id="sidebar_b">
<asp:ContentPlaceHolder ID="ContentReferenceB" runat="server" >
<% Html.RenderPartial("Tags"); %>
</asp:ContentPlaceHolder>
</div>
</code></pre>
<p>I found the following URL to be useful.</p>
<p><a href="http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx</a></p>
<p><a href="http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx" rel="nofollow noreferrer">http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx</a></p>
<p><a href="http://www.aaronlerch.com/blog/2008/01/26/displaying-foo-on-every-page-of-an-aspnet-mvc-application/" rel="nofollow noreferrer">http://www.aaronlerch.com/blog/2008/01/26/displaying-foo-on-every-page-of-an-aspnet-mvc-application/</a></p>
<p><a href="http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/" rel="nofollow noreferrer">http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/</a></p>
|
<p>Refactor the code that obtains the view data for this user control into it's own method, maybe even it's own model (class). Call this method from each controller that needs to populate the control and pass the results in the ViewData with a well-known key. You might even want to pass the type of the current controller to your method in case it needs to know what data to retrieve based on the base model for the controller.</p>
<pre><code> ViewData["RecentPosts"] = RecentPosts.GetRecentPosts( this.GetType() );
</code></pre>
<p>In your control, retrieve the data using the well-known key.</p>
| 42,363
|
<p>I have a C++ program that when run, by default, displays the X in the upper right corner. Clicking X, minimizes the program. I've added code using the SHInitDialog function to change the X to OK, so that clicking OK exits the program.</p>
<p>My question: Is there a better method that applies to the window, since SHInitDialog works best with Dialog Boxes?</p>
|
<p>With Windows Mobile 5.0 and higher, using the CreateWindowEx function passing it WS_EX_CAPTIONOKBTN for the extended style works.</p>
<p>@ctacke SHDoneButton may have also worked but I wanted to change the main window without handling it like a dialogbox, which is basically what SHInitDialog is doing.</p>
|
<p>Not sure how it's done in C++, but in .NET if you set the MinimizeBox property to false, you get an OK button. Since .NET Windows code is fancy wrapper code, there should be a C++ equivalent</p>
| 10,037
|
<p>In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.</p>
<pre><code>for ( int i=0; i < vecVector.size(); i++ )
{
..
}
</code></pre>
<p>Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?</p>
|
<p>Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings.</p>
<h3>Genericity</h3>
<p>Iterators increase the genericity of your code.</p>
<p>For example:</p>
<pre><code>typedef std::vector<int> Container ;
void doSomething(Container & p_aC)
{
for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it)
{
int & i = *it ; // i is now a reference to the value iterated
// do something with "i"
}
}
</code></pre>
<p>Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code.</p>
<p>Should you have used index-based code instead, it would have needed to be re-written.</p>
<h3>Access</h3>
<p>The iterator should be viewed like a kind of super pointer.
It "points" to the value (or, in case of maps, to the pair of key/value).</p>
<p>But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque).</p>
<h3>Algorithms</h3>
<p>Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.</p>
|
<p>Well, for one thing the above will no longer work if you turn that vector into a list.</p>
<p>Iterators allow you to create function templates that don't need to know the type of container they work on. You can even do the following:</p>
<pre><code>#include <algorithm>
void printvalue(double s)
{
// Do something with s
}
int _tmain(int argc, _TCHAR* argv[])
{
double s[20] = {0};
std::for_each(s, s+20, printvalue);
return 0;
}
</code></pre>
<p>That's because a standard pointer is also a valid iterator for for_each.</p>
<p>Dave</p>
| 21,575
|
<p>Given a stylesheet with a fully qualified reference to an image resource on another server, is there a good way to handle promotions through different environments that require a different base URL?</p>
<blockquote>
<p>background-image: url
(evironmentSpecificURL/resourceName.foo);</p>
</blockquote>
<p>The environmentSpecificURL will vary from environment to environment and I don't want this file to be modified as it progresses from development, qa, staging, production, etc.</p>
<p>I have ideas, but am interested in how others have dealt with this -- I'll post one of my ideas.</p>
<p>Let me underscore (based on another response) that the image resource does not exist on the same server and that is the URL that will change. So relative paths do not work in that situation.</p>
<p>Also, I am trying to avoid the need to modify the css where there could be multiple instances of the URL and centralize that URL to one point of configuration.</p>
<p>any help!</p>
|
<p>The resources that you reference should really be at a relative level to your css file, that way its just a "..\resourceName.foo" away from working.</p>
<p>Of cource you could also look into build tools that auto-generate the environment specific areas of your site, so all properties such as css file, .properties files, etc... are generated dynamically via a build tool link ANT or MSBuild</p>
|
<p>My idea:</p>
<p>Develop a handler/etc locally on the web application to pull in the image and handle the change in base URL in configuration files:</p>
<blockquote>
<p>background-image: url
(localHandler.ashx(aspx)/resourceName.foo);</p>
</blockquote>
<p>Where the localHandler calls the destination resource and then returns the resource based on content type.</p>
| 22,394
|
<p>I have a ListView which sometimes I need to put around 10000 items in. ListViews don't really handle this well, and they lock up for a couple of seconds while they sort the items and draw them. If you add the items in individually, it's even worse, locking up for nearly a minute.</p>
<p>To get around this, I thought I'd try populating the ListView before I need to display it, but unfortunately it has other ideas. It only starts drawing when I turn the panel that contains the ListView visible, making the program hang for a couple of seconds.</p>
<p>Any ideas for how I can eliminate this delay? Or is there another component that's relatively easy to use that is better at showing large quantities of data?</p>
|
<p>You need to use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx" rel="nofollow noreferrer">VirtualMode</a>.</p>
|
<p>Well. If you just want to load the content in the background you could try a thread to populate the ListView, which will let the form load. </p>
<p>I don't think you will get the pause if you put an Application.DoEvents(); when you are loading the items (which allows the form to redraw and receive events). </p>
<pre><code>for (int ix=0; ix < 10000; ix ++)
{
listView1.Items.Add(ix.ToString());
Application.DoEvents();
}
</code></pre>
<p>I guess my suggestions are good if you aren't aware of VirtualMode </p>
| 15,951
|
<p>Kind of a newbie question, but I am having problems using SNVKit. </p>
<p>I am using SVNKit in an application to commit changes to files. I have it successfully adding the files and folders to the working copy, but I am having problems committing it to the respository.</p>
<p>The command I am trying to run is 'commit -m "Test Add" /svnroot/project1/' but I keep getting "svn: '/home/user' is not a working copy"</p>
<p>I have a structure similar to this:</p>
<ul>
<li>/svnroot/</li>
<li>/svnroot/project1/</li>
<li>/svnroot/project1/grouping1/</li>
<li>/svnroot/project1/grouping1/myfilesarehere</li>
</ul>
<p>If I try to commit the file, I get the following message: "'/svnroot/project1/grouping1' is not under version control and is not part of the commit, yet its child is part of the commit."</p>
<p>What might I be doing wrong?</p>
<p>EDIT: Fixed the directories.</p>
|
<p>If you have both a directory and its child added, but neither is not committed, I believe you get this message if you try to commit just the child. You need to commit the parent directory first.</p>
|
<p>It's not entirely clear because you've inconsistently replaced them, but it looks like you're getting repository paths/URLs confused with working copy paths. If you're adding or committing files, always use the working copy paths. Try playing around with the command-line svn before trying to use SVNKit.</p>
| 16,932
|
<p>Does anybody know if it is possible <strong>to choose the order of the fields</strong> in Dynamic Data (of course, without customizing the templates of each table) ?</p>
<p>Thanks !</p>
|
<p>In .NET 4.0, using the 4.0 release of the Dynamic Data dll, you can set data annotations like so:</p>
<pre><code>[Display(Name = " Mission Statement", Order = 30)]
public object MissionStatement { get; set; }
[Display(Name = "Last Mod", Order = 40)]
public object DateModified { get; private set; }
</code></pre>
|
<p>You can do this by modifying the order of the public properties in your LINQ to SQL file. </p>
<p>For example, I went into Northwind.designer.cs which was my auto-generated LINQ to SQL file and moved the public property named Products above the public property CategoryName in the public partial class Category. Then I recompiled and the default template displayed the columns in my new order.</p>
<p>Of course, this means your editing auto-generated code and if you regenerate it, your changes are lost, so this technique is not without peril.</p>
| 41,668
|
<p>Is it possible to query the Crystal CMS database and get meaningful data back? The data appears to be encrypted.</p>
<p>I am running Business Objects Crystal Report Server version 11.5</p>
|
<p>Actually what I discovered I needed to do was use the administration tools available from the Administration Launchpad. I was not responsible for installing Crystal and did not even realise this existed. The query builder and also the "Report Datasources" feature that were available from here was exactly what I needed.</p>
|
<p>My experience is that the data is not encrypted but that it is not really readable. Your best option is to use the Auditor Universes to build you some reports. You can also check out the SQL that the auditor Universes are uses as a baseline for constructing additional reporting.</p>
| 9,471
|
<p>I'm looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also just use an unsorted container and explicitly sort it after each insert.</p>
<p>Usage:</p>
<ul>
<li>Occasional insert</li>
<li>Frequent traversal in order</li>
<li>Ideally not working with keys separate from the actual object, using a compare function to sort.</li>
<li>Stable sorting for equivalent objects is desired, but not required. </li>
<li>Random access is not required.</li>
</ul>
<p>I realize I can just build myself a balanced tree structure, I was just wondering if the framework already contains such a beast.</p>
|
<p>You might want to take a look at the <a href="http://www.codeplex.com/PowerCollections" rel="noreferrer">Wintellect Power Collections</a>. It is available on CodePlex and contains quite a few collections that are very helpful. The OrderedBag collection in the project is exactly what you are looking for. It essentially uses a <a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="noreferrer">red-black tree</a> to provide a pretty efficient sort.</p>
|
<p>If the key is also an attribute of the object, you might try the <code>System.Collections.ObjectModel.KeyedCollection<TKey, TItem></code>. It's an abstract class, but if your key is just a property of the item then it's real simple to derive from.</p>
| 23,874
|
<p>Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework.</p>
<p>The largest issue I've found is it can be confusing for other developers who are just learning it.</p>
<p>Also, I'd feel much better if it were a part of the language I was using. Though, for Java at least, there are a couple very lightweight libraries which are quite good.</p>
<p>Thoughts? Bad experiences? Or just stop worrying about it?</p>
<hr>
<p>[EDIT] Re: Description of Dependency Injection itself</p>
<p>Sorry for being vague. <a href="http://www.martinfowler.com/articles/injection.html" rel="noreferrer">Martin Fowler</a> probably describes it FAR better than I ever could... no need to waste the effort. </p>
<p>Coincidentally, this confirms one point about it, that it's still not widely practiced and might tend to be a barrier when working with teams if everyone is not up to speed on it. </p>
|
<p>I've taken a stab at describing some of the possible downsides in a blog post here: <a href="http://kevin-berridge.blogspot.com/2008/06/ioc-and-di-complexity.html" rel="noreferrer">http://kevin-berridge.blogspot.com/2008/06/ioc-and-di-complexity.html</a></p>
|
<p>@Blorgbeard: <a href="http://www.martinfowler.com/articles/injection.html" rel="nofollow noreferrer">http://www.martinfowler.com/articles/injection.html</a> is probably one of the best articles on the subject</p>
| 6,426
|
<p>I'm trying to figure out a way to add a self-update feature to a Java/Swing application I'm working on.</p>
<p>Basically I've got a bunch of jar files with extra functionality to be re-deployed to the installed users when they change. Nothing complicated, just check if a new version has been released, download them over HTTP, and then optionally offer to restart the app to the user.</p>
<p>I had a look at webstart, and it could work. But this particular app does some funky stuff with classloading and GC memory settings that don't look like they are supported via webstart, or will at least complicate matters. (It's a tweaked build of JMeter)</p>
<p>I also went down the road of adding in this plugin handler <a href="http://swing-fx.blogspot.com/2008/06/add-auto-update-and-plugins-to-your.html" rel="noreferrer">http://swing-fx.blogspot.com/2008/06/add-auto-update-and-plugins-to-your.html</a>, but it is very alpha, and tries to do too much with the usual bugs you get with alpha stuff.</p>
|
<p>I did the exact same thing. But that was long back so there are probably better tools today.</p>
<p>What I found out I needed was a loader. The loader main program did not have the app jars in classpath. It first downloaded an update if required and then created a custom classloader with the app jars in class path and invoked the main method of the application main class. It is not very complicated. IIRC I needed to do this because the jars could not be overwritten in windows if they were already in classpath.</p>
<p>Hope this helps. </p>
|
<p>I believe you should look again at Java WebStart, or at least detail the "funky classloading" which you think is going to cause problems (as it might also cause problems with any solution proposed here).</p>
<p>IIRC, you can set command line parameters using Java WebStart ( <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/syntax.html#resources" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/syntax.html#resources</a> ).</p>
| 25,433
|
<p>I need debug some old code that uses a Hashtable to store response from various threads.</p>
<p>I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.</p>
<p>How can this be done?</p>
|
<pre><code>foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
</code></pre>
|
<p>This should work for pretty much every version of the framework...</p>
<pre><code>foreach (string HashKey in TargetHash.Keys)
{
Console.WriteLine("Key: " + HashKey + " Value: " + TargetHash[HashKey]);
}
</code></pre>
<p>The trick is that you can get a list/collection of the keys (or the values) of a given hash to iterate through.</p>
<p>EDIT: Wow, you try to pretty your code a little and next thing ya know there 5 answers... 8^D</p>
| 5,525
|
<p><a href="http://www.w3.org/TR/REC-html40/interact/scripts.html" rel="noreferrer"><strong>According to spec</strong></a>, only the <code>BODY</code> and <code>FRAMESET</code> elements provide an "onload" event to attach to, but I would like to know when a dynamically-created DOM element has been added to the DOM in JavaScript.</p>
<p>The super-naive heuristics I am currently using, which work, are as follows:</p>
<ul>
<li>Traverse the <strong>parentNode</strong> property of the element back until I find the ultimate ancestor (i.e. parentNode.parentNode.parentNode.etc until parentNode is null)<br /><br /></li>
<li>If the ultimate ancestor has a defined, non-null <strong>body</strong> property<br /><br />
<ul>
<li>assume the element in question is part of the dom</li>
</ul></li>
<li>else<br /><br />
<ul>
<li>repeat these steps again in 100 milliseconds</li>
</ul></li>
</ul>
<p>What I am after is either confirmation that what I am doing is sufficient (again, it is working in both IE7 and FF3) or a better solution that, for whatever reason, I have been completely oblivious to; perhaps other properties I should be checking, etc.</p>
<hr>
<p>EDIT: I want a browser-agnostic way of doing this, I don't live in a one-browser world, unfortunately; that said, browser-specific information is appreciated, but please note which browser you know that it <em>does</em> work in. Thanks!</p>
|
<p>UPDATE: For anyone interested in it, here is the implementation I finally used:</p>
<pre><code>function isInDOMTree(node) {
// If the farthest-back ancestor of our node has a "body"
// property (that node would be the document itself),
// we assume it is in the page's DOM tree.
return !!(findUltimateAncestor(node).body);
}
function findUltimateAncestor(node) {
// Walk up the DOM tree until we are at the top (parentNode
// will return null at that point).
// NOTE: this will return the same node that was passed in
// if it has no ancestors.
var ancestor = node;
while(ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
return ancestor;
}
</code></pre>
<p>The reason I wanted this is to provide a way of synthesizing the <code>onload</code> event for DOM elements. Here is that function (although I am using something slightly different because I am using it in conjunction with <a href="http://www.mochikit.com/" rel="nofollow noreferrer"><strong>MochiKit</strong></a>):</p>
<pre><code>function executeOnLoad(node, func) {
// This function will check, every tenth of a second, to see if
// our element is a part of the DOM tree - as soon as we know
// that it is, we execute the provided function.
if(isInDOMTree(node)) {
func();
} else {
setTimeout(function() { executeOnLoad(node, func); }, 100);
}
}
</code></pre>
<p>For an example, this setup could be used as follows:</p>
<pre><code>var mySpan = document.createElement("span");
mySpan.innerHTML = "Hello world!";
executeOnLoad(mySpan, function(node) {
alert('Added to DOM tree. ' + node.innerHTML);
});
// now, at some point later in code, this
// node would be appended to the document
document.body.appendChild(mySpan);
// sometime after this is executed, but no more than 100 ms after,
// the anonymous function I passed to executeOnLoad() would execute
</code></pre>
<p>Hope that is useful to someone.</p>
<p>NOTE: the reason I ended up with this solution rather than <a href="https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224"><strong>Darryl's answer</strong></a> was because the getElementById technique only works if you are within the same document; I have some iframes on a page and the pages communicate between each other in some complex ways - when I tried this, the problem was that it couldn't find the element because it was part of a different document than the code it was executing in.</p>
|
<p>Neither of <strong>DOMNodeInserted</strong> or <strong>DOMNodeInsertedIntoDocument</strong> events is supported in IE. Another missing from IE [only] feature of DOM is <strong>compareDocumentPosition</strong> function that is designed to do what its name suggests. </p>
<p>As for the suggested solution, I think there is no better one (unless you do some dirty tricks like overwriting native DOM members implementations)</p>
<p>Also, correcting the title of the question: dynamically created Element is part of the DOM from the moment it is created, it can be appended to a document fragment, or to another element, but it might not be appended to a document.</p>
<p>I also think that the problem you described is not the problem that you have, this one looks to be rather one of the potential solutions to you problem. Can you probably explain in details the use case?</p>
| 27,111
|
<p>In my web app, I submit some form fields with jQuery's <code>$.getJSON()</code> method. I am having some problems with the encoding. The character-set of my app is <code>charset=ISO-8859-1</code>, but I think these fields are submitted with <code>UTF-8</code>. </p>
<p>How I can set encoding used in <code>$.getJSON</code> calls? </p>
|
<p>I think that you'll probably have to use <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer"><code>$.ajax()</code></a> if you want to change the encoding, see the <code>contentType</code> param below (the <code>success</code> and <code>error</code> callbacks assume you have <code><div id="success"></div></code> and <code><div id="error"></div></code> in the html):</p>
<pre><code>$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
</code></pre>
<p>I actually just had to do this about an hour ago, what a coincidence!</p>
|
<p>Use this function to regain the utf-8 characters</p>
<pre><code>function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
</code></pre>
<p>Example:
var new_Str=decode_utf8(str);</p>
| 4,617
|
<p>I'm using the ProgressBar control in a WPF application and I'm getting this old, Windows 3.1 Progress<em>Blocks</em> thing. In VB6, there was a property to show a <em>smooth</em> ProgressBar. Is there such a thing for WPF?</p>
|
<p><a href="http://support.microsoft.com/kb/323116" rel="nofollow noreferrer">This</a> KB article seems to explain what you are looking for... there is a link to a VB version of the article too.</p>
|
<p>I am not sure what you want to do.
If you simply want a progress bar that "sweeps" from side to side like on starting Vista you could use: IsIndetermined = true.</p>
<p>If you actually want to go from 0% to 100% you have to either animate over the value as shown in this example on msdn: <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.progressbar.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.controls.progressbar.aspx</a>
or set the value explicitly either in code-behind (most likely from a background worker) or through a binding to a changing value.</p>
<p>Nevertheless the WPF ProgressBar should always be "smooth", there is the possibility that the UI will default to a more simpler version through a RemoteDesktop connection.</p>
| 10,808
|
<p>I am not familiar with this website but I am desperately seeking help with the website I am building. I'm sorry if I'm not in the right place or asking my question incorrectly, so please tell me if I do something wrong!</p>
<p>I have built a simple website, consisting of four pages (index.html plus three others). In FF everything seems to work fine, but in IE it doesn't. I know there are a lot of similar problems, but after hours of searching I cannot find a solution. I have a sidebar on the left, which in FF appears in place, but in IE comes up below the content. The strange thing is that on the fourth page it does work, so I'm lost as to if it is a css or html error on my account. For the time being the website is to be found at <a href="http://www.kids2move.nl/djctapas" rel="nofollow noreferrer">http://www.kids2move.nl/djctapas</a></p>
<p>I hope there is anyone out there that sees what I have done wrong and how I can fix it. I will check this page regularly so I can add additional information if needed, like my css-file or the htmlcode. Thanks in advance!!</p>
|
<p>Why don't you put the sidebar div into the page div?</p>
|
<p>You currently have: </p>
<pre><code><div id=page>
<div id=content></div>
</div>
<div id=sidebar></div>
</code></pre>
<p>I think:</p>
<pre><code><div id=page>
<div id=sidebar></div>
<div id=content></div>
</div>
</code></pre>
<p>would make much more sense layout-wise and may possibly fix your problem. If not, play around with position: absolute; of the sidebar div and margin-left of the content div in the CSS.</p>
| 40,521
|
<p>What is the best way to sync up two lists each of which may contain items not in the other? As shown the lists are not sorted - although if necessary sorting them first would not be an issue.</p>
<pre><code>List 1 = a,b,c,e
List 2 = b,e,c,d
</code></pre>
<p>Using the lists above, I'm looking for a solution that will write out to a spreadsheet in two columns:</p>
<pre><code>a
b b
c c
d
e e
</code></pre>
|
<p>Here are some notes on using a disconnected recordset.</p>
<pre><code>Const adVarChar = 200 'the SQL datatype is varchar
'Create arrays fron the lists
asL1 = Split("a,b,c,", ",")
asL2 = Split("b,e,c,d", ",")
'Create a disconnected recordset
Set rs = CreateObject("ADODB.RECORDSET")
rs.Fields.append "Srt", adVarChar, 25
rs.Fields.append "L1", adVarChar, 25
rs.Fields.append "L2", adVarChar, 25
rs.CursorType = adOpenStatic
rs.Open
'Add list 1 to the recordset
For i = 0 To UBound(asL1)
rs.AddNew Array("Srt", "L1"), Array(asL1(i), asL1(i))
rs.Update
Next
'Add list 2
For i = 0 To UBound(asL2)
rs.MoveFirst
rs.Find "L1='" & asL2(i) & "'"
If rs.EOF Then
rs.AddNew Array("Srt", "L2"), Array(asL2(i), asL2(i))
Else
rs.Fields("L2") = asL2(i)
End If
rs.Update
Next
rs.Sort = "Srt"
'Add the data to the active sheet
Set wks = Application.ActiveWorkbook.ActiveSheet
rs.MoveFirst
intRow = 1
Do
For intField = 1 To rs.Fields.Count - 1
wks.Cells(intRow, intField + 1) = rs.Fields(intField).Value
Next intField
rs.MoveNext
intRow = intRow + 1
Loop Until rs.EOF = True
</code></pre>
|
<p>Another option is Collections. This doesn't sort the output alphabetically, but you can sort the lists first if you need to. Note this will also give you a unique list,stripping out duplicates. The code assumes your lists are in string arrays L1 and L2.</p>
<pre><code>Dim C As New Collection,i As Long, j As Long
ReDim LL(UBound(L1) + UBound(L2), 2) As String 'output array
For i = 1 To UBound(L1)
On Error Resume Next 'try adding to collection
C.Add C.Count + 1, L1(i) 'store sequence number,ie 1,2,3,4,...
On Error GoTo 0
j = C(L1(i)) 'look up sequence number
LL(j, 1) = L1(i)
Next i
For i = 1 To UBound(L2) 'same for L2
On Error Resume Next
C.Add C.Count + 1, L2(i)
On Error GoTo 0
j = C(L2(i))
LL(j, 2) = L2(i)
Next i
'Result is in LL, number of rows is C.Count
Range("Results").Resize(UBound(LL, 1), 2) = LL
</code></pre>
| 28,080
|
<p>I keep seeing the phrase "duck typing" bandied about, and even ran across a code example or two. I am way too <strike>lazy</strike> busy to do my own research, can someone tell me, briefly:</p>
<ul>
<li>the difference between a 'duck type' and an old-skool 'variant type', and </li>
<li>provide an example of where I might prefer duck typing over variant typing, and</li>
<li>provide an example of something that i would <em>have</em> to use duck typing to accomplish?</li>
</ul>
<p><img src="https://regmedia.co.uk/2007/05/03/cartoon_duck.jpg" alt="duck typing illustration courtesy of The Register"></p>
<p>I don't mean to seem fowl by doubting the power of this 'new' construct, and I'm not ducking the issue by refusing to do the research, but I am quacking up at all the flocking hype i've been seeing about it lately. It looks like <em>no</em> typing (aka dynamic typing) to me, so I'm not seeing the advantages right away.</p>
<p>ADDENDUM: Thanks for the examples so far. It seems to me that using something like 'O->can(Blah)' is equivalent to doing a reflection lookup (which is probably not cheap), and/or is about the same as saying (O is IBlah) which the compiler might be able to check for you, but the latter has the advantage of distinguishing my IBlah interface from your IBlah interface while the other two do not. Granted, having a lot of tiny interfaces floating around for every method would get messy, but then again so can checking for a lot of individual methods...</p>
<p>...so again i'm just not getting it. Is it a fantastic time-saver, or the same old thing in a brand new sack? Where is the example that <em>requires</em> duck typing?</p>
|
<p>The simple answer is variant is weakly typed while duck typing is strongly typed. </p>
<p>Duck typing can be summed up nicely as "if it walks like a duck, looks like a duck, acts like a duck, then it's a duck." It computer science terms consider duck to be the following interface.</p>
<pre><code>interface IDuck {
void Quack();
}
</code></pre>
<p>Now let's examine Daffy</p>
<pre><code>class Daffy {
void Quack() {
Console.WriteLine("Thatsssss dispicable!!!!");
}
}
</code></pre>
<p>Daffy is not actually an IDuck in this case. Yet it acts just like a Duck. Why make Daffy implement IDuck when it's quite obvious that Daffy is in fact a duck. </p>
<p>This is where Duck typing comes in. It allows a type safe conversion between any type that has all of the behaviors of a IDuck and an IDuck reference.</p>
<pre><code>IDuck d = new Daffy();
d.Quack();
</code></pre>
<p>The Quack method can now be called on "d" with complete type safety. There is no chance of a runtime type error in this assignment or method call. </p>
|
<p>Everything you can do with duck-typing you can also do with interfaces. Duck-typing is fast and comfortable, but some argue it can lead to errors (if two distinct methods/properties are named alike). Interfaces are safe and explicit, but people might say "why state the obvious?". Rest is a flame. Everyone chooses what suits him and no one is "right". </p>
| 36,818
|
<p>The following works in Firefox, but breaks in IE7 & 8:</p>
<pre><code>$("#my-first-div, #my-second-div").hide();
</code></pre>
<p>so I have to do this:</p>
<pre><code>$("#my-first-div").hide();
$("#my-second-div").hide();
</code></pre>
<p>Is this normal?</p>
<p>EDIT: ok, my actual real-life code is this:</p>
<pre><code>$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html(html);
</code></pre>
<p>and my error is this</p>
<pre><code>( IE8): Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
</code></pre>
|
<p>The location you specify states:</p>
<pre><code>Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
</code></pre>
<p>That particular piece of jquery is:</p>
<pre><code>nodeName:function(elem,name){
return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();
}
</code></pre>
<p>which is itself a closure created for the call to <code>jQuery.extend()</code>. So I would like to ask, if you do a "View source" or its IE equivalent, are there any other occurrences of the string "nodeName" that could be interfering with the jQuery one.</p>
<p>Can you also test the following by creating an xx.html file and opeing it in IE7/8? It works fine under Firefox 3 in Ubuntu, with or without the spaces following the commas in the selector.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html("xx")
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<hr>
<div id="charges-gsm">CHARGES-GSM</div>
<div id="charges-gsm-faq">CHARGES-GSM-FAQ</div>
<div id="charges-gsm-prices">CHARGES-GSM-PRICES</div>
</body>
</html>
</code></pre>
|
<p>Have you tried it without a space after the comma? <a href="http://docs.jquery.com/Selectors/multiple#selector1selector2selectorN" rel="nofollow noreferrer">The examples given in the specification have no space.</a></p>
| 22,620
|
<p>Things like <code>$log$</code> and <code>$version$</code> which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.</p>
|
<p>Both Subversion and CVS call them <code>Keywords</code>.</p>
<p><a href="http://svnbook.red-bean.com/en/1.0/ch07s02.html#svn-ch-7-sect-2.3" rel="nofollow noreferrer">Have a look in the SVN manual here</a> (scroll down to <strong>svn:keywords</strong>) or <a href="http://badgertronics.com/writings/cvs/keywords.html" rel="nofollow noreferrer">here for CVS</a>.</p>
|
<p>These are Keyword substitutions. The link to SVNBook 1.8 is here: <a href="http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html" rel="nofollow noreferrer" title="Subversion Keywords">http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html</a>.</p>
<p>Subversion's built-in keywords are:</p>
<ul>
<li>Date / LastChangedDate</li>
<li>Revision / Rev / LastChangedRevision</li>
<li>Author / LastChangedBy</li>
<li>HeadURL / URL</li>
<li>Id</li>
</ul>
<p>The keywords are case sensitive, and remember to surround them with $.</p>
| 6,092
|
<p>In firefox, the error messages display as should. Just to the right of the element being validated. In IE. No matter what I do with the sizing of the labels/elements/errors, the error is always posted below the element, causing every other element to be pushed down.</p>
<pre><code><p>
<label for="handle"><strong>User Name</strong></label>
<INPUT NAME="handle" id="handle" VALUE="#attributes.getUser.handle#">
</p>
<p>
<label for="password"><strong>Password</strong></label>
<INPUT TYPE="TEXT" id="password" NAME="password"
MAXLENGTH=50 VALUE="#attributes.getUser.password#">
</p>
<p>
<label for="confirmPassword"><strong>Confirm Password</strong></label>
<INPUT TYPE="TEXT" id="confirmPassword" NAME="confirmPassword"
MAXLENGTH=50 VALUE="#attributes.getUser.password#">
</p>
</code></pre>
<p>If anyone else has had this issue, i'd be very grateful for any help.</p>
|
<p>One approach for Oracle:</p>
<pre><code>SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)
</code></pre>
<p>Or alternatively in Oracle:</p>
<pre><code>SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable
</code></pre>
<p>Or alternatively in SqlServer:</p>
<pre><code>SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable
</code></pre>
<p>These use the fact that <code>MIN()</code> returns <code>NULL</code> when there are no rows.</p>
|
<p>Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.</p>
<pre><code> ---=== The table & its data
CREATE TABLE dbo.Rates (
PkId int,
name varchar(10),
rate decimal(10,2)
)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)
</code></pre>
<p>Here's the solution:</p>
<pre><code>---=== The solution
CREATE PROCEDURE dbo.GetRate
@PkId int
AS
BEGIN
DECLARE @tempTable TABLE (
PkId int,
name varchar(10),
rate decimal(10,2)
)
--- [1] Insert default values into @tempTable. PkId=0 is dummy value
INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)
--- [2] Update the single row in @tempTable with the actual value.
--- This only happens if a match is found
UPDATE @tempTable
SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
FROM @tempTable t INNER JOIN dbo.Rates x
ON t.PkId = 0
WHERE x.PkId = @PkId
SELECT * FROM @tempTable
END
</code></pre>
<p>Test the code:</p>
<pre><code>EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1
EXEC dbo.GetRate @PkId=12314 --- returns default values
</code></pre>
| 36,280
|
<p>Emacs puts backup files named <code>foo~</code> everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful. How can I either eliminate these backup files, or have them go somewhere other than the same directory?</p>
|
<p>If you've ever been saved by an Emacs backup file, you
probably want more of them, not less of them. It is annoying
that they go in the same directory as the file you're editing,
but that is easy to change. You can make all backup files go
into a directory by putting something like the following in your
<code>.emacs</code>.</p>
<pre class="lang-lisp prettyprint-override"><code>(setq backup-directory-alist `(("." . "~/.saves")))
</code></pre>
<p>There are a number of arcane details associated with how Emacs
might create your backup files. Should it rename the original
and write out the edited buffer? What if the original is linked?
In general, the safest but slowest bet is to always make backups
by copying.</p>
<pre class="lang-lisp prettyprint-override"><code>(setq backup-by-copying t)
</code></pre>
<p>If that's too slow for some reason you might also have a look at
<code>backup-by-copying-when-linked</code>.</p>
<p>Since your backups are all in their own place now, you might want
more of them, rather than less of them. Have a look at the Emacs
documentation for these variables (with <code>C-h v</code>).</p>
<pre class="lang-lisp prettyprint-override"><code>(setq delete-old-versions t
kept-new-versions 6
kept-old-versions 2
version-control t)
</code></pre>
<p>Finally, if you absolutely must have no backup files:</p>
<pre class="lang-lisp prettyprint-override"><code>(setq make-backup-files nil)
</code></pre>
<p>It makes me sick to think of it though.</p>
|
<p><code>(setq delete-auto-save-files t)</code></p>
<p>deletes buffer's auto save file when it is saved or when killed with no changes in it. thus you still get some of the safety of auto save files, since they are only left around when a buffer is killed with unsaved changes or if emacs exits unexpectedly. if you want to do this, but really need history on some of your files, consider putting them under source control.</p>
| 18,316
|
<p>Has anybody seen such a thing? Small self-sufficient modules are preferred.</p>
|
<p>The <a href="http://docs.python.org/library/fractions.html" rel="nofollow noreferrer">fractions module</a> from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules. </p>
<p>You can get the single files from here (2.6 branch, 2.7 does not work):
<a href="http://hg.python.org/cpython/branches" rel="nofollow noreferrer">http://hg.python.org/cpython/branches</a></p>
|
<p>One more thing to try is <a href="http://svn.python.org/view/python/branches/release25-maint/Demo/classes/Rat.py?rev=51333&view=markup" rel="nofollow noreferrer">Rat.py</a> from demo folder in Python 2.5 maintenance branch. If i understand correctly, it is the daddy of 2.6 <code>fractions</code>. It's a single module without dependencies.</p>
<pre><code>>>> from Rat import rat
>>> rat(1) / rat(3)
Rat(1,3)
>>> rat(1, 3) ** 2
Rat(1,9)
</code></pre>
<p><strong>UPDATE</strong>: Nah, <code>fractions.py</code> is about 2.5 times faster for my task.</p>
| 42,674
|
<p>I have a structure in C#:</p>
<pre><code>public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
}
</code></pre>
<p>The only rule is that <code>UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))</code></p>
<p>How to override the GetHashCode function for this structure? </p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">MSDN</a>:</p>
<p>A hash function must have the following properties:</p>
<blockquote>
<ul>
<li>If two objects compare as equal, the <code>GetHashCode</code> method for each object must return the same value. However, if two objects do not compare as equal, the <code>GetHashCode</code> methods for the two object do not have to return different values.</li>
<li>The <code>GetHashCode</code> method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's <code>Equals</code> method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.</li>
<li>For the best performance, a hash function must generate a random distribution for all input. </li>
</ul>
</blockquote>
<p>Taking it into account correct way is:</p>
<pre><code>return str1.GetHashCode() ^ str2.GetHashCode()
</code></pre>
<p><code>^</code> can be substituted with other commutative operation</p>
|
<p>Too complicated, and forgets nulls, etc. This is used for things like bucketing, so you can get away with something like</p>
<pre><code>if (null != str1) {
return str1.GetHashCode();
}
if (null != str2) {
return str2.GetHashCode();
}
//Not sure what you would put here, some constant value will do
return 0;
</code></pre>
<p>This is biased by assuming that str1 is not likely to be common in an unusually large proportion of instances.</p>
| 9,566
|
<p>Is it possible to replace the standard broken image via CSS or using another technique? All my images are the same size and my have transparency.</p>
<p>I've tried to wrap all images with a div's background:</p>
<pre><code><div class="no_broken">
<img src="http://www.web.com/found.gif"/>
</div>
<div class="no_broken">
<img src="http://www.web.com/notfound.gif"/>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>div.no_broken {
background-image: url(standard.gif);
}
div.no_broken, div.no_broken img {
width: 32px;
height: 32px;
display: block;
}
</code></pre>
<p>But this will display two images on top of each other if the IMG is transparent.</p>
|
<p>This works without CSS:</p>
<pre><code><img src="some.jpg" onerror="this.src='alternative.jpg';">
</code></pre>
<p>It seems to even work when Javascript is disabled.</p>
|
<p>As far as I know, there is no CSS property that controls the display of broken images. Maybe there are browser-specific properties? You may have to resort to Javascript to iterate the images on the page, and replace their src if they are broken.</p>
| 32,726
|
<p>I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory. What are some best practices for reducing memory usage in Ruby?</p>
<ul>
<li>Please, let each answer have one "best practice" and let the community vote it up.</li>
</ul>
|
<p>Don't abuse symbols.</p>
<p>Each time you create a symbol, ruby puts an entry in it's symbol table. The symbol table is a global hash which <em>never</em> gets emptied.<br>
This is not technically a memory leak, but it behaves like one. Symbols don't take up much memory so you don't need to be too paranoid, but it pays to be aware of this.</p>
<p>A general guideline: If you've actually typed the symbol in code, it's fine (you only have a finite amount of code after all), but don't call to_sym on dynamically generated or user-input strings, as this opens the door to a potentially ever-increasing number</p>
|
<p><strong>Measure and detect which parts of your code are creating objects that cause memory usage to go up</strong>. Improve and modify your code then measure again. Sometimes, you're using gems or libraries that use up a lot of memory and creating a lot of objects as well.</p>
<p>There are many tools out there such as <a href="https://github.com/joshualat/busy-administrator" rel="nofollow">busy-administrator</a> that allow you to check the memory size of objects (including those inside hashes and arrays).</p>
<pre><code>$ gem install busy-administrator
</code></pre>
<h2>Example # 1: MemorySize.of</h2>
<pre><code>require 'busy-administrator'
data = BusyAdministrator::ExampleGenerator.generate_string_with_specified_memory_size(10.mebibytes)
puts BusyAdministrator::MemorySize.of(data)
# => 10 MiB
</code></pre>
<h2>Example # 2: MemoryUtils.profile</h2>
<h3>Code</h3>
<pre><code>require 'busy-administrator'
results = BusyAdministrator::MemoryUtils.profile(gc_enabled: false) do |analyzer|
BusyAdministrator::ExampleGenerator.generate_string_with_specified_memory_size(10.mebibytes)
end
BusyAdministrator::Display.debug(results)
</code></pre>
<h3>Output:</h3>
<pre><code>{
memory_usage:
{
before: 12 MiB
after: 22 MiB
diff: 10 MiB
}
total_time: 0.406452
gc:
{
count: 0
enabled: false
}
specific:
{
}
object_count: 151
general:
{
String: 10 MiB
Hash: 8 KiB
BusyAdministrator::MemorySize: 0 Bytes
Process::Status: 0 Bytes
IO: 432 Bytes
Array: 326 KiB
Proc: 72 Bytes
RubyVM::Env: 96 Bytes
Time: 176 Bytes
Enumerator: 80 Bytes
}
}
</code></pre>
<p>You can also try <strong>ruby-prof</strong> and <strong>memory_profiler</strong>. It is better if you test and experiment different versions of your code so you can measure the memory usage and performance of each version. This will allow you to check if your optimization really worked or not. You usually use these tools in development / testing mode and turn them off in production.</p>
| 21,895
|
<p>A .net desktop application will send information to a central server, there will be potentially thousands and thousands of deskop apps sending info to my server(s).</p>
<p>The data will be small in size.</p>
<p>Would .net web services be good for this scenerio or would WCF be better suited?</p>
<p>What are the pros/cons?</p>
|
<p>the possibilities for throttling, concurrency, etc. are far more developed within wcf.
its a little bit more work in the beginning, but i guess that it's better suited for scenarios where you need to have full control over your bindings.</p>
|
<p>ASMX is like remoting, it's still around because it shipped with 1.0, but you shouldn't use it anymore if you are starting a new project. WCF will give you many more features and better tooling support.</p>
| 25,581
|
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p>
<pre><code>result = [x**2 for x in mylist if type(x) is int]
</code></pre>
<p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
|
<p>If the calculations are already nicely bundled into functions, how about using <code>filter</code> and <code>map</code>?</p>
<pre><code>result = filter (None, map (expensive, mylist))
</code></pre>
<p>You can use <code>itertools.imap</code> if the list is very large.</p>
|
<p>There is the plain old use of a <code>for</code> loop to append to a list, too:</p>
<pre><code>result = []
for x in mylist:
expense = expensive(x)
if expense:
result.append(expense)
</code></pre>
| 15,817
|
<p>Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. </p>
|
<p>Ok, I found some free time finally.<br>
Here we go: </p>
<pre><code>class TreeNode
{
public string Value { get; set;}
public List<TreeNode> Nodes { get; set;}
public TreeNode()
{
Nodes = new List<TreeNode>();
}
}
Action<TreeNode> traverse = null;
traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};
var root = new TreeNode { Value = "Root" };
root.Nodes.Add(new TreeNode { Value = "ChildA"} );
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" });
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" });
root.Nodes.Add(new TreeNode { Value = "ChildB"} );
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" });
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" });
traverse(root);
</code></pre>
|
<p>Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.</p>
<pre><code> public void HandleTreeItems(Action<TreeItem> item, TreeItem parent)
{
if (parent.Children.Count > 0)
{
foreach (TreeItem ti in parent.Children)
{
HandleTreeItems(item, ti);
}
}
item(parent);
}
</code></pre>
<p>Now to call it, passing in the lambda that handles one item, by printing its name to the console.</p>
<pre><code>HandleTreeItems(item => { Console.WriteLine(item.Name); }, TreeItemRoot);
</code></pre>
| 8,625
|
<p>Is there anyway to have items in an ASP.NET DropDownList have either their Text or Value bound to a method on the source rather than a property? </p>
|
<p>This is my solution:</p>
<pre><code><asp:DropDownList ID="dropDownList" runat="server" DataSourceID="dataSource" DataValueField="DataValueField" DataTextField="DataTextField" />
<asp:ObjectDataSource ID="dataSource" runat="server" SelectMethod="SelectForDataSource" TypeName="CategoryDao" />
public IEnumerable<object> SelectForDataSource()
{
return _repository.Search().Select(x => new{
DataValueField = x.CategoryId,
DataTextField = x.ToString() // Here is the trick!
}).Cast<object>();
}
</code></pre>
|
<p>Declaratively:</p>
<pre><code><asp:DropDownList ID="ddlType" runat="server" Width="250px" AppendDataBoundItems="true" DataSourceID="dsTypeList" DataTextField="Description" DataValueField="ID">
<asp:ListItem Value="0">All Categories</asp:ListItem>
</asp:DropDownList><br />
<asp:ObjectDataSource ID="dsTypeList" runat="server" DataObjectTypeName="MyType" SelectMethod="GetList" TypeName="MyTypeManager">
</asp:ObjectDataSource>
</code></pre>
<p>The above binds to a method that returns a generic list, but you could also bind to a method that returns a DataReader. You could also create your dataSource in code.</p>
| 16,314
|
<p>What is the best approach in stripping leading and trailing spaces in C?</p>
|
<p>Here is how linux kernel does the trimming, called strstrip():</p>
<pre><code>char *strstrip(char *s)
{
size_t size;
char *end;
size = strlen(s);
if (!size)
return s;
end = s + size - 1;
while (end >= s && isspace(*end))
end--;
*(end + 1) = '\0';
while (*s && isspace(*s))
s++;
return s;
}
</code></pre>
<p>Its basically a better formatted and error-checked version what the previous poster said.</p>
|
<pre><code>int i = strlen(s) - 1;
while (isspace(s[i]))
s[i--] = '\0';
while (isspace(*s))
s++;
</code></pre>
<p>That should take care of the problem as long as you don't care about mangling up the string like crazy and if you don't care about memory leaks!</p>
| 45,844
|
<p>On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?</p>
<p>Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.</p>
<p>Example: I need to copy every .txt file in the following hierarchy</p>
<pre><code>/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt
</code></pre>
<p>To a folder named 'dest' and get:</p>
<pre><code>/dest/a.txt
/dest/b.txt
</code></pre>
|
<p>In bash:</p>
<pre><code>find /foo -iname '*.txt' -exec cp \{\} /dest/ \;
</code></pre>
<p><code>find</code> will find all the files under the path <code>/foo</code> matching the wildcard <code>*.txt</code>, case insensitively (That's what <code>-iname</code> means). For each file, <code>find</code> will execute <code>cp {} /dest/</code>, with the found file in place of <code>{}</code>.</p>
|
<p>As far as the man page for cp on a FreeBSD box goes, there's no need for a -t switch. cp will assume the last argument on the command line to be the target directory if more than two names are passed.</p>
| 4,726
|
<p>I've just come across a property setter that catches exceptions (all Exceptions; I know that's bad, but it's not relevant here), and <em>only</em> logs them. First of all, I think it should through them again as well; why wait for a crash and a log study when you can know something is wrong right away?</p>
<p>However, my main question is, do I validate against invalid date values, add a RuleViolation object to a ValidationRules object on my document, or throw an InvalidDate exception, or just let the CLR throw the exception for me (invalid dates are nothing but invalid dates, not checked for range etc.)</p>
|
<p>Exceptions should be thrown whenever the method or class member is unable to complete whatever task it is designed to accomplish.</p>
<p>So for a property setter, if the setter is unable to set the property, then it should throw an exception. </p>
<p>As to whether you should catch it and rethrow it, the answer is yes, but only if you need to process the exception immediately in the setter, before passing it up the stack... but logging it is not a reason to do that. In general, you should implement cross-cutting logging of exceptions at a higher level, where the exception is NOT going to be re-thrown... if you are taking care of those cross-cutting concerns higher up the stack somewhere, then no, definitely do not catch and re-throw the same exception. </p>
<p>However, if you are writing a tool, or a framework library, where you want your component's clients to have a clearly defined set of expected exceptions, and you have defined your own custom exceptions that your component will throw to client code, and which client components will expect to see, then you may want to catch CLR generated exceptions and rethrow your own custom exceptions instead.. Always include the Actual underlying exception in your custom exceptions "InnerException" property before passing it up the stack, so that the data in it is available to whatever system end up consuming it. </p>
|
<p>Catching and rethrowing is the worst thing to do. Its expensive to TRY, if youre just going to rethrow what the point? You can <a href="http://www.west-wind.com/WebLog/posts/1393.aspx" rel="nofollow noreferrer">catch unhandled exceptions with the global.asax</a> for example if you need to log them.</p>
<p>In terms of validation, from a web perspective i always use regex validators for dates, these fire client and server side so i know when im inside an</p>
<pre><code>if(Page.IsValid)
</code></pre>
<p>block that my txtDate.Text is a valid date, so i dont bother checking because its just wasteful.</p>
| 33,707
|
<p>We have a number of Excel-based membership rosters for a non-profit organization and we need to merge these into one master MS Access table. From time to time, we receive updated copies of the Excel-based membership rosters and I need to synchronize these with the master MS Access table.</p>
<p>I'm looking for the optimal way to accomplish this. Since I am not a huge fan of Access VBA, I was thinking of writing a C# console app,leveraging Marcos Meli's <a href="http://www.filehelpers.com/" rel="nofollow noreferrer">FileHelpers</a> library to communicate between Excel and Access. Do you have any recommendations for either a good approach for building myself or something off-the-shelf that could be used to accomplish this objective?</p>
|
<p>You haven't said how big the membership lists are.</p>
<p>If they aren't too massive, and if you aren't doing anything too complex, then simply linking the Excel files to the Access database would allow you to replace the Excel files with new ones (with the same names) and then the database would use the new data automatically and you don't need any updating software at all.</p>
<p>I'm also thinking that a non-profit wouldn't have much IT budget, so the simpler the better.</p>
|
<p>Typically, what I've done in the past was import the excel file into a staging table, and then pruned out duplicated, and then copied the resulting list into the master table.</p>
<p>You might have to cull ex-members from the your master table, in which case, maybe it's easier to delete all the members that came from member organisation and reload the entire list. But then you have to record which organisation they came from.</p>
| 34,691
|
<p>I have done a little Django development, but it has all been in a text editor. I was curious what more advanced development tools others are using in their Django development.</p>
<p>I am used to using Visual Studio for development and really like the <a href="https://en.wikipedia.org/wiki/Intelligent_code_completion#IntelliSense" rel="noreferrer">IntelliSense</a>, code completion, and file organization it provides and would like to find something (or a combination of tools) that would provide some of this in the Django/Python environment.</p>
|
<p>I use Eclipse and a plain vanilla <a href="https://en.wikipedia.org/wiki/PyDev" rel="nofollow noreferrer">PyDev</a>. There isn't any specific Django functionality. The best I came up with was setting up a run profile to run the development web server.</p>
<p>If you add the web tools project (WTP), you'll get syntax highlighting in your templates, but nothing that relates to the specific template language. PyDev is a decent plugin, and if you are already familiar with Eclipse and use it for other projects it is a good way to go.</p>
<p>I recall NetBeans starting to get Python support, but I have no idea where that is right now. Lots of people rave about NetBeans 6, but in the Java world Eclipse still reigns as the king of the OSS IDEs.</p>
<p>Update: LiClipse is also fantastic for Django.<br />
<a href="https://i.stack.imgur.com/lBgOz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lBgOz.png" alt="enter image description here" /></a><br />
Install it, use <a href="https://nrecursions.blogspot.com/2019/03/which-ide-to-choose-for-python.html" rel="nofollow noreferrer">this method</a> to get the icon into Ubuntu's menu. Start LiClipse and in File > New > Project ..., select PyDev and PyDev Django project. You may have to set up your Python interpreter etc, but that you'll be able to figure out on your own. Once the Django project is created, you can right click on the project and the menu will have a "Django" option, which allows various things like creating a Django app or running migrations etc. LiClipse is good because it consumes far lesser memory than PyCharm and supports refactoring and autocomplete reasonably well.</p>
|
<p>I have consistently used Vim or Kate, but I would prefer a full-blown IDE. Given it is not as heavy as Visual Studio.</p>
| 21,103
|
<p>If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll?</p>
|
<p>The VC80 SP1 CRT redistributable package will install both the RTM and SP1 versions of the C runtime into <code>%SystemRoot%\WinSxS</code> (assuming you're using Windows XP or Vista; Windows 2000 doesn't support side-by-side assemblies). If you have VC8 installed, the CRT redistributable package is in <code>%ProgramFiles%\Microsoft Visual Studio 8\VC\redist</code>. If you don't have VC8 installed, I think you can download the CRT redistributable package from Microsoft.com. </p>
<p>Also, to find out exactly what CRT version (e.g. RTM vs. SP1) is needed by a binary that was built with VC8 or VC9, you can extract the manifest:</p>
<pre><code>mt.exe -inputresource:mydll.dll;#1 -out:mydll.dll.manifest
</code></pre>
<p>Look for something like this:</p>
<pre><code><assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b">
</assemblyIdentity>
</code></pre>
<p>My executable requires CRT version 9.0.21022.8. This version number is also embedded in the <code>WinSxS</code> subdirectory names (unfortunately it's surrounded by hashes):</p>
<pre><code>D:>dir c:\windows\WinSxS\*VC90.CRT*
12/14/2007 02:16 AM <DIR> amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b
12/14/2007 02:00 AM <DIR> x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91
</code></pre>
|
<p>If you're authoring and distributing the mentioned DLL, consider using a merge module for Visual C++ 8.0 CRT as part of your installer.</p>
<p>I noticed that there is a new mt.exe tool and new Visual C++ CRT in Windows SDK 6.1. I use the merge module as a prerequisite in the InstallShield 12 installer with great success.</p>
| 26,706
|
<p>Does the SDK provide any way to change the brightness of the backlight, or turn it off temporarily? </p>
|
<p>I'm trying to do the same thing.
As it happens there are a number posts out there in the internets with "solutions" for this.</p>
<p>The most detailed is <a href="http://idevkit.com/forums/tutorials-code-samples-toolchain/14-controlling-brightness.html?t-14.html=" rel="nofollow noreferrer">here</a>
This one is more <a href="http://tlog.fabiocaseri.com/post/28024696/change-backlight-brightness-on-iphone" rel="nofollow noreferrer" title="succinct">succinct</a></p>
<p>The problem is that I've tried these and they all rely on calling this function</p>
<pre><code>GSEventSetBacklightLevel();
</code></pre>
<p>which requires this header to be imported</p>
<pre><code>#import <GraphicsServices/GraphicsServices.h>
</code></pre>
<p>And that import fails in the SDK reporting that the header file cannot be found.</p>
<p>I've searched for some solution but haven't found it.
There is some talk about "building the toolchain" (for the best description I've found see <a href="http://www.saurik.com/id/4" rel="nofollow noreferrer">here</a>) but that seems to involve bypassing the SDK altogether. Pretty drastic.</p>
<p>Summary: It's possible, but not with the standard iPhone SDK. I imagine an update to the SDK will come soon that should allow for it.</p>
<p>Let me know if you find any other solution.</p>
|
<pre><code>-(void)changeLight{
GSEventSetBacklightLevel(float number);//number between 0.0 - 1.0
}
</code></pre>
<p>call the above method using </p>
<pre><code>[self performSelector:@selector(changeLight) withObject:nil afterDelay:0.0];
</code></pre>
<p>you can add the private framework by just drag and drop to your xcode project from /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/System/Library/PrivateFrameworks/GraphicsServices.framework.</p>
<p>Also add #import "GraphicsServices.h" header in your .h file..<em>remember: since you are using private framework you application will reject in app store push</em></p>
| 47,886
|
<p>I need to copy an entire database from a SQL Server 2005 on my server over to my local SQL Express in order to run my application for a presentation. What is the fastest/easiest way to get this done?</p>
<p>EDIT: I have very limited access to my server so I don't think I can access the backup file that I could create so that is out.</p>
|
<p>If the database is not too big, you could use the Database Publishing Wizard.</p>
<p>This is a free tool from Microsoft which creates a complete SQL script of a database for you (not only the tables and stuff, but all data as well).</p>
<p>You can install the tool on your machine, connect to a remote server and let the tool create the script directly on your machine.</p>
<p>You can download the Database Publishing Wizard <a href="http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en" rel="nofollow noreferrer">here</a>.</p>
<hr>
<p>Apparently the link above doesn't work anymore in 2019.<br>
That's probably because <strong>in newer versions of SQL Server Management Studio, the functionality of the Database Publishing Wizard is included out-of-the-box</strong>, so there's no need to install it separately.</p>
<p>It's now called the <a href="https://learn.microsoft.com/en-us/sql/ssms/scripting/generate-and-publish-scripts-wizard?view=sql-server-ver15" rel="nofollow noreferrer">Generate and Publish Scripts Wizard</a>, but it does exactly the same.</p>
|
<p>If you can login to both servers (the Express and the 05 Server) using SQL Server Management Studio then you can do a DB Restore from one database to the other. No need for backup files at all.</p>
| 30,178
|
<p>in a web application I am building I need to upload photos without using a form, otherwise it will come up with form embedded in an outer from which is not permitted in XHTML.</p>
<p>I think uploading files is what jQuery.post should be able to do, but I currently can't figure out how to do this using jQuery.</p>
|
<p>take a look at <a href="http://swfupload.org/" rel="nofollow noreferrer">swfupload</a>, it's a pretty nifty little app that should accomplish what you want. otherwise, you could separate out the forms, and just use css/javascript to reposition them if necessary.</p>
|
<p>Have you check out the fieldset element? Why not wrap your input elements in that, then use jQuery to dynamically assign 'submit' functionality, as opposed to trying to attach it to the overall form element?</p>
| 23,556
|
<p>In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'." </p>
|
<p>The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.</p>
<pre><code>myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value
</code></pre>
<p>It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.</p>
<p>We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword <code>DEFAULT</code> instead of <code>NULL</code> for the value so I'd recommend the same approach when building parameters.</p>
|
<pre><code>Guid? _field = null;
if (myValue!="")//test if myValue has value
{
_field = Guid.Parse(myValue)
}
</code></pre>
| 25,980
|
<p>As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:</p>
<pre><code>centroid = average(x), average(y), average(z)
</code></pre>
<p>where <code>x</code>, <code>y</code> and <code>z</code> are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.</p>
|
<p>Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will <strong>not</strong> argue that there is anything wrong with this:</p>
<p><code>centroid = average(x), average(y), average(z)</code></p>
<p>The "problem" here is that it will "distort" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction.</p>
<p>As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this:</p>
<p><code>middle = middle(x), middle(y), middle(z)</code></p>
<p>You can use this when you don't care much about the number of points, but more about the global bounding box, because that's all this is - the center of the bounding box around your points.</p>
<p>Lastly, you could also use the <code>median</code> (the element in the middle) in each dimension:</p>
<p><code>median = median(x), median(y), median(z)</code></p>
<p>Now this will sort of do the opposite to the <code>middle</code> and actually help you ignore outliers in your point cloud and find a centerpoint <strong>based on</strong> the distribution of your points.</p>
<p>A more and robust way to find a "good" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the <code>average</code> or <code>median</code>. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind.</p>
<p>The dark blue dot is the average (mean) centroid.
The median is shown in green.
And the middle is shown in red.
In the second image you will see exactly what I was talking about earlier: The green dot is "closer" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud.</p>
<p><a href="https://i.stack.imgur.com/8qSQA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8qSQA.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/iZSSi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iZSSi.png" alt="enter image description here"></a></p>
|
<p>You got it. What you are calculating is the centroid, or the mean vector.</p>
| 10,336
|
<p>I have built a RepRap Prusa i2 a while back. It worked for a while, but then I moved the printer from place to place and after a while I noticed that the printer's bed is not heating anymore. The thermistor shows the temperature (room temperature), but the bed is not heating.
The wires are connected and the heated bed has a resistance. </p>
<p>Did anyone else confronted with this? Thanks!</p>
|
<h1>diagnosing a heated bed</h1>
<p>Switch the hot end and the heater bed wires on the board. See if there is a difference. (Note that it will not reach a thermal limit when plugged in this way! So don't leave it on too long!)</p>
<p>After that, if you see that your heat increases with the hot end's wires and the hot end being set on in software then you know the issue is likely with the board. At which point try updating / reflashing the board.</p>
<p>Alternatively, you can try a second board and see if it makes a difference.</p>
<p>If the bed does not heat up even using the heater cartridge connectors, then your heated build plate likely needs to be replaced. Or the wire needs to be replaced.</p>
<p>If you are running Ramps or a board that uses 2 hot end outputs you can likely reprogram it to use hot end heater 2 as the new output for your heated bed.</p>
|
<p>It's probably a fuse or the MOSFET fried?
Try checking for continuity on the fuse and voltage on the MOSFET.</p>
| 386
|
<p>I'm working on several distinct but related projects in different programming languages. Some of these projects need to parse filenames written by other projects, and expect a certain filename pattern.</p>
<p>This pattern is now hardcoded in several places and in several languages, making it a maintenance bomb. It is fairly easy to define this pattern exactly once in a given project, but what are the techniques for defining it once and for all for all projects and for all languages in use?</p>
|
<p>Creating a Domain Specific Language, then compile that into the code for each of the target languages that you are using would be the best solution (and most elegant). </p>
<p>Its not difficult to make a DSL - wither embed it in something (like inside Ruby since its the 'in' thing right now, or another language like LISP/Haskell...), or create a grammar from scratch (use Antlr?). It seems like the project is large, then this path is worth your while. </p>
|
<p>Put the pattern in a database - the easiest and comfortable way could be using XML database. This database will be accessible by all the projects and they will read the pattern from there</p>
| 13,880
|
<p>Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy:</p>
<pre><code>set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)
</code></pre>
|
<pre><code>Do Until zip.Items.Count = Fol.Items.Count
WScript.Sleep 300
Loop
</code></pre>
<p>When the loop finishes your copy is finished.</p>
<p>But if you only want to copy and not zip, FSO or WMI is better.</p>
<p>If you are zipping and want them in a file you have to create the zip-file yourself, with the right header first. Else you only get compressed files/folders IIRC. Something like this:</p>
<pre><code>Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set File = FSO.OpenTextFile( saveFile, 2, True )
File.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) )
File.Close
Set File = Nothing
Set FSO = Nothing
</code></pre>
<p>The 2 in OpenTextFile is ForWriting.</p>
|
<pre><code>Const FOF_CREATEPROGRESSDLG = &H0&
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
strSource = " " ' Source folder path of log files
strTarget = " .zip" ' backup path where file will be created
AddFilesToZip strSource,strTarget
Function AddFilesToZip (strSource,strTarget)
Set r=fso.GetFolder(strSource)
set file = fso.opentextfile(strTarget,ForWriting,true)
file.write "PK" & chr(5) & chr(6) & string(18,chr(0))
file.Close
Set shl = CreateObject("Shell.Application")
i = 0
For each f in r.Files
If fso.GetExtensionName(f) = "log" Or fso.GetExtensionName(f) = "Log" Or fso.GetExtensionName(f) = "LOG" Then
shl.namespace(strTarget).copyhere(f.Path)', FOF_CREATEPROGRESSDLG
Do until shl.namespace(strTarget).items.count = i
wscript.sleep 300
Loop
End If
i = i + 1
Next
set shl = Nothing
End Function
</code></pre>
| 18,068
|
<p>When I try to create a a new snapshot in SQL Server Reporting Services 2005, i get the message: "report history may not be created because the credentials used to run the report are not stored, the report is using user-defined parameter values, default report parameter values are missing, or if a linked report, the link is no longer valid"</p>
<p>Under Data Sources, it has "Windows integrated security" checked. I can choose "Credentials securely stored in the report server" and enter my user name, password, but that doesnt seem right since I dont want to do that for every report.</p>
<p>Right now Im just running it on my local machine (<a href="http://localhost/Reports" rel="nofollow noreferrer">http://localhost/Reports</a>$SQL2005/), so I don't know why I would be getting these errors</p>
<p>Any ideas?</p>
|
<p>setting a data source to use "credentials stored securely in the report server" is required when you want to use Reporting Services features like Subscriptions and Report Snapshots. You only have to do this on the data sources, so assuming you have not created a new data source for each and every report (and they are therefore sharing one or more data sources) you only have to set this up the first time you deploy the data source(s).</p>
<p>Many people create a specific domain account for Reporting Services and use these credentials for the data sources (making sure you have given the domain account necessary permissions to the underlying databases involved). This means that the reports are executed as the Reporting Services account whenever they are run.</p>
<p>More info: <a href="http://msdn.microsoft.com/en-us/library/ms160330(SQL.90).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms160330(SQL.90).aspx</a></p>
|
<p>Agree with everything Nathan said. Make sure the credentials you use have at least dbdatareader access to the reportserver, reportservertemp, and any other db's you use.</p>
| 48,096
|
<p>I was wondering, what's the best approach in creating users authentication for my asp.net-mvc web application.</p>
<p>Should I use the Forms authentication using a custom MembershipProvider ?
Or should I implement my own login and registration mechanism for my users? </p>
|
<p>Seems silly to reinvent the wheel if you don't have a pressing business need to do so. I'd go with forms authentication with a custom provider (if necessary)</p>
|
<p>Unless you have some special needs, its always best to use the out-of-the-box solution. So perhaps you should describe what considerations makes you consider rolling your own? (And add that information to the original question - this will help people provide useful answers).</p>
| 23,576
|
<p>I'm using a large open-source control and I can't seem to find the code that handles a double-click event. Could I perhaps have the debugger break when a double-click occurs or otherwise learn what code is associated with that event?</p>
|
<p>It's not cp, it's tar. You are passing it -v, which makes it print the names of the files.</p>
|
<p>As others pointed out, the -v (verbose) option to tar is kicking out the file names to STDERR. You can also make your script more efficient by having tar write the compressed file stream to STDOUT:</p>
<pre><code>tar zcf - file1 file2 file3
</code></pre>
<p>In this example, the "-" option passed as the filename makes tar write the output to STDOUT.</p>
| 34,065
|
<p>I have a large xml document that needs to be processed 100 records at a time</p>
<p>It is being done within a Windows Service written in c#. </p>
<p>The structure is as follows :</p>
<pre><code><docket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="docket.xsd">
<order>
<Date>2008-10-13</Date>
<orderNumber>050758023</orderNumber>
<ParcelID/>
<CustomerName>sddsf</CustomerName>
<DeliveryName>dsfd</DeliveryName>
<Address1>sdf</Address1>
<Address2>sdfsdd</Address2>
<Address3>sdfdsfdf</Address3>
<Address4>dffddf</Address4>
<PostCode/>
</order>
<order>
<Date>2008-10-13</Date>
<orderNumber>050758023</orderNumber>
<ParcelID/>
<CustomerName>sddsf</CustomerName>
<DeliveryName>dsfd</DeliveryName>
<Address1>sdf</Address1>
<Address2>sdfsdd</Address2>
<Address3>sdfdsfdf</Address3>
<Address4>dffddf</Address4>
<PostCode/>
</order>
.....
.....
</docket>
</code></pre>
<p>There could be thousands of orders in a docket.</p>
<p>I need to chop this into 100 element chunks</p>
<p>However each of the 100 orders still need to be wrapped with the parent "docket" node and have the same namespace etc</p>
<p>is this possible? </p>
|
<p>Another naive solution; this time for .NET 2.0. It should give you an idea of how to go about what you want. Uses Xpath expressions instead of Linq to XML. Chunks a 100 order docket into 10 dockets in under a second on my devbox.</p>
<pre><code> public List<XmlDocument> ChunkDocket(XmlDocument docket, int chunkSize)
{
List<XmlDocument> newDockets = new List<XmlDocument>();
//
int orderCount = docket.SelectNodes("//docket/order").Count;
int chunkStart = 0;
XmlDocument newDocket = null;
XmlElement root = null;
XmlNodeList chunk = null;
while (chunkStart < orderCount)
{
newDocket = new XmlDocument();
root = newDocket.CreateElement("docket");
newDocket.AppendChild(root);
chunk = docket.SelectNodes(String.Format("//docket/order[position() > {0} and position() <= {1}]", chunkStart, chunkStart + chunkSize));
chunkStart += chunkSize;
XmlNode targetNode = null;
foreach (XmlNode c in chunk)
{
targetNode = newDocket.ImportNode(c, true);
root.AppendChild(targetNode);
}
newDockets.Add(newDocket);
}
return newDockets;
}
</code></pre>
|
<p>If the reason to process 100 orders at a time is for performance purposes, e.g. taking too much time and resource to open a big file, You can utilize XmlReader to process order element one at a time without degrading the performance.</p>
<pre><code>XmlReader reader = XmlReader.Create(@"c:\foo\Doket.xml")
while( reader.Read())
{
if(reader.LocalName == "order")
{
// read each child element and its value from the reader.
// or you can deserialize the order element by using a XmlSerializer and Order class
}
}
</code></pre>
| 30,983
|
<p>I'm trying to export a Crystal Report to an HTML file, but when I call the Export method, I immediately get this error:</p>
<blockquote>
<p><strong>Source</strong>: Crystal Reports ActiveX Designer </p>
<p><strong>Description</strong>: Failed to export the report.</p>
</blockquote>
<p>I have tried both crEFTHTML40 and crEFTHTML32Standard as export format types - and both result in the same error.</p>
<p>Here is a highly simplified version of what I'm doing:</p>
<pre><code>Dim objCRReport As CRAXDRT.Report
[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here
</code></pre>
<p>Please note that I am referencing the "Crystal Reports 9 ActiveX Designer Runtime Library" specifically.</p>
|
<p>I'm not sure what you have in the <code>[...]</code> section but your code should include a call to open the report with an instance of the CRAXDRT Application.</p>
<pre><code>Dim objCRReport As CRAXDRT.Report
'***********************************
Dim objCRApp As New CRAXDRT.Application
objCRReport = objCRApp.OpenReport("<YOUR REPORT FILENAME>", 1)
'***********************************
[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here
</code></pre>
|
<p>Try setting the <code>HTMLFileName</code> option instead:</p>
<pre><code>objCRReport.ExportOptions.HTMLFileName = "C:\reportInHtmlFormat.html"
</code></pre>
| 31,208
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2213205/configure-eclipse-to-use-vs-net-shortcuts">Configure Eclipse to use VS.Net shortcuts?</a> </p>
</blockquote>
<p>I mostly work in VS2008 but I need to do some java work in Eclipse. Is there an easy and fast way to map the VS2008 keyboard shortcuts to Eclipse?</p>
<p>For example, I want to map F11 in Eclipse to "step info" instead of its default of F5 but don't want to have to map each and every shortcut manually...</p>
|
<p>How are the Eclipse settings saved? Perhaps you could simply adapt <a href="http://xona.com/2005/08/02.html" rel="nofollow noreferrer">this macro</a> and load the resulting file into Eclipse?</p>
|
<p>Doesn't Eclipse have a predefined keyboard setup for Visual Studio?</p>
| 3,740
|
<p>I have an application installed on my computer. How do I find out if it was compiled in DEBUG mode or not?</p>
<p>I've tried to use <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="noreferrer">.NET Reflector</a>, but it does not show anything specific. Here is what I see:</p>
<pre><code>// Assembly APPLICATION_NAME, Version 8.0.0.15072
Location: C:\APPLICATION_FOLDER\APPLICATION_NAME.exe
Name: APPLICATION_NAME, Version=8.0.0.15072, Culture=neutral, PublicKeyToken=null
Type: Windows Application
</code></pre>
|
<p>I <a href="http://chillijam.co.uk/?p=134" rel="noreferrer">blogged</a> this a long time ago, and I don't know if it still valid or not, but the code is something like...</p>
<pre><code>private void testfile(string file)
{
if(isAssemblyDebugBuild(file))
{
MessageBox.Show(String.Format("{0} seems to be a debug build",file));
}
else
{
MessageBox.Show(String.Format("{0} seems to be a release build",file));
}
}
private bool isAssemblyDebugBuild(string filename)
{
return isAssemblyDebugBuild(System.Reflection.Assembly.LoadFile(filename));
}
private bool isAssemblyDebugBuild(System.Reflection.Assembly assemb)
{
bool retVal = false;
foreach(object att in assemb.GetCustomAttributes(false))
{
if(att.GetType() == System.Type.GetType("System.Diagnostics.DebuggableAttribute"))
{
retVal = ((System.Diagnostics.DebuggableAttribute)att).IsJITTrackingEnabled;
}
}
return retVal;
}
</code></pre>
|
<p>How about using Jeff Key's <a href="http://www.sliver.com/dotnet/IsDebug/" rel="nofollow noreferrer">IsDebug</a> utility? It is a little dated, but since you have Reflector you can decompile it and recompile it in any version of the framework. I did.</p>
| 23,649
|
<p>Can it be done or the only way is to configure it on IIS?</p>
|
<p>You edit generally the Global.asax file's Session_Start method and set <a href="http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx" rel="noreferrer">Session.TimeOut</a> to whatever you want. You can do this anywhere else in your code too.</p>
|
<p>If your in a hosted environment and your not allowed to override IIS default session timeout (as others have mentioned in the comments), you can trick IIS into keeping the session alive for longer by using an iframe that refreshes the session over and over (kind of like a keep alive ping) for whatever interval of time you need. I had this situation and used this approach</p>
<p><a href="https://stackoverflow.com/questions/484964/asp-net-push-redirect-on-session-timeout/5863952#5863952">ASP.NET Push Redirect on Session Timeout</a></p>
| 29,097
|
<p>With the XML below, I would like to know how to get the value of text in the case_id node as an attribute for the hidden input tag in the xsl sheet below.
Is this possible?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="data.xsl"?>
<NewDataSet>
<Cases>
<Case>
<case_id>30</case_id>
...
...
</Case>
</Cases>
</NewDataset>
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<input type="hidden" name="case_num" value="?"/>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
<p>Just change your XSLT to this, this assumes that you do only have 1 case_id, otherwise, you will need to go with a more specific template match, and remove some of the path in the XPATH value I used as an example.</p>
<pre><code><input type="hidden" name="case-num">
<xsl:attribute name="value">
<xsl:value-of select="/NewDataSet/Cases/Case/case_id" />
</xsl:attribute>
</input>
</code></pre>
|
<p>I changed it to:</p>
<pre><code><input type="hidden" name="case-num">
<xsl:attribute name="value">
<xsl:value-of select="case_id" />
</xsl:attribute>
</input>
</code></pre>
<p>as it's in a foreach loop.
Thanks guys, that worked a treat!</p>
| 43,350
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx" rel="nofollow noreferrer">AssemblyVersion</a> and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblyfileversionattribute.aspx" rel="nofollow noreferrer">AssemblyFileVersion</a> attributes are the built-in way of handling version numbers for .NET assemblies. While the framework provides the ability to have the least significant parts of a version number (build and revision, in Microsoft terms) automatically determined, I find the method for this pretty weak, and no doubt have many others.</p>
<p>So I'd like to ask, what ways have been determined to do the best job of having version numbers that better reflect the actual version of a project? Do you have a pre-build script that sets part of the version to the date and time, or repository version for your working copy of a project? Do you just use the automatic generation provided by the framework? Or something else? What's the best way to manage assembly/file versioning? </p>
|
<p>On my current project, we use the Subversion revision number as the least significant (build) part of the version number, and we use a Nant script to create the project AssemblyInfo file. We use the same version number for both the AssemblyVersion and AssemblyFileVersion attributes. (The other three parts are major.minor.point, where major.minor will be incremented every time there's a database schema change, and point is incremented for each release.)</p>
<p>We started out with the build number being simply incremented, but that required that the version file be checked in for every build, and caused conflicts when merging. When that proved unworkable, we started using CruiseControl.NET to generate the build number, but that made it difficult to reproduce specific builds manually. Eventually we went to the current (Subversion-revision) scheme.</p>
<p>Note: Unfortunately with .NET, it is not possible to perfectly recreate a build from a past revision, because the .NET compilers encode the current timestamp into the object file when compiling. Every time you compile the same code, you get a different object file.</p>
|
<p>The AssemblyVersionAttribute is part of an assembly's identity. Changing that means it is a different assembly and programs linking to that assembly need to be recompiled/linked or a version policy need to be applied. We didn't find that apealing so we choose to only increase the AssemblyFileVersion for each hotfix and only change the AssemblyVersion for each major release. We are aware that this decision brings back some of the win32 dll hell. We increase the AssemblyFileVersion for each build and label/tag the version control system with that version so we know from what source the binary came.</p>
| 21,133
|
<p>I have let's say 2 (but they'll become more in the future) fully decoupled systems: system A and system B.</p>
<p>Let's say every piece of information on each system has an informationID. There's nothing stopping the informationID to be the same on different systems. What univocally identifies a piece of information across all systems is a Source-informationID pair.</p>
<p>Let's say I need to export a piece of information from System A to system B. I then want to export the same piece of information from System B and re-import it into System A and I need to be able to recognize that's the same piece of information.</p>
<p>What's the best way of doing this in people's experience?</p>
<p>This is what I am thinking to do:</p>
<ol>
<li>Setup a message bus between the
systems with message queues.</li>
<li>Setup endpoints for each system
that will monitor changes and
generate commands wrapped into
messages that will be pumped
into queues (for example
when a piece of information is
created/deleted/updated).</li>
<li>Assign ranks to the endpoints
relative to create/delete/update
commands in order no to rely on
system names but only on a general
hierarchy - so that each system
doesn't need to know about the
others.</li>
<li>Assign a treshold on
update/delete/create command to each
endpoint so that commands not
meeting the treshold requirement
will be filtered out and not
processed</li>
</ol>
<p>This won't solve the fact that I still need to carry around originalSource+originalSourceID though.</p>
<p>Any help appreciated.</p>
|
<p>This problem has been addressed by EAI (Enterprise Application Integration) vendors like <a href="http://tibco.com/" rel="nofollow noreferrer">Tibco</a> and <a href="http://www.softwareag.com/Corporate/products/wm/default.asp" rel="nofollow noreferrer">webMethods</a> (now part of Software AG). I've never used Tibco before, but I've used webMethods to solve these kind of problems so I'll just focus on webmethods. For example, in an enterprise, data about employees could reside in both Active Directory and PeopleSoft. webMethods could be used to ensure changes, additions, deletes in one system (application) will be reflected in the other in real time. In some other organization, data about employees could also be in an Oracle or SQL Server database. Again, not a problem. These EAI tools like webMethods can talk to a wide variety of back-ends. webMethods is not limited to a single source and a single target, but because it has a publish-subscribe architecture, data from a single source can flow to multiple interested targets who subscribe to a particular piece of information. Guaranteed delivery and may other features can be found in these products. Back to the employee example, ultimately if one does it right, at any given time, all systems and applications in an enterprise can contain the same information about the employees without any discrepancy. </p>
<p>So instead of doing programming in C# or Java, you'll be doing webMethods programming which is very much like a 4GL language. I call it programming because there are still logic involved, loop, if then else, branch, variables, packages, etc but it's very procedure oriented, i.e. no concept of OOP at all.</p>
<p>These EAI tools are built with limited purposes in mind and one of the purposes is to synchronize data between disparate systems in an enterprise easily. And they do their job very well. </p>
<p>The drawback is these tools cost a lot of money. Companies often have a long-term strategy before investing in these tools. </p>
|
<p>Unless there is some specific limitation in the system design preventing this, I'd suggest factoring out the shared/sharable information into a separate DB that the other two can either reference or just replicate locally. Then you don't need the dual-element key nor any elaborate ESB contraption...</p>
| 48,256
|
<p>When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?</p>
|
<p>You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but <em>never, never</em> go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that :)</p>
<p>The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design.</p>
<p>There are a couple of good articles:</p>
<p><a href="http://www.agiledata.org/essays/dataNormalization.html" rel="nofollow noreferrer">http://www.agiledata.org/essays/dataNormalization.html</a></p>
|
<p>Often if you normalize as far as your other software will let you, you'll be done.</p>
<p>For example, when using Object-Relational mapping technology, you'll have a rich set of semantics for various many-to-one and many-to-many relationships. Under the hood that'll provide join tables with effectively 2 primary keys. While relatively rare, true normalization often gives you relations with 3 or more primary keys. In cases like this, I prefer to stick with the O/R and roll my own code to avoid the various DB anomalies.</p>
| 6,999
|
<p>For technical reasons, I can't use ClickOnce to auto-update my .NET application and its assemblies. What is the best way to handle auto-updating in .NET?</p>
|
<p>I think the <a href="http://msdn.microsoft.com/en-us/library/ms978574.aspx" rel="nofollow noreferrer">Updater Application Block</a> was something of a precursor to ClickOnce. Might be worth investigating. Looking at its source code might be enough to spark some ideas.</p>
|
<p>Write your own.</p>
<p>I have heard that they are somewhat difficult to write the first time, but after that it gets simple.</p>
<p>Since I haven't written one yet (although its on my list), I can give you some of the things that I have thought of. Maintain accurate dll versions, as this is important for self updating. And make sure that the updater can update itself.</p>
| 18,202
|
<p>I would like to know exactly how the "Is" command works in Linux and Unix.</p>
<p>As far as I know, ls forks & exec to the Linux/Unix shell and then gets the output (of the current file tree. eg./home/ankit/). I need a more detailed explanation, as I am not sure about what happens after calling fork.</p>
<p>Could anyone please explain the functionality of the 'ls' command in detail?</p>
|
<p>ls doesn't fork. The shell forks and execs in order to run any command that isn't built in, and one of the commands it can run is ls.</p>
<p>ls uses opendir() and readdir() to step through all the files in the directory. If it needs more information about one of them it calls stat().</p>
|
<p>This is a old thread , but still I am commenting because I believe the answer which was upvoted and accepted is partially incorrect. @Mark says that ls is built into shell so shell doesn't exec and fork. When I studied the tldp document on bash(I have attached the link)
"<strong>ls</strong>" is not listed as a build in command.</p>
<p><a href="http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_01_03.html" rel="nofollow">http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_01_03.html</a></p>
<p>Bash built-in commands:</p>
<p>alias, bind, builtin, command, declare, echo, enable, help, let, local, logout, printf, read, shopt, type, typeset, ulimit and unalias.</p>
| 24,986
|
<p>I asked the question:
<a href="https://stackoverflow.com/questions/373818/whats-with-those-do-not-use-javascript-people">What's with those Do-Not-Use Javascript People</a> and many people said that Javascript allows security exploits through client-side attacks. </p>
<p>So I need to follow up and understand the how bad the nature of these attacks are:</p>
<p>I'd like to hear some detailed descriptions of actual attacks or damage caused to your computer or your network that was directly or indirectly caused or allowed via Javascript.</p>
<p>Specifically, was there any physical damage caused to your computer or network? Did you lose any data? Was any of your software damaged? If any damage happened, how long did it take to fix, and how much did it cost?</p>
<p>Or was the attack stopped before it did any damage and how was it stopped? How long did this take and how much did it cost?</p>
<p>I don't consider popups an attack. They are simply an annoyance that can easily be blocked without disabling Javascript.</p>
<p>Please only detail attacks that you personally have attended to. I trust your wisdom as programmers, but I don't trust third party stories as much, where the cause might have been something else.</p>
|
<p>Hmm... <a href="http://www.milw0rm.com/exploits/7477" rel="nofollow noreferrer">Can 0wn you</a>. I mean literally can own the whole computer, install a trojan.</p>
<p>I've seen and done so many XSS attacks successful which caused to steal administration's session and control the whole application. I've seen and done delivering a client side attack such as the link above, which caused installing another application (a RAT) and control the whole box. </p>
<p>After this point as an attacker you can start to attack internal network, such as you can own the router and then control the whole company traffic, you can attack the domain controller, or you can use <strong>pass the hash tool</strong> or a similar tool to steal local credentials and attack other systems with those credentials. After this point it's all about the security of the other computers (and the local computer if the browser was running as a least privileged used instead of an administrator account)</p>
|
<p>An injection attack on a vulnerable input script on a client site caused a trojan-loading script body to be appended to each and every text field in their database via an automatic MS SQL script. We ended up using the script to negate itself to clean it up, but quite a few people got some sort of infection through a server in China before the hole could be plugged.</p>
<p>This applies to this in that the injection hole was one created through a javascript reference (an AJAX call) and the deliverable was also caused via the subsequently injected javascript.</p>
| 49,936
|
<p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p>
|
<p>There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.</p>
<p>Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<a href="http://httpd.apache.org/docs/2.0/howto/cgi.html" rel="nofollow noreferrer">http://httpd.apache.org/docs/2.0/howto/cgi.html</a>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<a href="https://docs.python.org/library/cgi.html" rel="nofollow noreferrer">https://docs.python.org/library/cgi.html</a>).</p>
<p>If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (<a href="http://www.djangoproject.com/documentation/modpython/" rel="nofollow noreferrer">http://www.djangoproject.com/documentation/modpython/</a>)</p>
|
<p>The problem for me wasn't in Apache set up, but in understanding how mod_apache actually uses the .py files. Module-level statements (including those in a <code>if __name__=='__main__'</code> section) are <em>not</em> executed--I assumed that the stdout from running the script at the commandline would be what the server would output, but that's not how it works.</p>
<p>Instead, I wrote a module-level function called <code>index()</code>, and had it return as a string the HTML of the page. It's also possible to have other module-level functions (e.g., <code>otherFunction()</code>) that can be accessed as further segments in the URI (e.g., <code>testScript/otherFunction</code> for the file <code>testScript.py</code>.)</p>
<p>Obviously, this makes more sense than my original stdout conception. Better capability of actually using Python as a scripting language and not a humongous markup language.</p>
| 2,709
|
<p>Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?</p>
<pre><code>update mytable set counter = counter + 1
</code></pre>
<p>I would assume that in the general case, where this update statement is part of a larger transaction, that it wouldn't be. For example, I think this scenario is possible:</p>
<ul>
<li>update the counter within transaction #1</li>
<li>do some other stuff
in transaction #1</li>
<li>update the counter
with transaction #2</li>
<li>commit
transaction #2</li>
<li>commit transaction #1</li>
</ul>
<p>In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?</p>
<p>How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?</p>
|
<p>Read Committed Snapshot only deals with locks on selecting data from tables.</p>
<p>In t1 and t2 however, you're UPDATEing the data, which is a different scenario.</p>
<p>When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)</p>
<ul>
<li>counter = 0</li>
<li>t1 update counter (counter => 1)</li>
<li>t2 update counter (blocked)</li>
<li>t1 commit (counter = 1)</li>
<li>t2 unblocked (can now update counter) (counter => 2)</li>
<li>t2 commit</li>
</ul>
<hr>
<p>Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level. </p>
<p>You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.</p>
<pre><code>DECLARE @CounterInitialValue INT
DECLARE @NewCounterValue INT
SELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234
-- do stuff with the counter value
UPDATE MyTable
SET counter = counter + 1
WHERE
MyID = 1234
AND
counter = @CounterInitialValue -- prevents the update if counter changed.
-- the value of counter must not change in this scenario.
-- so we rollback if the update affected no rows
IF( @@ROWCOUNT = 0 )
ROLLBACK
</code></pre>
<p>This <a href="http://www.devx.com/codemag/Article/21570" rel="noreferrer">devx</a> article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.</p>
<hr>
<p>update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.</p>
<ul>
<li>counter = 0</li>
<li>t1 update counter (counter => 1)</li>
<li>t2 update counter (nested transaction) (counter => 2)</li>
<li>t2 commit</li>
<li>t1 commit (counter = 2)</li>
</ul>
<p>With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.</p>
|
<p>There is at heart only one transaction, the outermost one. The inner transactions are more like checkpoints within a transaction. Isolation levels affect only sibling outermost transactions, not parent/child related transactions.</p>
<p>The counter will be incremented by two. The following yields one row with a value of (Num = 3). (I opened up SMSS and pointed it to a local SQL Server 2008 Express instance. I have a database named Playground for testing stuff.)</p>
<pre><code>use Playground
drop table C
create table C (
Num int not null)
insert into C (Num) values (1)
begin tran X
update C set Num = Num + 1
begin tran Y
update C set Num = Num + 1
commit tran Y
commit tran X
select * from C
</code></pre>
| 23,491
|
<p>Currently using System.Web.UI.WebControls.FileUpload wrapped in our own control.</p>
<p>We have licenses for Telerik. I wanted to know if anyone had experience with that or could suggest a better one?</p>
<p>Some criteria to be measured by</p>
<ul>
<li>validation</li>
<li>peformance</li>
<li>multiple files</li>
<li>localisation (<a href="https://stackoverflow.com/questions/94316/how-to-change-the-text-of-the-browse-button-in-the-fileupload-control-systemweb">browse</a> is difficult)</li>
<li>security</li>
</ul>
|
<p>Personally, if you have the Telerik controls I would give them a shot. I've found that they are very helpful, and the user experience is good. Their upload control is quite nice.</p>
|
<p>You could try a flash-based solution that allows you to display whatever text, textboxes, buttons, or anything else as part of your own file upload control. These solutions typically put a 1x1 flash movie on the page that acts as a bridge between javascript and flash such that javascript can call flash's file upload box dynamically.</p>
<p>In a recent project, I used <a href="http://digitarald.de/journal/54706744/fancyupload-for-flash-10/" rel="nofollow noreferrer">FancyUpload</a> to do exactly that.</p>
| 31,615
|
<p>In my webpage, I want the website to greet the user, but the username is surrounded by 'single quotations'. Since this isn't to prevent MySQL injection, i just want to remove quotes around my name on the display page.</p>
<p>Ex: Welcome 'user'!
I'm trying to find the way where i can strip the quotations around the user and have it display on the example below.</p>
<p>Ex: Welcome user!</p>
<p>The only line of code that I can think relating is this:</p>
<p>$login = $_SESSION['login'];</p>
<p>Does anyone know how to strip single lines quotes?</p>
|
<p>If you're sure that the first and last characters of <code>$login</code> are always a <code>'</code> you can use <a href="http://de3.php.net/manual/en/function.substr.php" rel="noreferrer"><code>substr()</code></a> to do something like</p>
<pre><code>$login = substr($_SESSION['login'], 1, -1); // example 1
</code></pre>
<p>You can strip all <code>'</code> from the string with <a href="http://de3.php.net/manual/en/function.str-replace.php" rel="noreferrer"><code>str_replace()</code></a></p>
<pre><code>$login = str_replace("'", '', $_SESSION['login']); // example 2
</code></pre>
<p>Or you can use the <a href="http://de3.php.net/manual/en/function.trim.php" rel="noreferrer"><code>trim()</code></a> function, which is in fact the same as example 1:</p>
<pre><code>$login = trim($_SESSION['login'], "'"); // example 3
</code></pre>
<p>My personal favorite is example 3, because it can easily be extended to strip away both quote types: </p>
<pre><code>$login = trim($_SESSION['login'], "'\""); // example 4
</code></pre>
|
<p>I think the easiest way would be to use the trim() function. It usually trims whitespace characters, but you may pass it a string containing characters you want to be removed:</p>
<pre><code>echo 'Welcome ' . trim($login, "'");
</code></pre>
<p>See <a href="http://php.net/trim" rel="nofollow noreferrer">http://php.net/trim</a></p>
| 35,449
|
<p>How do you access a SQL Server 2005 Express Edition from a application in a network computer?</p>
<p>The access I need is both from application (Linq-to-SQL and ODBC) and from Management Studio</p>
|
<p>See this KB Article. <a href="http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277" rel="noreferrer">How to configure SQL Server 2005 to allow remote connections</a>.<br>
Oh, and remember that the SQLServer name will probably be MyMachineName\SQLExpress</p>
|
<p>If you're running it on a 2k3 box, you need to install all updates for Sql Server and the 2003 server. </p>
<p>Check the event logs after you start the Sql Server. It logs everything well, telling you if its being blocked, and where it is listening for connections.</p>
<p>From a remote machine, you can use telnet to see if a sql server is listening for remote connections. You just need the IP and the port of the server (default is 1433). From the command line:</p>
<pre><code>telnet 192.168.10.10 1433
</code></pre>
<p>If you get a blank screen, its listening. If you get thrown back to the command prompt, something is blocking you.</p>
| 3,081
|
<p>I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.</p>
<pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
</code></pre>
<p>Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.</p>
<p><strong>UPDATE:</strong><br>
I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. </p>
<pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780");
$(popupWindow.window).unload(function() { alert('hello'); });
</code></pre>
<p>Does anybody have any idea as to why the unload event could be raised when the window is loading?</p>
<p>One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:</p>
<pre><code>popupWindow.onunload = function(){alert('hello')};
</code></pre>
<p>It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the <code>popupWindow.closed</code> property inside of the event to ensure the window was really closed.</p>
|
<p>I created a watcher that checks if the window has been closed:</p>
<pre><code>var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true);
var watchClose = setInterval(function() {
if (w.closed) {
clearTimeout(watchClose);
//Do something here...
}
}, 200);
</code></pre>
|
<p>Use <a href="http://developer.mozilla.org/en/DOM/window.onunload" rel="nofollow noreferrer">window.onUnload</a></p>
| 16,957
|
<p>I just (re-)joined a company to work on some C++ projects. I'm looking at the files and I'm trying to figure out what all the Visual Studio related files are. Many I suspect are orphans from previous versions of the IDE.</p>
<p>I've listed all the file extensions below and annotated the ones I think I understand. If can provide more information about the individual files or how they different files are related, I would be very appreciative. I'd also like to hear advice on dealing with these files under some version control system (we use Visual SourceSafe for now).</p>
<p>.dsp - Developer Studio project (obsolete?)<br>
.dsw - Developer Studio workspace (obsolete?)<br>
.ncb - No compile browser file (for intellisense?)<br>
.sln - Solution<br>
.suo - Solution user options <br>
.vcproj - VC++ project file<br>
.vcproj.$DOMAIN.$USER.user - huh?<br>
.vcproj.vspscc - ?<br>
.vsscc - ?<br>
.vssscc - ?<br>
.vc08 - ?<br>
What drives me really crazy are the files that are binary rather than simple text files. Why does MS hate text files so much? Sigh...</p>
<p>-cr</p>
|
<p>.dsp - Obsolete<br>
.dsw - Obsolete<br>
.ncb - for intellisense (should not be in source control)<br>
.sln - Solution<br>
.suo - Solution user options (should not be in source control)<br>
.vcproj - VC++ project file<br>
.vcproj.$DOMAIN.$USER.user - Project user options (should not be in source control)<br>
.vcproj.vspscc - source control file<br>
.vsscc - source control file<br>
.vssscc - source control file </p>
<p>VSS = Visual Source Safe<br>
SCC = Source Code Control (The TLA for the source control plugin architecture in VS)</p>
|
<p>The vsscc and vssscc have to do with Visual Source Safe.</p>
| 49,134
|
<p>How do you <a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.html" rel="noreferrer">branch and merge</a> with Apache Subversion using the TortoiseSVN client? </p>
|
<p>My easy click-by-click instructions (<strong>specific to TortoiseSVN</strong>) are in Stack Overflow question <em><a href="https://stackoverflow.com/questions/1461922">What is the simplest way to do branching and merging using TortoiseSVN?</a></em>.</p>
|
<p>You can also try <em><a href="http://www.codeproject.com/KB/work/XTortoiseSVN.aspx" rel="nofollow noreferrer">Version Control for the Standalone Programmer - Part 1</a></em> or perhaps <em><a href="http://www.kenegozi.com/Blog/2007/07/30/merging-with-tortoisesvn.aspx" rel="nofollow noreferrer">Merging with TortoiseSVN</a></em>.</p>
| 2,253
|
<p>Our family no longer uses our <a href="http://www.mixman.com/products/dm2.html" rel="nofollow noreferrer">Mixman DM2</a> USB controller for making music. This frees it up for me to use as an auxiliary keyboard with 31 "keys" (and a few "sliders"). I had the crazy idea to use these buttons to send keyboard shortcuts to Visual Studio. It just seems easier pressing one key than some of the finger-bending ctrl double-key combos.</p>
<p>I tried a couple utilities like JoyToKey and XPadder but they only recognize game controllers and the DM2 falls into the more generic "USB Controller" category.</p>
<p>Have you ever heard of such nonsense?</p>
<p><strong>Clarify Question:</strong> Are you aware of a utility to read inputs from a generic USB Controller and map them to keyboard key presses? -OR- Are you aware of a Visual Studio add-in that will read from a generic USB Controller?</p>
|
<p>Haven't heard of it before, but I can't wait to see if you can make it useful!</p>
<p>You can assign Visual Studio functions to "chords" of key combinations, right? So maybe you could play shave-and-a-haircut to start a build.</p>
|
<p>Yeah, I was thinking about doing something similiar to that myself. I'm pretty sure you'd have to write your own driver for it though.</p>
| 13,284
|
<p>What serial communication bus would you use in a automotive embedded system if your main selection criteria were: </p>
<ul>
<li>Electrically robust </li>
<li>Slow speed (32 kb/s) </li>
<li>Easy to program </li>
<li>Easy to interface with microcontrollers </li>
</ul>
<p>It won't be transferring much data, but it will need to be transferred periodically at high speed (100 - 500 Hz). I find that RS-232 is just not reliable enough if you have noise in your ground line. CAN-bus seems interesting, but I have no experience with it. </p>
<p>We are currently interested in a combination of AVR AT90CAN128 microcontrollers.</p>
|
<p>You've already chosen the AT90CAN128, whose standout feature compared to other AVR processors is support for the CAN bus. There really is not a better choice than CAN for an automotive application with your data rate and noise immunity requirements. If you march in to an automotive customer with anything other than CAN, you'll end up spending all your time defending the decision not to use it.</p>
<p>With that said, for noise immunity in a hostile environment like a car you'll need a bus using differential signaling. That rules out i2c or SPI, which is unfortunate because they meet your other requirements. RS-485 would be workable as @Andrew Edgecombe points out.</p>
<p>If you're not building a commercial product but instead building something for your own use to put in the engine compartment, you can probably get by with USB. USB will make it easy to interface with a laptop in the passenger compartment, and though it isn't designed for high-noise environments it is differentially signaled at a reasonably high voltage.</p>
|
<p>As others said, CAN is standard, robust, more robust with slow speed etc.</p>
<p>And there's even support in Linux kernel for it from version 2.6.15 if you ever need bigger system.</p>
| 17,436
|
<p>Does anyone know of an easy way to escape HTML from strings in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.</p>
|
<p>Since you're using <a href="https://jquery.com/" rel="noreferrer">jQuery</a>, you can just set the element's <a href="http://api.jquery.com/text/" rel="noreferrer"><code>text</code></a> property:</p>
<pre><code>// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// &lt;script&gt;alert('hi!');&lt;/script&gt;
</code></pre>
|
<p><a href="https://stackoverflow.com/a/10825766/819417">This answer</a> provides the jQuery and normal JS methods, but this is shortest without using the DOM:</p>
<pre><code>unescape(escape("It's > 20% less complicated this way."))
</code></pre>
<p>Escaped string: <code>It%27s%20%3E%2020%25%20less%20complicated%20this%20way.</code></p>
<p>If the escaped spaces bother you, try:</p>
<pre><code>unescape(escape("It's > 20% less complicated this way.").replace(/%20/g, " "))
</code></pre>
<p>Escaped string: <code>It%27s %3E 20%25 less complicated this way.</code></p>
<p>Unfortunately, the <code>escape()</code> function was <a href="http://www.w3schools.com/jsref/jsref_escape.asp" rel="nofollow noreferrer">deprecated in JavaScript version 1.5</a>. <code>encodeURI()</code> or <code>encodeURIComponent()</code> are alternatives, but they ignore <code>'</code>, so the last line of code would turn into this:</p>
<pre><code>decodeURI(encodeURI("It's > 20% less complicated this way.").replace(/%20/g, " ").replace("'", '%27'))
</code></pre>
<p>All major browsers still support the short code, and given the number of old websites, i doubt that will change soon.</p>
| 4,445
|
<p>Is there any need of Virtual Constructors? If so can any one post a scenario?</p>
|
<p>If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.</p>
<pre><code>class A
{
~A();
}
class B : public A
{
~B();
}
A* pB = new B();
delete pB; // NOTE: WILL NOT CALL B's destructor
class A
{
virtual ~A();
}
class B : public A
{
virtual ~B();
}
A* pB = new B();
delete pB; // NOTE: WILL CALL B's destructor
</code></pre>
<p><strong>Edit:</strong> Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well</p>
<p><a href="http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx</a></p>
|
<p>In C++, all constructors are implicitly virtual (with a little extra). That is, the constructor of the base class is called before that of the derived class. So, it's like they're sort of virtual. Because, in a virtual method, if the derived class implements a method of the same signature, only the method in the derived class is invoked.</p>
<p>However, <strong>in a constructor, BOTH METHODS ARE INVOKED</strong> (see example below).</p>
<p>For a more complete explanation of why this is so, please see Item 9 of Effective C++, Third Edition, By Scott Meyers (Never call a virtual function during construction or destruction). The title of the item may be misleading in relation to the question, but if you read the explanation, it'll make perfect sense.</p>
<pre><code>#include <iostream>
#include <vector>
class Animal {
public:
Animal(){
std::cout << "Animal Constructor Invoked." << std::endl;
}
virtual void eat() {
std::cout << "I eat like a generic animal.\n";
}
//always make destructors virtual in base classes
virtual ~Animal() {
}
};
class Wolf : public Animal {
public:
Wolf(){
std::cout << "Wolf Constructor Invoked." << std::endl;
}
void eat() {
std::cout << "I eat like a wolf!" << std::endl;
}
};
int main() {
Wolf wolf;
std::cout << "-------------" << std::endl;
wolf.eat();
}
</code></pre>
<p>Output:</p>
<pre><code>Animal Constructor Invoked.
Wolf Constructor Invoked.
-------------
I eat like a wolf!
</code></pre>
| 9,600
|
<p>We are trying to repair an Ultimaker Original+. One problem is a missing resistor isolation. The Ultimaker Original+ prints with up to 260 Degree Celcius.</p>
<p><strong>Which kind of isolation products are suitable to resist the heat and are fitting on the thin wires of the thermistor?</strong></p>
|
<p>The most common choice for insulating thermistors is glass fiber sleeving. It tolerates very high temperatures, and is commonly rated for up to 600 °C.</p>
<p>Teflon is also used but has a rather low upper limit on its working temperature; it shouldn't be used at temperatures exceeding 260 °C - which rules it out for your purpose.</p>
|
<p>There are many materials you can use one that came to my mind is this High Temperature & Pressure Sealant and also the best way to apply it so it can be removed easy is this . take a kitchen food very thing nylon cover you know the very thin elastic one or cover the parts with some type of release agent (dont use something that inhibit silicone like sulfur or sulfur containing staff) and apply it over it then when is solid cut it and release it it would be like a glove i hope ;)There are silicone that are really high temp 1000 f to 2000 f good luck :) </p>
| 489
|
<p>I have the following code which plays a video clip but when it is finished it does not release the form but instead leaves the last frame of the video. how do I get it to clear when playback ends so that I can see the orignal contents of the form it took over to play the video?</p>
<pre><code>_video = new Video("video.wmv");
_video.Owner = frmVideoWindow;
_video.Play();
</code></pre>
|
<p><a href="https://stackoverflow.com/users/13913/daok">Daok</a> pointed me in the correct direction. An event handler on the video ending and then setting the Owner of the Video object to null.</p>
<pre><code>_video.Ending += new System.EventHandler(this.video_stopped);
private void video_stopped(object sender, EventArgs e)
{
_video.Owner = null;
}
</code></pre>
|
<p>Release the form you mean to close it? You might want to check for an event in your Video object that will raise when the video is done and you will need to use this.close(); to close the form. Is it what you desire?</p>
| 34,622
|
<p>I'm working on some production software, using C# on the .NET framework. I really would like to be able to use LINQ on the project. I believe it requires .NET version 3.5 (correct me if I'm wrong). This application is a commercial software app, required to run on a client's work PC. Is it reasonable to assume they have .NET 3.5, or assume that they won't mind upgrading to the latest version?</p>
<p>I just wanted to feel out what the consensus was as far as mandating framework upgrades to run apps.</p>
|
<p>I would say that it isn't safe to assume they have .NET 3.5.</p>
<p>Where as it is very, very unlikely they will have any problems when upgrading, changing anything always carries a risk. I know I wouldn't mind upgrading, but I am a developer.</p>
<p>I think it's one of those things that could go either way, they either won't think twice about it and just upgrade, or they might make an issue out of it. I think it would depend on your customers, 'low-tech' clients may think twice as they may not fully understand it, which would make them nervous.</p>
|
<p>So long as you know that you don't need to support Windows 2000 or any older versions of Windows then requiring the latest and greatest framework version doesn't feel too onerous. </p>
<p>Some less fortunate developers are stuck with older framework versions because they need to support older OS versions.</p>
| 13,196
|
<p>I recognize that there's an obvious pattern in the output to this, I just want to know why lispbox's REPL aborts when I try to run anything > 52. Also, any suggestions on improving the code are more than welcome. ^-^</p>
<pre><code>(defun count-reduced-fractions (n d sum)
(setf g (gcd n d))
(if (equal 1 d)
(return-from count-reduced-fractions sum)
(if (zerop n)
(if (= 1 g)
(count-reduced-fractions (1- d) (1- d) (1+ sum))
(count-reduced-fractions (1- d) (1- d) sum))
(if (= 1 g)
(count-reduced-fractions (1- n) d (1+ sum))
(count-reduced-fractions (1- n) d sum)))))
</code></pre>
<p>All I get when I call </p>
<p><code>(count-reduced-fractions 53 53 0)</code></p>
<p>is</p>
<blockquote>
<p>;Evaluation aborted</p>
</blockquote>
<p>It doesn't make much sense to me, considering it'll run (and return the accurate result) on all numbers below that, and that I could (if i wanted to) do 53 in my head, on paper, or one line at a time in lisp. I even tested on many different numbers greater than 53 to make sure it wasnt specific to 53. Nothing works.</p>
|
<p>This behaviour hints at a missing tail call optimization, so that your recursion blows the stack. A possible reason is that you have declaimed debugging optimization.</p>
<p>By the way, you don't need to make an explicit call to <code>return-from</code>. Since <code>sum</code> is a self-evaluating symbol, you can change this line</p>
<pre><code>(return-from count-reduced-fractions sum)</code></pre>
<p>to</p>
<pre><code>sum</code></pre>
<p><em>edit:</em> Explanation of the proposed change: "sum" evaluates to its own value, which becomes the return value of the "if" statement, which (since this is the last statement in the defun) becomes the return value of the function.</p>
<p><em>edit:</em> Explanation of declaimed optimization: You could add the following to your top level:</p>
<pre><code>(declaim (optimize (speed 3)
(debug 0)))</code></pre>
<p>or use the same, but with <code>declare</code> instead of <code>declaim</code> as the first statement in your function. You could also try (space 3) and (safety 0) if it doesn't work.</p>
<p>Tail call optimization means that a function call whose return value is directly returned is translated into a frame replacement on the stack (instead of stacking up), effectively "flattening" a recursive function call to a loop, and eliminating the recursive function calls. This makes debugging a bit harder, because there are no function calls where you expect them, resp. you do not know how "deep" into a recursion an error occurs (just as if you had written a loop to begin with). Your environment might make some default declamations that you have to override to enable TCO.</p>
<p><em>edit:</em> Just revisiting this question, what is <code>g</code>? I think that you actually want to</p>
<pre><code>(let ((g (gcd n d)))
;; ...
)
</code></pre>
|
<p>Probably a Stack Overflow (heh).</p>
| 46,209
|
<p>I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.</p>
<p>The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:</p>
<pre><code>MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
</code></pre>
<p>Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.</p>
<p>Any ideas?</p>
|
<p>Remove the last parameter, <code>MessageBoxOptions.DefaultDesktopOnly</code>. </p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxoptions(VS.80).aspx" rel="noreferrer">MSDN</a>:</p>
<blockquote>
<p>DefaultDesktopOnly will cause the
application that raised the MessageBox
to lose focus. The MessageBox that is
displayed will not use visual styles.
For more information, see Rendering
Controls with Visual Styles.</p>
</blockquote>
<p>The last parameter allows communication of a background Windows Service with the active desktop through means of csrss.exe! See Bart de Smet's <a href="http://bartdesmet.net/blogs/bart/archive/2004/12/03/488.aspx" rel="noreferrer">blog post</a> for details.</p>
|
<p>These answers are correct, but I wanted to add another point. I came across this question while working with someone else's code. A simple message box was causing the front most window to move to the back:</p>
<p>MessageBox.Show("Hello").</p>
<p>Turns out, there was a BindingSource.Endedit command before the MessageBox. The BindingSource wasn't connected to any controls yet, but it caused the window to change z-positions. </p>
<p>I am only including this note since my search brought me to this question and I thought it might be helpful to someone else.</p>
| 18,872
|
<p>I need to determine which version of GTK+ is installed on Ubuntu</p>
<p>Man does not seem to help</p>
|
<p><a href="https://stackoverflow.com/a/126145/">This suggestion</a> will tell you which minor version of 2.0 is installed. Different major versions will have different package names because they can co-exist on the system (in order to support applications built with older versions).</p>
<p>Even for development files, which normally would only let you have one version on the system, you can have a version of gtk 1.x and a version of gtk 2.0 on the same system (the include files are in directories called gtk-1.2 or gtk-2.0).</p>
<p>So in short there isn't a simple answer to "what version of GTK is on the system". But...</p>
<p>Try something like:</p>
<pre><code>dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]'
</code></pre>
<p>to list all the libgtk packages, including -dev ones, that are on your system. <code>dpkg -l</code> will list all the packages that dpkg knows about, including ones that aren't currently installed, so I've used grep to list only ones that are installed (line starts with i).</p>
<p>Alternatively, and probably better if it's the version of the headers etc that you're interested in, use pkg-config:</p>
<pre><code>pkg-config --modversion gtk+
</code></pre>
<p>will tell you what version of GTK 1.x development files are installed, and</p>
<pre><code>pkg-config --modversion gtk+-2.0
</code></pre>
<p>will tell you what version of GTK 2.0. The old 1.x version also has its own gtk-config program that does the same thing. Similarly, for GTK+ 3:</p>
<pre><code>pkg-config --modversion gtk+-3.0
</code></pre>
|
<p>To make the answer more general than Ubuntu (I have Redhat):</p>
<p>gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with </p>
<pre><code>env | grep gtk
</code></pre>
<p>Then try to find where your gtk files are stored. For example, use <code>locate</code> and grep.</p>
<pre><code>locate gtk | grep /usr/lib
</code></pre>
<p>In this way, I found <code>/usr/lib64/gtk-2.0</code>, which contains the subdirectory <code>2.10.0</code>, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: <code>rpm -qa | grep gtk2</code>, so I think my conclusion is right.</p>
| 15,340
|
<pre><code>Open App.Path & "\Folder\" & str(0) For Output
</code></pre>
<p>Seems to get a path not found however if directly before that I do</p>
<pre><code>MsgBox App.Path & "\Folder\" & str(0)
</code></pre>
<p>It Provides the correct directory/filename that I want</p>
<p>and if I replace that string with the direct path in quotes it works fine however that won't be very good for other users of my app :( Anyone know why this doesn't work? </p>
|
<p>You can open a file that doesn't exist. I tried it with:</p>
<pre><code> Open "c:\temp\test.txt" & Str(0) For Output As #1
Close #1
</code></pre>
<p>When it ran it created c:\temp\test.txt 0</p>
<p>Note that I added "As #1" to the Open statement, and taht Str(0) adds a leading space for the optional minus sign (CStr(0) doens't add a leading space)</p>
|
<p>Here something easy i made for you:</p>
<pre><code>Function CreateLog(Destination As String, MyMessage As String)
Dim PathToCreate, FolderPath, FileName As String
'Check for Unnecessary Spaces
Destination = Trim(Destination)
FolderStr = Destination
'Gather only FolderPath of Destination
Do
FolderStr = Mid(FolderStr, 1, Len(FolderStr) - 1)
Loop Until Right(FolderStr, 1) = "\" Or Len(FolderStr) < 1
'Gather only FileName
FileName = Mid(Destination, Len(FolderStr) + 1, Len(Destination) - Len(FolderStr))
'If the path does not exist than create it
'Recursive approach
For Each Folder In Split(FolderStr, "\")
If InStr(1, Folder, ":") = 0 Then
PathToCreate = PathToCreate & "\" & Folder
Else
PathToCreate = Folder
End If
If fso.FolderExists(PathToCreate) = False And PathToCreate <> "" Then
fso.CreateFolder PathToCreate
End If
Next
'Open file and add the message in it
Open PathToCreate & "\" & FileName & ".txt" For Append As #1
Print #1, MyMessage
Close #1
End Function
</code></pre>
<p>Usage:</p>
<pre><code>CreateLog "D:\Test\NewTest\NewFolder\AnotherFolder\atlastthefile.abcdefg", "Hello!"
</code></pre>
<p>Doesnt matter what fileExtention given cause ill add ".txt" anyways..</p>
| 37,443
|
<p>I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner:</p>
<pre><code>f_oType = Type.GetTypeFromProgID(MyProgId);
f_oInstance = Activator.CreateInstance(f_oType);
</code></pre>
<p>I need to use GetTypeFromProgID rather than using tlbimp to create a library against the COM DLL as the ProgId of the type I need to instantiate can vary. I then use Type.InvokeMember to call the COM method in my code like:</p>
<pre><code>f_oType.InvokeMember("Process", BindingFlags.InvokeMethod, null, f_oInstance, new object[] { param1, param2, param3, param4 });
</code></pre>
<p>I catch any raised TargetInvocationException's for logging and can get the detailed error description from the TargetInvocationException.InnerException field. However, I know that the COM component uses Error.Raise to generate an error number and I need to somehow get hold of this in my calling .Net application.</p>
<p>The problem seems to stem from the TargetInvocationException not containing the error number as I'd expect if it were a normal COMException so:</p>
<p><em><strong>How can I get the Error Number from the COM object in my .Net code?</strong></em></p>
<p>or</p>
<p><em><strong>Can I make this same call in a way that would cause a COMException (containing the error number) rather than a TargetInvocationException when the COM component fails?</strong></em></p>
<p>Please also note that the target platform is .Net 2.0 and I do have access to the VB6 source code but would regard altering the error message raised from VB6 to contain the error code as part of the text to be a bit of a hack.</p>
|
<p>JUnit has no such runner at the moment. Addressing the underlying issue, the need to get reasonable assurance from a test suite in a limited amount of time, is our highest development priority for the next release. In the meantime, implementing a Filter that works through annotations seems like it wouldn't be a big project, although I'm biased.</p>
|
<p>You can create suites, although that puts all the configuration in the suite, and not in annotations.</p>
| 18,521
|
<p>In my Page_Load event of codebehind file, I am loading data in to a datatable.In my .aspx page I am having some inline coding,I want to display some data from this datatable.But when i am running the program,It is showing an error like "Error 64 Use of unassigned local variable 'dtblChild' "
dtblChild is my DataTable Object</p>
<p>Is Page_Load in codebehind executes after loading the form elements ?</p>
|
<p>Inline Code executes during the Render stage.</p>
<p>in the <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">lifecycle</a> of a page, Render happens much later than Load</p>
|
<p>Yes, the page load executes after all of the server controls have been loaded into memory, but you have to ensure that the datatable is repopulated on each refresh if you're going to use it.</p>
<p>I think your question indicates some deeper problems with the way you're binding to the page.</p>
<p>Can you post some code?</p>
| 30,145
|
<p>I'm looking to the equivalent of Windows <a href="http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx" rel="noreferrer"><code>_wfopen()</code></a> under Mac OS X. Any idea?</p>
<p>I need this in order to port a Windows library that uses <code>wchar*</code> for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.</p>
|
<p>POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X. </p>
<p>Here is a class that will wrap an UTF-8 generated string from a wchar_t string.</p>
<pre><code>class Utf8
{
public:
Utf8(const wchar_t* wsz): m_utf8(NULL)
{
// OS X uses 32-bit wchar
const int bytes = wcslen(wsz) * sizeof(wchar_t);
// comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
: kCFStringEncodingUTF32BE;
CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
(const UInt8*)wsz, bytes,
encoding, false,
kCFAllocatorNull
);
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
m_utf8 = new char[bytesUtf8];
CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
CFRelease(str);
}
~Utf8()
{
if( m_utf8 )
{
delete[] m_utf8;
}
}
public:
operator const char*() const { return m_utf8; }
private:
char* m_utf8;
};
</code></pre>
<p>Usage:</p>
<pre><code>const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");
</code></pre>
<p>This will work for reading or writing files.</p>
|
<p>If you're using Cocoa it's fairly easy with NSString. Just load the UTF16 data in using -initWithBytes:length:encoding: (or perhaps -initWithCString:encoding:) and then get a UTF8 version by calling UTF8String on the result. Then, just call fopen with your new UTF8 string as the param.</p>
<p>You can definitely call fopen with a UTF-8 string, regardless of language - can't help with C++ on OSX though - sorry.</p>
| 3,337
|
<p>I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.</p>
<p>Lets say that I am trying to shuffle the <code>randomizer</code> array. </p>
<pre><code>int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
</code></pre>
<p>For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas? </p>
|
<p><code>Arrays.asList</code> cannot be used with arrays of primitives. Use this instead:</p>
<pre><code>Integer[] randomizer = new Integer[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
</code></pre>
<p>The same rule applies to most classes in the collections framework, in that you can't use primitive types.</p>
<p>The original code (with <code>int[]</code>) compiled fine, but did not work as intended, because of the behaviour of the variadic method <code>asList</code>: it just makes a one-element list, with the <code>int</code> array as its only member.</p>
|
<p>Chris' answer is correct.</p>
<p>As i said in a comment on Chris' answer, your underlying array will change appropriately unless the arraylist needs to grow, and the list creates a new one and copies items into it.</p>
<p>You may want to keep a reference to the list and iterate over that after the Arrays.asList call, and not iterate over the array after that, iterate over the List instead.</p>
| 21,834
|
<p>My SQL table looks like this:</p>
<pre><code>CREATE TABLE Page (
Id int primary key,
ParentId int, -- refers to Page.Id
Title varchar(255),
Content ntext
)
</code></pre>
<p>and maps to the following class in my ActiveRecord model:</p>
<pre><code>[ActiveRecord]
public class Page {
[PrimaryKey]
public int Id { get; set; }
[BelongsTo("Parent")]
public virtual Page Parent { get; set; }
[Property]
public string Title { get; set; }
[Property]
public string Content { get; set; }
[HasMany(typeof(Page), "Parent", "Page")]
public IList<Page> Children { get; set; }
}
</code></pre>
<p>I'm using ActiveRecord to retrieve the tree roots using the following code:</p>
<pre><code>var rootPages = new SimpleQuery<Page>(@"from Page p where p.Parent is null");
return(rootPages.Execute());
</code></pre>
<p>This gives me the correct object graph, but a SQL Profiler trace shows that child pages are being loaded by a separate query for every non-leaf node in the tree.</p>
<p>How can I get ActiveRecord to load the whole lot up front <code>("SELECT * FROM Page")</code> and then sort the in-memory objects to give me the required parent-child relationships?</p>
|
<p>The easiest way to do this is to fetch the entire table, then filter the result. This is pretty easy, if you are using linq.</p>
<pre><code>var AllPages = ActiveRecordMediator<Page>.FindAll();
var rootPages = AllPages.Where(p => p.Parent == null);
</code></pre>
|
<p>Try this:</p>
<pre><code>var rootPages = new SimpleQuery<Page>(@"from Page p left join fetch p.Children where p.Parent is null");
return(rootPages.Execute());
</code></pre>
<p>This will cause the Children collection of each Page in the result set to be populated out during the initial query, which should reduce your overall query load to a single query.</p>
| 35,299
|
<p>Groovy adds the <code>execute</code> method to <code>String</code> to make executing shells fairly easy;</p>
<pre><code>println "ls".execute().text
</code></pre>
<p>but if an error happens, then there is no resulting output. <strong>Is there an easy way to get both the standard error and standard out?</strong> (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)</p>
<p>It would be nice to have something like;</p>
<pre><code> def x = shellDo("ls /tmp/NoFile")
println "out: ${x.out} err:${x.err}"
</code></pre>
|
<p>Ok, solved it myself;</p>
<pre><code>def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"
</code></pre>
<p>displays:</p>
<p><code>out> err> ls: cannot access /badDir: No such file or directory</code></p>
|
<pre><code>command = "ls *"
def execute_state=sh(returnStdout: true, script: command)
</code></pre>
<p>but if the command failure the process will terminate</p>
| 19,253
|
<p>I am developing a TCP/IP client that has to deal with a proprietary binary protocol. I was considering using user-defined types to represent the protocol headers, and using CopyMemory to shuffle data to and from the UDT and a byte array. However, it appears that VB6 adds padding bytes to align user-defined types. Is there any way to force VB6 to not pad UDT's, similar to the <code>#pragma pack</code> directive available in many C/C++ compilers? Perhaps a special switch passed to the compiler?</p>
|
<p>No. </p>
<p>Your best bet is to write the low level code in C or C++ (where you do have <code>#pragma pack</code>), then expose the interface via COM.</p>
|
<p>There is not any way to force VB6 to not pad UDT's, similar to the #pragma pack directive available in many C/C++ compilers, but you can do it the other way around.</p>
<p>According to Q194609 Visual Basic uses 4 bytes alignment and
Visual C++ uses 8 bytes by default.</p>
<p>When using VB6 to call out to a C DLL, I used the MS "pshpack4.h" header files to handle the alignment because various compilers do this in different ways, as shown in this (rather edited) example:</p>
<pre>
// this is in a header file called vbstruct.h
...
# define VBSTRING char
# define VBFIXEDSTRING char
# define VBDATE double
# define VBSINGLE float
# ifdef _WIN32
# define VBLONG long
# define VBINT short
# else // and this was for 16bit code not 64bit!!!!
# define VBLONG long
# define VBINT int
# endif
...
# include "pshpack4.h"
...
typedef struct VbComputerNameStruct
{
VBLONG sName;
VBSTRING ComputerName[VB_COMPUTERNAME_LENGTH];
} VbComputerNameType;
typedef struct VbNetwareLoginInfoStruct
{
VBLONG ObjectId;
VBINT ObjectType;
VBSTRING ObjectName[48];
} VbNetwareLoginInfoType;
...
# include "poppack.h"
</pre>
| 17,278
|
<p>I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?</p>
|
<p>The answer is <code>SELECT DATEADD(ms, -3, '2008-01-24')</code>, the explanation is below.</p>
<p>From <a href="http://musingmarc.blogspot.com/2006/07/more-on-dates-and-sql.html" rel="nofollow noreferrer">Marc's blog</a>:</p>
<blockquote>
<p>But wait, Marc... you said you like to use <code>BETWEEN</code>, but that query doesn't have one... that's because <code>BETWEEN</code> <a href="http://www.techonthenet.com/sql/between.php" rel="nofollow noreferrer">is inclusive</a>, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly <strong>NOT</strong> by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server <code>DATETIME</code> columns have <em>at most</em> a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:</p>
</blockquote>
<pre><code> SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))
</code></pre>
<blockquote>
</blockquote>
<p>So to do the orders due this month as a <code>BETWEEN</code> query, you can use this:</p>
<blockquote>
</blockquote>
<pre><code> SELECT [ID]
FROM [dbo].[Orders]
WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)
AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))
</code></pre>
<blockquote>
</blockquote>
<p>Remember, always make sure that you do math against input parameters, <strong>NOT</strong> columns, or you will kill the <a href="http://www.databasejournal.com/features/mssql/article.php/1436301" rel="nofollow noreferrer">SARG</a>-ability of the query, which means indexes that might have been used aren't.</p>
|
<p>I was able to use:</p>
<pre><code>select {fn curdate()} + ' 23:59:59.000'
</code></pre>
<p>or</p>
<pre><code>select DATEADD(ss,-1,DATEADD(DAY,1,CAST({fn curdate()} as DATETIME)))
</code></pre>
<p>to get the end of a day</p>
| 20,207
|
<p>I have one <code>JSON</code> that is coming in a <code>string</code> format. I need to store it in a <code>key-pair</code> value or something like that. I am using <code>asp.net 2.0</code> and can not use 3rd party <code>DLL</code> like <code>Newtonsoft.Json.dll</code>. I guess last option will be to use <code>regular expression</code>. </p>
<p><em>Can anybody please help me in this?</em></p>
|
<p>If you go to <a href="http://www.json.org/" rel="nofollow noreferrer">http://www.json.org/</a> and look towards the bottom of the page there are dozens of json libraries most of them open source, I believe they list 8 for C#. If you can not reference one of these libraries, I think your best bet would be to find one with a permissive license and simply add the code to your project.</p>
<p>Another idea is to look at the diagrams, grammer, and syntax at <a href="http://www.json.org/" rel="nofollow noreferrer">http://www.json.org/</a> and just write your own parser, but regex is <strong>NOT</strong> the way to do it. If you dont know how to write a parser you could look at one of the open source json libraries or start with something less complicated like a good CSV parser, here is a paper that looks pretty good: <a href="http://www.boyet.com/Articles/CsvParser.html" rel="nofollow noreferrer">http://www.boyet.com/Articles/CsvParser.html</a></p>
|
<p>You will need to use jscript.net as the code behind language, but other pages of your site should be fine to stay as c# if thats what you prefer.</p>
<p>As mentioned in previous comment, you will need to be aware of the security aspects and risks - only use eval if you trust the JSON you're parsing!</p>
| 12,846
|
<p>I am thinking about making a website with some fairly intense JavaScript/canvas usage and I have been looking at <a href="http://ejohn.org/blog/processingjs/" rel="nofollow noreferrer">Processing.js</a> and it seems to me that it would make manipulating the canvas significantly easier. Does anyone know any reasons why I <strong>shouldn't</strong> use Processing.js? I understand that older browsers won't be able to use it, but for now that's ok.</p>
|
<p>As mentioned, IE is not supported by Processing.js (including IE8 beta). I've also found processing.js to be a bit slow in terms of performance, compared to just using canvas (especially if you're parsing a string with Processing language, instead of using the javascript API).</p>
<p>I personally prefer the canvas API over the processing wrapper, because it gives more me control. For example:</p>
<p>The processing line() function is implemented like this (roughly):</p>
<pre><code>function line (x1, y1, x2, y2) {
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.closePath();
context.stroke();
};
</code></pre>
<p>And you'd use it like this (assuming you're using the javascript-exposed API):</p>
<pre><code>var p = Processing("canvas")
p.stroke(255)
////Draw lines...///
p.line(0,0,10,10)
p.line(10,10,20,10)
//...and so on
p.line(100,100,200,200)
////End lines////
</code></pre>
<p>Notice that every line() call has to open and close a new path, whereas with the canvas API you can draw all the lines within a single beginPath/endPath block, improving performance significantly:</p>
<pre><code>context.strokeStyle = "#fff";
context.beginPath();
////Draw lines...///
context.moveTo(0, 0);
context.lineTo(10, 10);
context.lineTo(20, 10);
//...so on
context.lineTo(200, 200);
////End lines...///
context.closePath();
context.stroke();
</code></pre>
|
<p>I'd say use Flash instead. More browsers have Flash installed, than the number of browsers that work with processing.js. In addition, you'll get much better performance from Flash versus using JavaScript (at least for now, though there are projects in the works to speed up JS a lot, but it's still a little ways off)</p>
| 20,614
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.