instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. </p>
|
<p>Sure..it's pretty easy. Here's a fun app I threw together. I'm assuming you have Visual C++.</p>
<p>Save to test.cpp and compile: cl.exe /EHsc test.cpp</p>
<p>To test with your OCX you'll need to either #import the typelib and use it's CLSID (or just hard-code the CLSID) in the CoCreateInstance call. Using #import will also help define any custom interfaces you might need.</p>
<pre>
#include "windows.h"
#include "shobjidl.h"
#include "atlbase.h"
//
// compile with: cl /EHsc test.cpp
//
// A fun little program to demonstrate creating an OCX.
// (CLSID_TaskbarList in this case)
//
BOOL CALLBACK RemoveFromTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->DeleteTab(hwnd);
return TRUE;
}
void HideTaskWindows(ITaskbarList* ptbl)
{
EnumWindows( RemoveFromTaskbarProc, (LPARAM) ptbl);
}
// ============
BOOL CALLBACK AddToTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->AddTab(hwnd);
return TRUE;// continue enumerating
}
void ShowTaskWindows(ITaskbarList* ptbl)
{
if (!EnumWindows( AddToTaskbarProc, (LPARAM) ptbl))
throw "Unable to enum windows in ShowTaskWindows";
}
// ============
int main(int, char**)
{
CoInitialize(0);
try {
CComPtr<IUnknown> pUnk;
if (FAILED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**) &pUnk)))
throw "Unabled to create CLSID_TaskbarList";
// Do something with the object...
CComQIPtr<ITaskbarList> ptbl = pUnk;
if (ptbl)
ptbl->HrInit();
HideTaskWindows(ptbl);
MessageBox( GetDesktopWindow(), _T("Check out the task bar!"), _T("StackOverflow FTW"), MB_OK);
ShowTaskWindows(ptbl);
}
catch( TCHAR * msg ) {
MessageBox( GetDesktopWindow(), msg, _T("Error"), MB_OK);
}
CoUninitialize();
return 0;
}
</pre>
|
<p>@orion thats so cool. Never thought of it that way.</p>
<p>Well @jschroedl thats was fun indeed. </p>
<p>Testing an activex in console app is fun. But I think its worth not trying down that path. You can call the methods or set and get the properties either through the way @jschroedl had explained or you can call the IDIspatch object through the Invoke function. </p>
<p>The first step is to GetIDsByName and call the function through Invoke and parameters to the function should be an array of VARIANTS in the Invoke formal parameter list.</p>
<p>All is fine and dandy. But once you get to events its downhill from there. Windows application requires a message pump to fire events. On a console you don't have one. I went down the path to implement a EventNotifier for the events just like you implement a CallBack interface in classic C++ way. But the events doesn't get to your implemented interface. </p>
<p>I am pretty sure this cannot be done on a console application. But I am really hoping someone out there will have a different take on events in a console application</p>
| 3,852
|
<p>I have the following problem:</p>
<p>I open the dialog, open the SIP keyboard to fill the form and then minimize the SIP. Then when I close the current dialog and return to the main dialog the SIP keyboard appears again. Does anyone know how could I show/hide SIP keyboard programatically or better what could be done to solve the described problem. Once the user minimizes the keyboard it should not appear on the screen on dialog switching.</p>
<p>Thanks!</p>
|
<p>You'll want to call <strong>SipShowIM</strong>() in coredll. See this MSDN article:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms838341.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms838341.aspx</a></p>
|
<p>You can use the Microsoft.WindowsCE.Forms.InputPanel component. You can show/hide the SIP programmatically using the Enabled property. There is an InputPanel component at the toolbox.</p>
<p>There is also an EnabledChanged event for the InputPanel that you can handle. You usually want to show the SIP at a GetFocus event of a textbox.</p>
| 41,932
|
<p>I'm working on a billing system for a utility company, and we have the following requirements:</p>
<ul>
<li>Batch-generate and print approximately 1,500 bills per day that we then mail to customers</li>
<li>Save the bill in a format that can emailed to the customer and also archived (probably PDF)</li>
<li>Built with .NET with MS SQL Server database back-end</li>
</ul>
<p>I'd like some advice about the best way to accomplish this. I'm thinking about building a WPF application that would have the bill template that we bind the bill data to and print from. But I haven't used WPF before so I'm not sure if that's the best technology to use, and I can't get my head around how the batching and PDF conversion would work.</p>
<p>Any thoughts? Would WPF work, or is there a better solution?</p>
|
<p>If you are using a SQL Server backend, Reporting Services should work for you.</p>
<p>Otherwise I would recommend a third-party report generator that fits your reporting needs and create an app that uses it to create & export the reports.</p>
|
<p>Maybe you should try with ActiveReports.NET or DevExpress XtraReports to generate the reports first by code. Both have PDF export support so you can generate PDF files and send them by mail.</p>
| 14,264
|
<p>I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:</p>
<pre><code>var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
...
});
</code></pre>
<p>The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.</p>
<p>Is there a way to get the fields trimmed <strong>without</strong> doing the following:</p>
<pre><code>$("#name").val( jQuery.trim( $("#name") ) );
</code></pre>
|
<p>You could try looping through the object and triming everything.</p>
<pre><code>//Serialize form as array
var serializedForm = form.serializeArray();
//trim values
for(var i =0, len = serializedForm.length;i<len;i++){
serializedForm[i] = $.trim(serializedForm[i]);
}
//turn it into a string if you wish
serializedForm = $.param(serializedForm);
</code></pre>
|
<p>Neither of those solutions work, since they actually change the form fields on the page. I just want to modify the value of the field that without changing what the user typed in.</p>
| 26,923
|
<p>We have recently migrated a large, high demand web application to Tomcat 5.5 from Tomcat 4 and have noticed some peculiar slowdown behavior that appears to be related to JVM pauses. In order to run our application and support increased load over time on Tomcat 4, many not so standard JVM parameters were set and tuned as per the below, and I am hoping someone with Tomcat JVM tuning experience can comment on anything that would likely be detrimental to a Tomcat 5.5 install. Note also that some of these could be carry over from previous versions of Java (we were running Tomcat 4 on Java 1.6 with these parameters successfully for some time, but some may have been introduced to help garbage collection on Java 1.4 which was the basis of our Tomcat 4 install for a long time, and may now doing more harm than good).</p>
<p>Some notes:</p>
<ul>
<li>Application memory footprint is
around 1GB, probably slightly over.</li>
<li>CPU is not an issue - all machines
serving the app (load balanced) are
< 30% CPU</li>
<li>Lots of headroom on physical memory on the machines.</li>
<li>-XX:MaxPermSize=512m was the only parameter added as part of the 5.5 upgrade and was reactive to an outofmemory permgen space issue (which it solved).</li>
<li>Running on Java 1.6, Solaris OS</li>
</ul>
<p>-server -Xms1280m -Xmx1280m -XX:MaxPermSize=512m -XX:ParallelGCThreads=20 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX:TargetSurvivorRatio=75 -XX:MaxTenuringThreshold=0 -XX:+AggressiveOpts -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:-TraceClassUnloading -Dsun.io.useCanonCaches=false -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 </p>
|
<p>One of the Java Champions, Kirk Pepperdine's blog : <a href="http://kirk.blog-city.com/how_to_cripple_gc_ergonomics.htm" rel="noreferrer">http://kirk.blog-city.com/how_to_cripple_gc_ergonomics.htm</a>. <br>
Quote 1
"GC documentation will tell you what the setting affects but often without telling what the effect will be. The biggest clue that you've taken the wrong fork in the road is when you explicitly set a value and then give a hint to GC ergonomics. Another clue is if you don't have a sound reason to adjust a setting. And just because some so called expert says this setting works best is only noise, not sound and certanly not a reason."</p>
<p>Quote 2
"As I've stated in a prevous blog entry , don't touch the knobs unless you have a very good reason to do so. If you must touch the knobs, tred lightly by only using those that help ergonomics and not those that pin things down crippling ergonomics ability to meet your pause time and throughput goals."</p>
<p>So, I would suggest that you go back to plain <br>
-server -Xms1280m -Xmx1280m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:-TraceClassUnloading -Dsun.io.useCanonCaches=false -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000</p>
<p>Find if that gives you better performance. If yes, stick to it <br>
BTW, did -XX:MaxPermSize=378m have any issues ? <br>
Java 1.6 has much better ergonomics than 1.4. You might want to tune it less than 1.4<br>
BTW, did you try Tomcat 6 ? Tomcat 6 runs much better on Java 6 than Tomcat 5.5.<br></p>
<p>P.S : I've been using Tomcat for a while now and usually try to give sun's JDK free reign with little tuning here and there.</p>
|
<p>It may also be worth experimenting with an alternative JVM (like JRockit) to see if the differences in the garbage collection model are well suited to your application.</p>
| 24,763
|
<p>I have a need to convert Pixels to Points in C#. I've seen some complicated explanations about the topic, but can't seem to locate a simple formula. Let's assume a standard 96dpi, how do I calulate this conversion?</p>
|
<p>There are <a href="http://en.wikipedia.org/wiki/Point_%28typography%29" rel="noreferrer">72 points per inch</a>; if it is sufficient to assume 96 pixels per inch, the formula is rather simple:</p>
<p>points = pixels * 72 / 96</p>
<p>There is a way to get the configured pixels per inch of your display in Windows using <a href="https://msdn.microsoft.com/en-us/library/dd144877(v=vs.85).aspx" rel="noreferrer"><code>GetDeviceCaps</code></a>. Microsoft has a guide called <a href="http://msdn.microsoft.com/en-us/library/ms838191.aspx" rel="noreferrer">"Developing DPI-Aware Applications"</a>, look for the section "Creating DPI-Aware Fonts".</p>
<p>The W3C has defined the pixel measurement <code>px</code> as exactly <a href="https://www.w3.org/TR/css3-values/#absolute-lengths" rel="noreferrer">1/96th of 1in</a> regardless of the actual resolution of your display, so the above formula should be good for all web work.</p>
|
<p>Height lines converted into points and pixel (my own formula).
Here is an example with a manual entry of 213.67 points in the Row Height field:</p>
<pre class="lang-none prettyprint-override"><code>213.67 Manual Entry
0.45 Add 0.45
214.12 Subtotal
213.75 Round to a multiple of 0.75
213.00 Subtract 0.75 provides manual entry converted by Excel
284.00 Divide by 0.75 gives the number of pixels of height
</code></pre>
<p>Here the manual entry of 213.67 points gives 284 pixels.<br>
Here the manual entry of 213.68 points gives 285 pixels.</p>
<p>(Why 0.45? I do not know but it works.)</p>
| 16,892
|
<p>The title sort of explains itself. I am making some 'genrative' artwork in flash. Now I want to save the frame without making a screenshot so-on and sofort. And perhaps one day i would like to save a batch of frames. </p>
<p>Is there an AS3 class/library out there that could help me out ?</p>
|
<p>Actually, using the just released Flash 10, you CAN save to the HD! It's very handy, for just this situation. It's perfectly secure, because it only lets you save a file after the user clicks 'Save' in the file dialog, you can't just go writing files willy-nilly. Also, there is code out there already written that allows you to take snapshots using BitmapData, and compress to PNG or JPEG. I'd recommend PNG because it's lossless, which is nice for artwork you're creating.</p>
<p>Here's a few relevant links:</p>
<ul>
<li><a href="http://blog.everythingflex.com/2008/10/01/filereferencesave-in-flash-player-10/" rel="noreferrer">Example creating and saving a JPEG to local harddrive</a></li>
<li><a href="http://flashenabledblog.com/2008/05/19/tutorial-flash-player-10-beta-filereference/" rel="noreferrer">Video tutorial about loading & saving files</a></li>
<li><a href="http://sujitreddyg.wordpress.com/2008/11/04/filereference-in-flash-player-10/" rel="noreferrer">Another example, this time with text files</a></li>
<li><a href="http://livedocs.adobe.com/flex/gumbo/langref/flash/net/FileReference.html#save()" rel="noreferrer">API docs for FileReference.save()</a></li>
</ul>
|
<p>Do you want to save the file to a hard-drive or to a website?</p>
<p>If to a hard-drive, you might have a hard time unless you're open to using Air. Because of the security sandbox of Flash, you can't write arbitrary files to the user's hard disk. </p>
<p>If you absolutely must save it to a user's hard-drive using Flash and not Air, you'll probably have to send the bitmap data to a server-side PHP (or similar) script which will then allow the user to download and save the image in one location or another.</p>
| 34,416
|
<p>After successfully building dblink on solaris 10 using Sun C 5.9
SunOS_sparc 2007/05/03 and gmake.</p>
<p>I ran gmake installcheck and got the following output:</p>
<pre><code>========== running regression test queries ==========
test dblink ... FAILED
======================
1 of 1 tests failed.
</code></pre>
<p>The differences that caused some tests to fail can be viewed in the
file "./regression.diffs". A copy of the test summary that you see
above is saved in the file "./regression.out".</p>
<p>First error in regression.diffs file:</p>
<blockquote>
<p>psql:dblink.sql:11: ERROR: could not load library "/apps/postgresql/
lib/dblink.so": ld.so.1: postgre
s: fatal: relocation error: file /apps/postgresql/lib/dblink.so:
symbol PG_GETARG_TEXT_PP: referenced symbol not found</p>
</blockquote>
<p>I am running postgreSQL version 8.2.4 with the latest dblink source.</p>
<p>Has anyone got any idea what I need to do to solve this problem.
Thanks. </p>
|
<p>To solve this issue I tried using the 8.2 dblink sources, instead of the latest version.</p>
<p>You also need to make sure you use gnu make not the sun make.</p>
|
<p>Does the file it is looking for actually exist? Is it in that location?</p>
<p>It may be one of a few things I can think of:
1) The thing did not compile, and therefore does not exist.
2) It exists, but somewhere else, and the environment variable that tells it where to find it is set wrong.
3) The permissions are such that the ID that the postmaster is running as cannot traverse to that directory.</p>
<p>To check if it is somewhere else:</p>
<pre><code>find / -type f|grep dblink.so
</code></pre>
<p>To check the permissions:</p>
<pre><code>su -
su - postgres
less /apps/postgresql/ lib/dblink.so
</code></pre>
| 9,539
|
<p>we all writing code for single processor.
i wonder when we all are able to write code on multi processors?</p>
<p>what do we need (software tools, logic, algorithms) for this switching?</p>
<p>edit: in my view, as we do many task parallely, same way we need to convert those real life solutions(algorithms) to computer lang. just as OOPs coding did for procedural coding. OOPs is more real life coding style than procedural one. so i hope for that kind of solutions. </p>
|
<p>I think the most important requirement is a good language that has native constructs that support parallelism or one that can automatically generate parallel code. There are quite a few languages that fit that description, but none of them is popular enough to really be considered for mainstream use. That, in turn is caused by several things:</p>
<ol>
<li>By their very nature, these languages are very different from today's imperative languages, and are therefor harder to learn (or at least seem that way).</li>
<li>They often lack good tools and libraries, making them unusable for any "real" project.</li>
</ol>
<p>Of course, if it were more popular more people would be willing to learn it and there would be more support, so it's a kind of cycle that's pretty hard to break out of. I guess all we can do is hope. :)</p>
<p>An example of a language designed with heavy parallelization in mind is Erlang - and it's actually used in commercial projects.</p>
|
<p>There is no simple answer, and in many ways even the complex answers are currently inadequate or incomplete. You'll get a better answer if you are more specific about the replies you want: pointers to dev libraries and tools, instructional materials, pointers to current research projects and issues in this area, or something else?</p>
| 11,570
|
<p>I'm trying to create a query which uses a list of ids in the where clause, using the Silverlight ADO.Net Data Services client api (and therefore Linq To Entities). Does anyone know of a workaround to Contains not being supported?</p>
<p>I want to do something like this:</p>
<pre><code>List<long?> txnIds = new List<long?>();
// Fill list
var q = from t in svc.OpenTransaction
where txnIds.Contains(t.OpenTransactionId)
select t;
</code></pre>
<hr>
<p>Tried this:</p>
<pre><code>var q = from t in svc.OpenTransaction
where txnIds.Any<long>(tt => tt == t.OpenTransactionId)
select t;
</code></pre>
<p>But got "The method 'Any' is not supported".</p>
|
<p><strong>Update:</strong> EF ≥ 4 supports <a href="http://msdn.microsoft.com/en-us/library/bb352880.aspx" rel="noreferrer" title="Enumerable.Contains<T>"><code>Contains</code></a> directly (Checkout <a href="http://msdn.microsoft.com/en-us/library/bb534972.aspx" rel="noreferrer" title="Enumerable.Any<T>"><code>Any</code></a>), so you don't need any workaround.</p>
<pre><code>public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
IEnumerable<TValue> collection
)
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
if (!collection.Any())
return query.Where(t => false);
ParameterExpression p = selector.Parameters.Single();
IEnumerable<Expression> equals = collection.Select(value =>
(Expression)Expression.Equal(selector.Body,
Expression.Constant(value, typeof(TValue))));
Expression body = equals.Aggregate((accumulate, equal) =>
Expression.Or(accumulate, equal));
return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}
//Optional - to allow static collection:
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
params TValue[] collection
)
{
return WhereIn(query, selector, (IEnumerable<TValue>)collection);
}
</code></pre>
<p>USAGE:</p>
<pre><code>public static void Main()
{
using (MyObjectContext context = new MyObjectContext())
{
//Using method 1 - collection provided as collection
var contacts1 =
context.Contacts.WhereIn(c => c.Name, GetContactNames());
//Using method 2 - collection provided statically
var contacts2 = context.Contacts.WhereIn(c => c.Name,
"Contact1",
"Contact2",
"Contact3",
"Contact4"
);
}
}
</code></pre>
|
<p>Here's an example where I demonstrate how to write set-based queries using the DataServiceContext :
<a href="http://blogs.msdn.com/phaniraj/archive/2008/07/17/set-based-operations-in-ado-net-data-services.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/phaniraj/archive/2008/07/17/set-based-operations-in-ado-net-data-services.aspx</a></p>
| 48,945
|
<p>I am new to Python, and I'm working on writing some database code using the <code>cx_Oracle</code> module. In the <a href="http://cx-oracle.sourceforge.net/html/module.html" rel="nofollow noreferrer">cx_Oracle documentation</a> they have a code example like this:</p>
<pre><code>import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc.args
print >> sys.stderr, "Oracle-Error-Code:", error.code
print >> sys.stderr, "Oracle-Error-Message:", error.message
</code></pre>
<p>My question has to do with where the "error" object is created. What does the "<code>, =</code>" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)</p>
<p>I know that the exc.args is a singleton tuple, but I just don't understand the "<code>, =</code>" syntax. If I remove the comma, I get the error message, "<code>AttributeError: 'tuple' object has no attribute 'code'</code>". </p>
<p>Can someone point me to where this is documented? Thanks!</p>
<p><strong>EDIT:</strong></p>
<p>This works without having to unpack the tuple:</p>
<pre><code>import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code
print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message
</code></pre>
|
<pre><code>error, = exc.args
</code></pre>
<p>This is a case of <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">sequence unpacking</a>.</p>
<p>A more readable way to write the same, and the style I personally favor, is:</p>
<pre><code>[error] = exc.args
</code></pre>
<p>There are two bits required to understand the previous example:</p>
<ol>
<li>When the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS.</li>
<li>A one-item tuple in python is written <code>(foo,)</code>. In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator.</li>
</ol>
|
<p>The comma serves to unpack the tuple, i.e. it extracts the single item of the tuple, and binds it to <code>error</code>. Without the comma, you would bind the tuple itself, rather than its content.</p>
| 39,014
|
<p>In Informix, how can I cast a <code>char(8)</code> type into a <code>money</code> type, so that I can compare it to another <code>money</code> type?</p>
<p>Using "<code>tblAid.amt::money as aid_amt</code>" did not work.
Using "<code>(tblAid.amt * 1) AS aid_amt</code>" did not work.</p>
|
<p>try this --> </p>
<pre><code>select (disb_amt::NUMERIC) disb_amt from tmp_kygrants;
</code></pre>
<p>You may be able to compare the amounts as numeric.</p>
|
<p>'tis been a while since I played around with informix and I don't have a running instance handy at the moment. However, there are two things that can cause a problem here:</p>
<p>1) since it is a char(8) it can contain values that can not be casted to numeric without a bit of 'cleanup'. E.g. "abc". Or "1,234,567.00".<br>
2) Trailing spaces. (char as opposed to varchar).</p>
<p>What informix error do you get on your explicit cast (::money)?</p>
| 21,474
|
<p>I guess this topic is often overseen, but is rather useful when debugging your code. Just today I have stumbled across this simple yet effective visualizer that visualizes images (it's on a german blog, but I guess the code content is self-explanatory):</p>
<p><a href="http://blogs.msdn.com/dparys/archive/2007/10/23/das-debugger-visualizer-item-template.aspx" rel="nofollow noreferrer">link text</a></p>
<p>I would like to know which debug visualizers you use in your daily work with VS2005/2008.</p>
|
<p>I use <a href="http://karlshifflett.wordpress.com/mole-for-visual-studio/" rel="noreferrer">Mole</a>.</p>
<blockquote>
<p>Mole was designed to not only allow
the developer to view objects or data,
but to also allow the developer to
drill into properties of those objects
and then edit them. Mole allows
unlimited drilling into objects and
sub-objects.</p>
</blockquote>
|
<p>There was a sample on an MSDN blog for the Microsoft.Xna.Framework.Matrix, I think it was. I later made my own, but it was still good.</p>
| 12,584
|
<p>I have a database with two tables (<code>Table1</code> and <code>Table2</code>). They both have a common column <code>[ColumnA]</code> which is an <code>nvarchar</code>. </p>
<p>How can I select this column from both tables and return it as a single column in my result set?</p>
<p>So I'm looking for something like:</p>
<pre><code>ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
</code></pre>
|
<pre><code>SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
</code></pre>
<p>Also, if you know the contents of Table1 and Table2 will <strong>NEVER</strong> overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.</p>
<p>-- Kevin Fairchild</p>
|
<p>You can use a union select: </p>
<pre><code>Select columnA from table1 union select columnA from table2
</code></pre>
| 6,588
|
<p>I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code.</p>
<p>What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item.
Then you go off and may display some DisplayMember and a ValueMember and so on.</p>
<p>If I want to retrieve that value later I need to typecast my object back to what it was. Like with strings getting the value takes</p>
<pre><code>string value = (string)combobox1.SelectedItem;
</code></pre>
<p>Since there are generics in the Framework for quite some time now, I still wonder why in the Hell not one control from the standard toolbox is generic.</p>
<p>I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object. But everytime I need to access that object I then need another typecast.</p>
<p>Why cant I just create a ComboBox or ListView with items of type ListViewItem</p>
<p>Am I missing something here or is this just another example of not perfectly well thought through controls?</p>
|
<p>While the criticism of "didn't use generics" can't be fairly applied to controls developed before their existence... one must wonder about WPF controls (new in .NET 3.0, after generics in .NET 2.0).</p>
<p>I checked out the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.addchild.aspx" rel="nofollow noreferrer">AddChild</a> method in <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox_members.aspx" rel="nofollow noreferrer">ComboBox</a>. It takes an object parameter (ugh).</p>
<p>This control is intended to be used primarily via XAML. Was this done this way because there is no way to specify a type parameter in XAML? (aside, is there no way to specify a type parameter in XAML?)</p>
<p>Sorry to have no definitive "Why" answer, just sharing the common misery of needing to cast when working with the UI.</p>
|
<p>I dont think you're missing anything.
It's just that these classes were created back in the pre-Generics days, and WinForms is simply not cutting edge enough for MS to spend a lot of time changing or extending the API.</p>
| 42,930
|
<p>I've recently started using Eclipse Ganymede CDT for C development and I couldn't like it more. I'm aware the learning curve could be sort of pronounced, therefore and with your help, my goal is to flatten it as much as possible. I'm looking for the best hacks, hints, tips, tricks, and best practices to really unleash the full power of the IDE.</p>
|
<p><strong>Accurate Indexing</strong></p>
<p>With CDT you should be sure to enable the "Full Indexing" option rather than the "Fast Indexing" default. It's not perceptibly slower on modern hardware and it does a much better job. In that vein, you should be sure to enable semantic highlighting. This isn't as important in C/C++ as it is in a language like Scala, but it's still extremely useful.</p>
<p><strong>Streamlined Editing</strong></p>
<p>Get used to using <kbd>Ctrl</kbd>+<kbd>O</kbd> and <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>H</kbd>. The former pops up an incrementally searchable outline view, while the latter opens the "Call Hierarchy" view and searches on the currently selected function. This is incredibly useful for tracing execution.</p>
<p><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>T</kbd> (Open Type) isn't exactly an "editing" combo per se, but it is equally important in my workflow. The C++ Open Type dialog not only allows incremental filtering by type, but also selecting of definition (<code>.h</code>) or declaration (<code>.cpp</code>) and even filtering by element type (<code>typedef</code>, <code>struct</code>, <code>class</code>, etc).</p>
<p><strong>Task Oriented Programming</strong></p>
<p>Mylyn: never leave home without it. I just can't say enough about this tool. Every time I'm forced to do without it I find myself having to re-learn how to deal with all of the code noise. Very, very handy to have.</p>
<p><strong>Stripped Down Views</strong></p>
<p>The default Eclipse workspace layout is extremely inefficient both in space and in usability. Everyone has their favorite layout, take some time and find yours. I like to minimize (not necessarily close) everything except for Outline and keep the C/C++ Project Explorer docked in the sidebar configured to precisely hide the Outline when expanded. In this way I can always keep the editor visible while simultaneously reducing the space used by views irrelevant to the current task.</p>
|
<p><strong>If the Java Developer Tools aren't installed the Spellcheck won't work.</strong></p>
<p>The Spellcheck functionality is dependent upon the Java Development Tools being installed. This can be a perplexing issue if you just install the C Development Tools exclusively, because it gives no reason for the Spell Checker not working.</p>
| 9,469
|
<p>i'm wondering if there is any nice and neat tool to replace the GNU Autotools or Make to build a very large C++ project, which are such a complicated thing to use. </p>
<p>It is simple to generate all the files that de Autotools require if the project is small, but if the source code is divided in many directories, with multiple third party libraries and many dependencies, you fall into the "Autotools Hell"..</p>
<p>thanks for any recommendations</p>
|
<p>The <a href="http://code.google.com/p/v8/" rel="noreferrer">Google V8 JavaScript Engine</a> is written in C++ and uses <a href="http://www.scons.org/" rel="noreferrer">SCons</a>, so I guess that's one vote for it.</p>
|
<p>I use <a href="http://www.bakefile.org/index.html" rel="nofollow noreferrer">bakefile</a> for my build process and I became a big fan!</p>
<p>I never have to write a Makefile myself anymore, let alone horrible GNU autotools scripts. All I have to do is provide an <code>XML</code> file that describes the build targets. Bakefile can convert this into a Makefile that gets all the (header file) dependencies right etc, where different Makefile formats may be chosen (pasting the list from the documentation):</p>
<pre><code>available formats are:
autoconf GNU autoconf Makefile.in files
borland Borland C/C++ makefiles
dmars Digital Mars makefiles
dmars_smake Digital Mars makefiles for SMAKE
gnu GNU toolchain makefiles (Unix)
mingw MinGW makefiles (mingw32-make)
msevc4prj MS eMbedded Visual C++ 4 project files
msvc MS Visual C++ nmake makefiles
msvc6prj MS Visual C++ 6.0 project files
msvs2003prj MS Visual Studio 2003 project files
msvs2005prj MS Visual Studio 2005 project files
symbian Symbian development files
watcom OpenWatcom makefiles
xcode2 Xcode 2.4 project files
</code></pre>
<p>I usually use the <em>autoconf</em> option, and it writes the annoying GNU autotools scripts for me. I did have to adapt the <code>configure.ac</code> script, so that configure finds a certain library on any system. But it wasn't too bad. Getting the autoconf scripts in this way is nice, because I don't have to write them all by myself, and when I distribute my project it will look as if I had written them, and users can still build my project in the god-given way, with </p>
<pre><code>./configure && make && make install
</code></pre>
| 7,827
|
<p>Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.</p>
<p>Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc.</p>
<p>Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole? </p>
|
<p>What I found works best is to really learn CSS. I mean <strong>really</strong> learn CSS.</p>
<p>It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things.</p>
<p>The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it.</p>
<p>Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you <strong>really</strong> practice at it and learn what works and what doesn't, and how to get around problems.</p>
<p>All it takes is practice and in time you can become good at it.</p>
|
<p>CSS takes a bit of time to learn, but the thing I initially found most discouraging was the fact that so many hacks were needed to get all browsers to behave the same way. Learning a system which doesn't adhere to logic seems dumb... but I've clung to the vague belief that there is logic behind each browser's idiosyncrasy, in the form of the W3 spec. It seems that the new generation browsers are slowly coming into line - but IE6 still makes my life hell on a daily basis.</p>
<p>Maybe creating an abstraction layer between compliant/valid CSS code and the browsers' shoddy implementations wouldn't be a bad thing. But if such a thing was created - would it need to be powered by JS (or jQuery)? (and would that create an unreasonably burden, in terms of processing cost?)</p>
<p>I've found that it useful to 'level the ground' when scripting with CSS. There are probably loads of different flavours of reset script out there - but using YUI resets has helped me to reduce the number of quirks I'd otherwise encounter - and YUI grids make life a little easier sometimes. </p>
| 4,507
|
<p>I have an existing website that uses the same code base, but is deployed in a number of different configurations on different servers. Each configuration has a set of users, and they can upload personal files. The files are stored in an "uploaded files" directory on each server, and this directory is stuck in right next to the code that runs the site.</p>
<p>I am trying to bring the codebase into Subversion so we can manage things better, and also use SVN to make deployment easier as well, however, on each server the user files will be different. I understand that the best way to handle this would be to store the user files elsewhere, but at this point, that isn't an option. </p>
<p>So, with that in mind, how can I use Subversion in light of this situation?</p>
|
<p>Don't check it in that way you can't overwrite anything. For config.ini files and the like you can store a template version with a different name (ie. config.ini.tmpl) in your repository that won't overwrite the actual file. </p>
<p>Add the folder/files to your svn ignore so you don't check them in by accident.</p>
<p>It is also good practice to export to a new folder then do a quick mv or httpd.conf edit, apache restart to change to the new version all at once. If you do that you can copy the upload files and/or keep the old version as backup in case something goes screwy with your deployment or the new version of the code.</p>
|
<p>Just don't store that folder in your repository, eg. never check that folder in. I don't really see a problem here...</p>
| 28,592
|
<p>I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location.</p>
<p>I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file).</p>
<p>The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed.</p>
<p>Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome.</p>
<p>I did find something in the .NET framework which should work, ie:</p>
<p><pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile</code></pre></p>
<p>The problem is that this is returning empty strings, which does not help.</p>
<p>I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted.</p>
|
<p>What I discovered is that </p>
<pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile
</code></pre>
<p>only returns non-null when there is no path explicitly defined. As soon as you specify a path which is not the default, then this function returns that path correctly.</p>
<p>So, a simple workaround was to check whether this function returns a string, or null. If it returns a string, then use that, but if it's null, use</p>
<pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Information.RootDirectory + "\\DATA\\"
</code></pre>
|
<p>One option, that may be a simpler solution, is to create a new database on your destination server and then RESTORE over that database with your backup. Your backup will be in the right place and you will not have to fuss with "MOVING" the backup file when you restore it. SQL expects backups to be restored to exactly the same physical path that they were backed up from. If that is not the case you have to use the MOVE option during RESTORE.
This solution also makes it easier to rename the database in the process if, for example, you want to tack a date onto the name.</p>
| 8,854
|
<p>I am using Oracle adapter from the BizTalk Adapter Pack (WCF based for BTS 2006 R2). In the configuration of the "solicit-response" send ports, I have used Oracle's username and password to connect to the database. </p>
<p>Now I would like to change that and use the SSO. So far I have created the Affiliate application and mapped the BTS Host Instance "user id" to the Oracle database user details.</p>
<p>When I run the application I am constantly getting the error: "Unable to redeem ticket, no ticket exists in the message".</p>
<p>reading through the BTS documentation I found the following at "ms-help://MS.BTS.2006/BTS06CoreDocs/html/c7bf755c-c37d-4b19-9817-a7f42e1e9656.htm":
In scenarios where an orchestration invokes the send adapter, the BizTalk Messaging Engine sends the message to the MessageBox database. The orchestration should ensure that both the <strong>SSOTicket</strong> context property and the <strong>Microsoft.BizTalk.XLANGs.BTXEngine.OriginatorSID</strong> context property of the message that contains the ticket are maintained. When the adapter receives this message from the MessageBox database, the adapter calls the RedeemTicket method with the encrypted ticket to retrieve the back-end credentials from the SSO store. The user designing the orchestration should specifically copy this property to the message.</p>
<p>But I receive a message through SQL integrated connection, that doesn't have the SSO Ticket.</p>
<p>Please help to resolve this issue?</p>
|
<p>You can add an SSO ticket in a custom pipeline component on the send port. The following code works for me:</p>
<pre><code> public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
ISSOTicket ssoTicket = new ISSOTicket();
pInMsg.Context.Write("SSOTicket", "http://schemas.microsoft.com/BizTalk/2003/system-properties", ssoTicket.IssueTicket(0));
return pInMsg;
}
</code></pre>
<p>This will generate a ticket for the Biztalk host instance service account, so your Oracle affiliate application mapping should work as you expect.</p>
|
<p>You might need to "Allow tickets" to the System properties in SSO Administrator. Without that it will not work even if you allow tickets to the Affiliate Application.</p>
| 24,287
|
<p>I've seen examples like this: </p>
<pre><code>public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
</code></pre>
<p>and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants. </p>
|
<p>That is perfectly acceptable, probably even the standard.</p>
<pre><code>(public/private) static final TYPE NAME = VALUE;
</code></pre>
<p>where <code>TYPE</code> is the type, <code>NAME</code> is the name in all caps with underscores for spaces, and <code>VALUE</code> is the constant value;</p>
<p>I highly recommend NOT putting your constants in their own classes or interfaces. </p>
<p>As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.</p>
<p>For example:</p>
<pre><code>public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
</code></pre>
<p>That is legal and <code>ORIGIN</code> would then be a point at (3, 0).</p>
|
<p>I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)</p>
| 9,174
|
<p>I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.</p>
<p>Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.</p>
<p>My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage?</p>
<p>I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.</p>
<p>Any thoughts would be appreciated. Thanks.</p>
|
<p>When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example:</p>
<pre><code>ServletOutputStream out = response.getOutputStream();
InputStream in = [ code to get source input stream ];
String mimeType = [ code to get mimetype of data to be served ];
byte[] bytes = new byte[FILEBUFFERSIZE];
int bytesRead;
response.setContentType(mimeType);
while ((bytesRead = in.read(bytes)) != -1) {
out.write(bytes, 0, bytesRead);
}
// do the following in a finally block:
in.close();
out.close();
</code></pre>
<p>I do agree with toby, you should instead "point them to the S3 url."</p>
<p>As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception.</p>
<p>Edit - Regarding:</p>
<blockquote>
<p>In this use case the images can contain sensitive data...</p>
</blockquote>
<p>When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is:</p>
<ol>
<li>Initial HTML page has download links to your webapp</li>
<li>User clicks on a download link</li>
<li>Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes.</li>
<li>Send an HTTP redirect to the client with the URL from step 3.</li>
<li>The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion.</li>
</ol>
|
<p>You have to check two things:</p>
<ul>
<li>Are you closing the stream? Very important</li>
<li>Maybe you're giving stream connections "for free". The stream is not large, but many many streams at the same time can steal all your memory. Create a pool so that you cannot have a certain number of streams running at the same time</li>
</ul>
| 7,952
|
<p>I am absolutely new to the .NET world, and started with C# on friday. I have some experience with database apps, though.</p>
<p>We will go with LINQ-to-SQL for a medium scale project. I am used to generating my schema from classes and keep track of changes with subversion and equivalents to Ruby's Migrations. There obviously is <a href="https://stackoverflow.com/questions/29145/generating-database-tables-from-object-definitions">no easy way to do this with LINQ</a> itself.</p>
<p>So I thought of generating the schema (and do some data access) with <a href="http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle Project's ActiveRecord</a> and use <a href="http://code.google.com/p/migratordotnet/" rel="nofollow noreferrer">Migrator.NET</a> <a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement" rel="nofollow noreferrer">Tarantino</a> or <a href="http://sourceforge.net/projects/dbdeploy-net/" rel="nofollow noreferrer">dbdeploy.net</a> for the schema updates. (Any suggestions for this?)</p>
<p>My main question is: <strong>How do I verify that my LINQ classes still match the database schema? Does LINQ throw exceptions if the schema does not match? Can I iterate over all the LINQ classes and invoke some verify method?</strong></p>
<p>I already found that <a href="https://stackoverflow.com/questions/40022/best-way-to-update-linq-to-sql-classes-after-database-schema-change">sqlmetal is the way to regenerate the classes</a>.</p>
<p>PS: We will use SQL Server (2008 or 2005).</p>
|
<p>This <a href="http://blog.huagati.com/res/index.php/2008/07/17/tools-part-2-add-ins-dbml-synchronization-add-in-updated/" rel="nofollow noreferrer">tool</a> will help sync them, but I'm unsure if it'll show differences...may be of some use though. (:</p>
<p>EDIT: As <a href="https://stackoverflow.com/users/11241/kristofera">KristoferA</a> said in his comment, it does support comparisons (: - thanks KristoferA.</p>
|
<p>This <a href="http://blog.huagati.com/res/index.php/2008/07/17/tools-part-2-add-ins-dbml-synchronization-add-in-updated/" rel="nofollow noreferrer">tool</a> will help sync them, but I'm unsure if it'll show differences...may be of some use though. (:</p>
<p>EDIT: As <a href="https://stackoverflow.com/users/11241/kristofera">KristoferA</a> said in his comment, it does support comparisons (: - thanks KristoferA.</p>
| 38,173
|
<p>I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)</p>
|
<p><strong>EDIT</strong></p>
<p>As @Adam points out in the comments, there is a native jQuery mechanism that basically does the same thing as the hack in my original answer. Using jQuery you can do</p>
<pre><code> $('[id$=myButton]').click(function(){ alert('button clicked'); });
</code></pre>
<p>My hack was originally developed as a Prototype work around for ASP.NET and I adapted it for the original answer. Note that jQuery basically does the same thing under the hood. I recommend using the jQuery way, though, over implementing my hack.</p>
<p><strong>Original answer left for comment context</strong></p>
<p>When you use a master page, ASP.NET mangles the names of the controls on the dependent pages. You'll need to figure out a way to find the right control to add the handler to (assuming you're adding the handler with javascript).</p>
<p>I use this function to do that:</p>
<pre><code>function asp$( id, tagName ) {
var idRegexp = new RegExp( id + '$', 'i' );
var tags = new Array();
if (tagName) {
tags = document.getElementsByTagName( tagName );
}
else {
tags = document.getElementsByName( id );
}
var control = null;
for (var i = 0; i < tags.length; ++i) {
var ctl = tags[i];
if (idRegexp.test(ctl.id)) {
control = ctl;
break;
}
}
if (control) {
return $(control.id);
}
else {
return null;
}
}
</code></pre>
<p>Then you can do something like:</p>
<pre><code>jQuery(asp$('myButton','input')).click ( function() { alert('button clicked'); } );
</code></pre>
<p>where you have the following on your child page</p>
<pre><code><asp:Button ID="myButton" runat="server" Text="Click Me" />
</code></pre>
|
<p>I also started with the simplest of examples and had no luck. I finally had to add the jquery .js file <em>outside</em> of the <code><head></code> section of the master page. It was the only way I could get anything to work in Firefox (haven't tried other browsers just yet).</p>
<p>I also had to reference the .js file with an absolute address. Not entirely sure what's up with that one.</p>
| 37,358
|
<p>Where does Firefox store cookies and in what format are they stored</p>
|
<h1>For Windows</h1>
<p>Your cookies are stored in:</p>
<ul>
<li>In Firefox 2.x: plain text file (<code>cookies.txt</code>) in a unix-format text file (eg LF instead of CRLF for newlines).</li>
<li>In Firefox 3.0 and up: a binary file representing <a href="http://www.webdevbros.net/2008/07/31/query-your-firefox-cookies-with-sql/" rel="noreferrer"><strong>SQLite database</strong> on which you can make queries</a> (<a href="http://kb.mozillazine.org/Cookies" rel="noreferrer"><strong><code>cookies.sqlite</code></strong></a>).</li>
</ul>
<p>The file is located under your <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=ro&comments_parentId=192052&forumId=1" rel="noreferrer">profile folder</a>:</p>
<pre><code>C:\Documents and Settings\username\Application Data\Mozilla\Firefox\Profiles\xxxx.default
</code></pre>
<p>where <code>xxxx</code> is some random-appearing alphanumeric string.</p>
<p>You might want to install the Firefox plugin <a href="http://www.bitstorm.org/extensions/view-cookies/" rel="noreferrer">View Cookies</a> to better manage them.</p>
<p><img src="https://i.stack.imgur.com/Wwunb.jpg" alt="alt text" /></p>
<h1>For Linux</h1>
<p>Your cookies are stored at:</p>
<pre><code>~/.mozilla/firefox/xxxx.default/cookies.sqlite
</code></pre>
<p>where <code>xxxx</code> is some random-appearing alphanumeric string.</p>
|
<p>The directory depends on your OS, but they appear to be stored in a SQLite database.</p>
| 38,812
|
<p>I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?</p>
|
<p>Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix.</p>
<p><a href="http://www.regular-expressions.info/" rel="nofollow noreferrer">http://www.regular-expressions.info/</a></p>
<p>Here is the pattern that worked in some preliminary tests:</p>
<pre><code><!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? -->
</code></pre>
<p>It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix.</p>
<p>Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.</p>
|
<p>I'm using this application to test the regex:</p>
<p><a href="http://www.regular-expressions.info/dotnetexample.html" rel="nofollow noreferrer">http://www.regular-expressions.info/dotnetexample.html</a></p>
<p>I have tested it against some fairly good data and it seems to be pulling out only the commented section.</p>
| 11,179
|
<p>Can somebody in SO please provide me with a list of resources about Enterprise Mashups and technologies related to SharePoint platform?</p>
<p><strong>Update</strong> (as per suggestion of @Spoon16 in the comments):-
The mashup application may typically retrieve a list of contacts from a SharePoint site and display the address of a selected contact person on a map (again maybe Google maps).</p>
|
<p>There are a number of different ways to pull external information into SharePoint.</p>
<p>For mashing up SharePoint data in external applications:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms479390.aspx" rel="nofollow noreferrer">Web Services</a>; great web services coverage for the underlying API will allow you to build external mashups (like the one you mention in your question comment). Specifically take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms479390.aspx" rel="nofollow noreferrer">Lists Service</a>.</li>
</ul>
<p>For mashing up external data sources inside of SharePoint:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms563661.aspx" rel="nofollow noreferrer">Business Data Catalog</a>; when you have the enterprise version of Microsoft Office SharePoint Portal server you can use the Business Data Catalog to interact with a very wide variety of external datasources in a read/write fashion. Works with relational databases and web services.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms570748.aspx" rel="nofollow noreferrer">Enterprise Search</a>; the indexing capabilities provided by SharePoint's Enterprise search technology are extensive</li>
<li><a href="http://office.microsoft.com/en-us/sharepointserver/HA101079761033.aspx" rel="nofollow noreferrer">RSS Web Part</a>; allows you to consume and apply XSLT transform to any RSS feed and output the result on any SharePoint page</li>
<li><a href="http://office.microsoft.com/en-us/sharepointtechnology/HA011609261033.aspx" rel="nofollow noreferrer">Page Viewer Web Part</a>; allows an iframe to be embedded on any page, provides an easy mechanism of integrating external applications into the SharePoint environment</li>
</ul>
<p>SharePoint has an <a href="http://msdn.microsoft.com/en-us/sharepoint/default.aspx" rel="nofollow noreferrer">extensive development framework</a> that enables you to leverage the full capabilities of the .NET framework to make your wildest mashup dreams come true. You can use even add additional services to SharePoint that expose the underlying data in custom ways (not covered by the Out of the Box web services) if you like.</p>
|
<p>Also it is possible to customize List View in order to render Map using <a href="https://developers.google.com/maps/documentation/javascript/" rel="nofollow noreferrer">Google Maps</a>.</p>
<h2>Solution description</h2>
<p>For storing geographical locations and visualizing it on Map is used Custom List. Custom List is based on Generic List with Custom Content Type and with View to render Map.</p>
<p>Map List View is implemented using custom XSLT style sheet and JavaScript rendering control for Map.</p>
<p>For implementation details please follow post <a href="http://vgrem.wordpress.com/2012/12/21/bringing-map-functionality-into-sharepoint-2010-rendering-map-list-view/" rel="nofollow noreferrer">Bringing Map functionality into SharePoint 2010: Rendering Map List View</a></p>
<h2>Usage</h2>
<p>For specified solution we only need to create List instance for storing contacts and populate it. </p>
<p>Form for saving of geographical locations
<img src="https://i.stack.imgur.com/ViRge.png" alt="enter image description here"></p>
<p>Map List View
<img src="https://i.stack.imgur.com/8s6Rp.png" alt="enter image description here"></p>
| 12,557
|
<p>I'd like to upload (via ftp) a website when doing a release build in visual studio 2008. I don't want any source code files to be uploaded and it would be nice to configure which folders should get uploaded. I'm using either ASP.NET Web Applications or MVC. How do I configure VS.NET to automatically upload (and overwrite) the last deployed website?</p>
|
<p>You can use the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en" rel="nofollow noreferrer">Visual Studio Web Deployment Project</a> Add In from Microsoft.</p>
<p>I use this with MSBuild as part of CruiseControl, its very nice, and with some of the <a href="http://msbuildtasks.tigris.org/" rel="nofollow noreferrer">Community Tasks for MS Build</a> you can do *.config (or any XML file) substitutions as part of your build process.</p>
<p>Edit: I also see that the MSBuild Community Tasks includes an FtpUpload action. This should be exactly what you need.</p>
|
<p>Or you can use nant</p>
| 24,888
|
<p>If I click on File -> Close, it closes the buffer like I want, but doesn't list a key mapping. What is the key mapping?</p>
|
<p>You can use <code>C-x k</code> to kill current buffer. See <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Kill-Buffer.html">Emacs Manual</a> .</p>
|
<ol>
<li><code>C-x k</code> to kill the current buffer.</li>
<li><code>C-x 0</code> to close the current window.</li>
<li><code>C-x 1</code> to close every other window.</li>
</ol>
| 25,426
|
<p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
|
<p>Use Imagemagick, or better yet, Ghostscript.</p>
<p><a href="http://www.ibm.com/developerworks/library/l-graf2/#N101C2" rel="noreferrer">http://www.ibm.com/developerworks/library/l-graf2/#N101C2</a> has an example for imagemagick:</p>
<pre><code>convert foo.pdf pages-%03d.tiff
</code></pre>
<p><a href="http://www.asmail.be/msg0055376363.html" rel="noreferrer">http://www.asmail.be/msg0055376363.html</a> has an example for ghostscript:</p>
<pre><code>gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit
</code></pre>
<p>I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.</p>
|
<p>I like PDFTIFF.com to <a href="http://www.pdftiff.com" rel="nofollow noreferrer">convert PDF to TIFF</a>, it can handle unlimited pages</p>
| 10,114
|
<p>Are there any industry standard conventions for naming jar files?</p>
|
<p>I have been using </p>
<pre><code>*Informative*-*name*-*M*.*m*.*b*.jar
</code></pre>
<p>Where:</p>
<p><em>M</em> = <code>major version number</code> (changed when backward compatibility is not necessarily maintained)</p>
<p><em>m</em> = <code>minor version number</code> (feature additions etc)</p>
<p><em>b</em> = <code>build number</code> (for releases containing bug fixes)</p>
|
<p>If your jar is used for JEE then <a href="http://www.oracle.com/technetwork/java/namingconventions-139351.html" rel="nofollow">these guidelines</a> apply:</p>
<blockquote>
<p>The module name is used as the EJB archive name. By default, the
module name should be based on the package name and should be written
in all-lowercase ASCII letters. In case of conflict, the module name
should be a more specific version (including other part of the package
name):</p>
<p>EJB archive: -ejb.jar</p>
<p>EJB client archive: -ejb-client.jar</p>
</blockquote>
| 14,525
|
<p>We have a project page which consists of users' files, multimedia stuff, etc and we want to allow the user to export all this out into a single zip file. We're using unix and mysql to store all of these currently and our primary goal is to minimize load/performance time from all the processing and compiling all the files into a zip file.</p>
<p>My idea was to cache the zip file into a temp dir and keep all the CRC checksum for each files in the zip into a separate text file. Each time the user tries to do an export I will first check through each file's CRC and compare it to the list before adding or removing files from the zip file.</p>
<p>But my other concern is also the space that the zip file will be occupying as we might have a lot of users.</p>
<p>IMHO, this is probably the dumbest way possible to do this,
so can any of you guys please suggest a better way to deal with this problem?</p>
<p>thanks
~codeNoobian</p>
|
<p>This reaks of premature optimization, just use a very light compression, aka 'fastest' and worry about the speed if it's actually a problem.</p>
|
<p>If bandwidth/download speed is not a concern, I recommend you use an uncompressed tar file. TAR is a very simple format, so it will be easy to write code to update sections of it when a few of the files have changed. Also, leaving it uncompressed will be a huge win on server CPU time.</p>
<p>Of course, leaving it uncompressed will take a lot of storage space on your server. But since it is uncompressed, it might remove the need for you to keep a cache copy of the file at all, if you can build it fast enough you can just build it on the fly as needed. Then you don't have to worry about storing CRCs and updating the TAR, either.</p>
| 37,619
|
<p>Eclipse is a really great editor, which I prefer to use, but the GUI design tools for Eclipse are lacking. On the other hand, NetBeans works really well for GUI design. </p>
<p>Are there any tips, tricks or pitfalls for using NetBeans for GUI design and Eclipse for everything else on the same project?</p>
<p><strong>EDIT:</strong> I tried Maven, and it does not seem to work (too complex for my needs).</p>
|
<p>Create your GUI with Netbeans. copy a Eclipse .project file (like below) into the project folder change the MyProjectName. Open Eclipse and import the project into your workspace, so you can open the projekt from your Eclipse workspace with Netbeans. Now you able to use Netbeans to create and change the GUI and editing the code with Eclipse.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MyProject</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
</code></pre>
|
<p>For me using linked source folders works quite well. </p>
<p>I build the GUIs in independent NetBeans projects - if they need some simple classes or interfaces, I use the "link source" (right click on project in NetBeans, choose properties), to include these in the NetBeans project.</p>
<p>My main projects are in eclipse. Here I again use the link source feature to link to the NetBeans project (right click on project in eclipse, select "build path", then "link source").</p>
<p>EDIT (Thx to Milhous :) ): in both projects in eclipse and NetBeans further all required JAR files need to be added to the build path (also the libraries added by NetBeans: eg beansbinding-1.2.1.jar, appframework-1.0.3.jar swing-worker-1.1.jar, ...)</p>
<p>Now the GUI classes can be reused in eclipse. Also leads to need to have GUI and logic classes quite decoupled, which can be nothing bad.</p>
| 21,001
|
<p>How do I return a constant from an sql statement? </p>
<p>For example how would I change the code below so "my message" would return if my (boolean expression) was true</p>
<pre><code>if (my boolean expression)
"my message"
else
select top 1 name from people;
</code></pre>
<p>I am using ms sql 2000</p>
|
<p>Did you try:</p>
<pre><code>select 'my message';
</code></pre>
|
<p>I just tried this on the AdventureWorks database and it works</p>
<pre><code>Use AdventureWorks
Declare @myVar int
SET @myVar = 1
if (@myVar = 2)
select top 2 * from HumanResources.Department
else
select top 1 * from HumanResources.Department
</code></pre>
| 39,075
|
<p>I need to set a system environment variable from a Bash script that would be available outside of the current scope. So you would normally export environment variables like this:</p>
<pre><code>export MY_VAR=/opt/my_var
</code></pre>
<p>But I need the environment variable to be available at a system level though. Is this possible?</p>
|
<p>Not really - once you're running in a subprocess you can't affect your parent.</p>
<p>There two possibilities:</p>
<ol>
<li><p><a href="https://en.wikipedia.org/wiki/Dot_(command)#Source" rel="nofollow noreferrer">Source</a> the script rather than run it (see <a href="http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins" rel="nofollow noreferrer">source .</a>):</p>
<pre class="lang-none prettyprint-override"><code>source {script}
</code></pre>
</li>
<li><p>Have the script output the export commands, and eval that:</p>
<pre class="lang-none prettyprint-override"><code>eval `bash {script}`
</code></pre>
<p><em>Or</em>:</p>
<pre class="lang-none prettyprint-override"><code>eval "$(bash script.sh)"
</code></pre>
</li>
</ol>
|
<p>You may want to use source instead of running the executable directly:</p>
<pre class="lang-bash prettyprint-override"><code># Executable : exec.sh
export var="test"
invar="inside variable"
</code></pre>
<pre class="lang-bash prettyprint-override"><code>source exec.sh
echo $var # test
echo $invar # inside variable
</code></pre>
<p>This will run the file but in same shell as the parent shell.<br>
Possible downside in some rare cases : all variables regardless of explicit export or not will be exported. If some variables are required to be unset, unset those explicitly. Similarly, handle imported variables.</p>
<pre class="lang-bash prettyprint-override"><code># Executable : exec.sh
export var="test"
invar="inside variable"
# --- #
unset invar
</code></pre>
| 39,522
|
<p>I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.</p>
<p>For example if I have the URL: <code>http://localhost/proxy.php?user name=Max</code>
the browser will convert it to <code>http://localhost/proxy.php?user%20name=Max</code>.</p>
<p>But if I give the $_GET parameters out, the key is not <code>user name</code> but <code>user_name</code> (note the underscore)!</p>
<p>Is there any possibility to change this behaviour?</p>
|
<p>From the <a href="http://www.php.net/manual/en/language.variables.external.php" rel="noreferrer">PHP manual</a>:</p>
<blockquote>
<p>Dots in incoming variable names</p>
<p>Typically, PHP does not alter the
names of variables when they are
passed into a script. However, it
should be noted that the dot (period,
full stop) is not a valid character in
a PHP variable name. For the reason,
look at it: </p>
<pre><code><?php $varname.ext; /* invalid variable name */ ?>
</code></pre>
<p>Now, what
the parser sees is a variable named
$varname, followed by the string
concatenation operator, followed by
the barestring (i.e. unquoted string
which doesn't match any known key or
reserved words) 'ext'. Obviously, this
doesn't have the intended result.</p>
<p>For this reason, it is important to
note that PHP will automatically
replace any dots in incoming variable
names with underscores.</p>
</blockquote>
<p>And a comment on the page:</p>
<blockquote>
<p>The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):</p>
<pre><code>chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)
</code></pre>
<p>PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.</p>
</blockquote>
|
<p>As far as i can remember, i've never seen spaces in URL parameter names...</p>
<p>I think, it would be better to convert all spaces of parameter names into "_".</p>
| 35,985
|
<p>What is preferable, keeping a dataset in session or filling the dataset on each postback?</p>
|
<p>That would depend on many factors. It is usually best not to keep too many items in session memory if your session is inproc or on a state server because it is less scalable. </p>
<p>If your session resides on the database, it might be better to just requery and repopulate the dataset unless the query is costly to execute.</p>
|
<p>Keep in session. Have option to repopulate if you need to, for example if the session memory is wiped.</p>
| 31,910
|
<p>I have a little utility that does a search of a number of files. I had to create it because both Google & Windows desktop searches were not finding the appropriate lines in files. The searching works fine (I am willing to improve on it) but one of the things I would like to add to my util is a batch find/replace.</p>
<p>So how would be the best way to read a line from a file, compare it to a search term and if it passes, then update the line, and continue through the rest of the file?</p>
|
<p>I would do the following for each file:</p>
<ul>
<li>Do the search as normal. Also check for the token to replace. As soon as you've seen it, start that file again. If you don't see the token to replace, you're done.</li>
<li>When you start again, create a new file and copy each line that you read from the input file, doing the replacement as you go.</li>
<li>When you've finished with the file:
<ul>
<li>Move the current file to a backup filename</li>
<li>Move the new file to the original filename</li>
<li>Delete the backup file</li>
</ul></li>
</ul>
<p>Be careful that you don't do this on binary files etc though - the consequences of doing a textual search and replace on binary files would usually be dire!</p>
|
<p>If PowerShell is an option, the function defined below can be used to perform find and replace across files. For example, to find <code>'a string'</code> in text files in the current directory, you would do:</p>
<pre><code>dir *.txt | FindReplace 'a string'
</code></pre>
<p>To replace <code>'a string'</code> with another value, just add the new value at the end:</p>
<pre><code>dir *.txt | FindReplace 'a string' 'replacement string'
</code></pre>
<p>You can also call it on a single file using <code>FindReplace -path MyFile.txt 'a string'</code>.</p>
<pre><code>function FindReplace( [string]$search, [string]$replace, [string[]]$path ) {
# Include paths from pipeline input.
$path += @($input)
# Find all matches in the specified files.
$matches = Select-String -path $path -pattern $search -simpleMatch
# If replacement value was given, perform replacements.
if( $replace ) {
# Group matches by file path.
$matches | group -property Path | % {
$content = Get-Content $_.Name
# Replace all matching lines in current file.
foreach( $match in $_.Group ) {
$index = $match.LineNumber - 1
$line = $content[$index]
$updatedLine = $line -replace $search,$replace
$content[$index] = $updatedLine
# Update match with new line value.
$match | Add-Member NoteProperty UpdatedLine $updatedLine
}
# Update file content.
Set-Content $_.Name $content
}
}
# Return matches.
$matches
}
</code></pre>
<p>Note that <code>Select-String</code> also supports regex matches, but has been constrainted to simple matches for simplicity ;) You can also perform a more robust replacement like <a href="https://stackoverflow.com/questions/342080/read-update-filestream#342099">Jon</a> suggested, rather than just overwriting the file with the new content.</p>
| 44,460
|
<p>Following on from my recent question on <a href="https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result">Large, Complex Objects as a Web Service Result</a>. I have been thinking about how I can ensure all future child classes are serializable to XML.</p>
<p>Now, obviously I could implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="noreferrer">IXmlSerializable</a> interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a <em>string</em> so I may just write my own.</p>
<p>However, to serialize to XML, I am simply decorating the class and its members with the <em>Xml???</em> attributes ( <em>XmlRoot</em> , <em>XmlElement</em> etc.) and then passing it to the <em>XmlSerializer</em> and a <em>StringWriter</em> to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.</p>
<p>The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.</p>
<p><strong>Is there any way to enforce attribute decoration? Can this be done with FxCop?</strong> (I have not used FxCop yet)</p>
<h3>UPDATE:</h3>
<p>Sorry for the delay in getting this close off guys, lots to do!</p>
<p>Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455">Fredrik Kalseth's answer</a> was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!</p>
<p>+1 to the other guys for similar suggestions :)</p>
|
<p>I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.</p>
<p>UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this:</p>
<pre><code>[TestClass]
public class When_type_inherits_MyObject
{
private readonly List<Type> _types = new List<Type>();
public When_type_inherits_MyObject()
{
// lets find all types that inherit from MyObject, directly or indirectly
foreach(Type type in typeof(MyObject).Assembly.GetTypes())
{
if(type.IsClass && typeof(MyObject).IsAssignableFrom(type))
{
_types.Add(type);
}
}
}
[TestMethod]
public void Properties_have_XmlElement_attribute
{
foreach(Type type in _types)
{
foreach(PropertyInfo property in type.GetProperties())
{
object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);
Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName);
}
}
}
}
</code></pre>
|
<p>A good FXCop rule (and one which I am finding I need right now) would be to check that all objects that are being added to the ASP.NET Session have the Serializable attribute. I'm trying to move from InProc session state to SQL Server. First time I requested a page, my site blew up on me because non-serializable objects were being stored in Session. Then came the task of hunting through all the source code looking for every instance where an object is set in the Session... FXCop would be a nice solution. Something to work on...</p>
| 3,992
|
<p>got a new blog at wordpress few days ago (<a href="http://ghads.wordpress.com" rel="noreferrer">http://ghads.wordpress.com</a>) and I want to post some code snippets now or then. Is there anyway to make it look like code without paying for extra plugins?</p>
|
<p>See here: <a href="http://en.support.wordpress.com/code/posting-source-code/" rel="noreferrer">http://en.support.wordpress.com/code/posting-source-code/</a></p>
<p>Wrap your code in these tags: [sourcecode language='css'] .. [/sourcecode]</p>
<p>(or shorter [code lang='css'] .. [/code] )</p>
<p>Note that Visual Editor doesn't interpret the tags, you need to click Preview to see how it works.</p>
<p>Available language codes:</p>
<ul>
<li>actionscript3</li>
<li>bash</li>
<li>clojure</li>
<li>coldfusion</li>
<li>cpp</li>
<li>csharp</li>
<li>css</li>
<li>delphi</li>
<li>erlang</li>
<li>fsharp</li>
<li>diff</li>
<li>groovy</li>
<li>html</li>
<li>javascript</li>
<li>java</li>
<li>javafx</li>
<li>matlab (keywords only)</li>
<li>objc</li>
<li>perl</li>
<li>php</li>
<li>text</li>
<li>powershell</li>
<li>python</li>
<li>r</li>
<li>ruby</li>
<li>scala</li>
<li>sql</li>
<li>vb</li>
<li>xml</li>
</ul>
<p>Hope that helps.</p>
|
<p>If you are hosting your own wordpress blog opposed to on WP.com you can get this functionality by installing this plugin, since it is the same plugin that the WP.com code relies on.</p>
<p><a href="http://wordpress.org/extend/plugins/google-syntax-highlighter/" rel="nofollow noreferrer">http://wordpress.org/extend/plugins/google-syntax-highlighter/</a></p>
| 10,696
|
<p>As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name.</p>
<p>Is there an equivalent to the UNIX command 'which'?</p>
<p>On UNIX, <code>which command</code> prints the full path of the given command to easily find and repair these shadowing problems.</p>
|
<p>Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the <code>where.exe</code> program which does some of what <code>which</code> does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like <code>cd</code>.) It will even accept wildcards, so <code>where nt*</code> finds all files in your <code>%PATH%</code> and current directory whose names start with <code>nt</code>.</p>
<p>Try <code>where /?</code> for help.</p>
<p>Note that Windows PowerShell defines <code>where</code> as an alias for <a href="http://technet.microsoft.com/en-us/library/hh849715.aspx" rel="noreferrer">the <code>Where-Object</code> cmdlet</a>, so if you want <code>where.exe</code>, you need to type the full name instead of omitting the <code>.exe</code> extension. Alternatively, you can set an alias for it:</p>
<pre><code>Set-Alias which where.exe
</code></pre>
<p><strong>Update:</strong> Using <code>Get-Command</code> (alias: <code>gcm</code>) is recommended since it's native to PS and will get all command types: aliases, cmdlets, executables, and functions. Example:</p>
<pre><code>gcm notepad*
</code></pre>
|
<p>Here is a function which I made to find executable similar to the Unix command 'WHICH`</p>
<p><strong>app_path_func.cmd:</strong></p>
<pre><code>@ECHO OFF
CLS
FOR /F "skip=2 tokens=1,2* USEBACKQ" %%N IN (`reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\%~1" /t REG_SZ /v "Path"`) DO (
IF /I "%%N" == "Path" (
SET wherepath=%%P%~1
GoTo Found
)
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES(x86)%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%WINDIR%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
:Found
SET %2=%wherepath%
:End
</code></pre>
<p><strong>Test:</strong></p>
<pre><code>@ECHO OFF
CLS
CALL "app_path_func.cmd" WINWORD.EXE PROGPATH
ECHO %PROGPATH%
PAUSE
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>C:\Program Files (x86)\Microsoft Office\Office15\
Press any key to continue . . .
</code></pre>
<p><a href="https://www.freesoftwareservers.com/display/FREES/Find+Executable+via+Batch+-+Microsoft+Office+Example+-+WINWORD+-+Find+Microsoft+Office+Path" rel="nofollow noreferrer">https://www.freesoftwareservers.com/display/FREES/Find+Executable+via+Batch+-+Microsoft+Office+Example+-+WINWORD+-+Find+Microsoft+Office+Path</a></p>
| 39,101
|
<p>Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization.</p>
<p>Am I remembering correctly? Can someone fill in the details?</p>
|
<p>The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers.</p>
<p>The token <code>ignore</code> for tuples, mentioned in another answer is one example, the <code>_1</code>, <code>_2</code> etc. bind placeholders are others.</p>
|
<p>If it's initialization, it would likely be an <code>iostream</code>s header (like <code>istream</code>, <code>ios</code>, etc.).</p>
| 46,624
|
<p>Is it possible to use <a href="http://subversion.apache.org/" rel="noreferrer">Apache Subversion</a> (SVN) as general purpose backup tool? (As a kind of <a href="http://en.wikipedia.org/wiki/Rsync" rel="noreferrer">rsync</a> alternative.)</p>
|
<p>I found this article to be a pretty cool description of using svn to backup your home directory, and more:</p>
<blockquote>
<p>I use Subversion to backup my Linux boxes. With some minor creativity, it easily covers:</p>
<ul>
<li>Daily snapshots and offsite backup.</li>
<li>Easy addition and removal of files and folders.</li>
<li>Detailed tracking of file versions.</li>
</ul>
<p>It also allows for a few bonus features:</p>
<ul>
<li>Regular log emails to keep track of filesystem activity via Subversion's event hooks.</li>
<li>Users may request a checkout of their home folders from any respository revision.</li>
<li>New or replacement servers can be setup with a few svn checkout commands.</li>
</ul>
</blockquote>
<p>Source: <a href="http://web.archive.org/web/20080824094836/http://www.mythago.net/svn_for_backup.html" rel="nofollow noreferrer">http://www.mythago.net/svn_for_backup.html</a></p>
<p>Also found <a href="http://www.onlamp.com/pub/a/onlamp/2005/01/06/svn_homedir.html" rel="nofollow noreferrer">this article</a> which shows an example of versioning your home directory. This allows you to bring your environment with you by checking out your home directory into a new machine. I used to do something similar and found it very useful.</p>
|
<p>I've used CVS as a substitute for ghost so I don't see why not.</p>
<p>I'ts nice as you can tag a baseline: you can change manage machines.</p>
<p>This works better on unixes than windows, obviously.</p>
| 8,720
|
<p>For the past few years whenever I learn something I tend to spend way too much time researching on the best materials for the subject than actually studying it. What should I do to get over this mentality? I am stuck. How to stop worrying about getting or using the BEST books, training videos and online materials on .net and just start learning?</p>
|
<p>Start doing a project with a deadline. You will code and learn together. If you cannot do that at work, think of a hobby project with some real requirements (like building a photo sharing site).</p>
|
<p>When you work at a new job, you learn a lot because you have great individuals who transfer a lot of knowledge they find useful. You can review how they do things, which parts are done well and which parts are done poorly.</p>
<p>Learning by isolation is hard especially when there are so many resources out there.</p>
<p>I recommend connecting with individuals in your local community user group or an online group, or start your own group. Many of these individuals will have had real-world experience and can help direct your learning path more effectively.</p>
| 24,699
|
<p>In short: I'm trying to figure out if I should tell a mail administrator of a friend's employer whether their mail configuration should be fixed, or if I should revise my own policy to be more liberal in what I accept, or neither.</p>
<p>A friend was complaining of being unable to reach anything on my mailserver. I dug into it and it seems that the hostname provided by his mail server when it connected to mine was somewhere in the *.local space, meaning it wasn't globally resolvable.</p>
<p>They were rejected with "Helo command rejected: Host not found;" by my postfix mailserver. I'm perhaps strict on my UCE checks in postfix, so I whitelisted their (in my opinion, misconfigured) server but now I'm trying to figure out to what extent they actually are misconfigured, versus whether I'm just being too harsh in what I accept.</p>
<p>So then I checked the RFCs - RFC 821 says "The HELO receiver MAY verify that the HELO parameter really corresponds to the IP address of the sender. However, the receiver MUST NOT refuse to accept a message, even if the sender's HELO command fails verification." which suggests to me that I'm actually the one violating the RFC.</p>
<p>Was this portion of RFC 821 ever replaced by a future RFC, that I can point to? Or must mail servers accept mail with bogus HELOs? Are there any well respected authorities I can point to that state the HELO hostname should be valid, as a reference for contacting their mail admin?</p>
|
<p>SMTP RFCs do not require it, but lots of popular systems will reject mail with bogus HELOs. Note that RFC 1033 and RFC 1912 both require all internet-reachable hosts to have a valid name; simply listing that name in the HELO will fix many problems. Some spam filters, unfortunately, also reject mail from hostnames containing strings that imply they are in dynamic address pools (e.g. "dynamic", "dsl", or a dash-separated IP address as is common with many ISPs).</p>
<p>One option if your friend does not have control over their reverse DNS is to use a suitable machine as smarthost for outgoing mail; e.g. their ISP's mailserver.</p>
|
<p>Eh, I disagree. It can provide total garbage within the EHLO/HELO if it wants to. As long as it says something, <em>and</em> as long as I can resolve the ip address it's coming from, I'm happy.</p>
<p>Inside the EHLO is often a short hostname, not a FQDN.</p>
| 12,263
|
<p>I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.</p>
<pre><code>if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
</code></pre>
|
<p>You need an <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Alert.html" rel="nofollow noreferrer">Alert</a>:</p>
<blockquote>
<p>An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.</p>
</blockquote>
<p>With 2 <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Command.html" rel="nofollow noreferrer">commands</a> ("Yes"/"No" in your case):</p>
<blockquote>
<p>If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.</p>
</blockquote>
<p>These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/CommandListener.html" rel="nofollow noreferrer">CommandListener</a>, and prepare your code for asynchronous execution.</p>
<p>Here is an (untested!) example class based on Alert:</p>
<pre><code>public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
</code></pre>
<p>To use it (again, untested and on top of my head):</p>
<pre><code>MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
</code></pre>
<p>This code will make the prompt the current displayed form in your app, but it <em>won't block your thread</em> like in the example you posted. You need to continue running and wait for a commandAction invocation.</p>
|
<p>I dont have programed in Java ME, but i found in it's reference for optional packages the
<a href="http://java.sun.com/javame/reference/apis/jsr209/" rel="nofollow noreferrer">Advanced Graphics and User Interface API</a>, and it's used like the Java SE API to create these dialogs with the <a href="http://java.sun.com/javame/reference/apis/jsr209/javax/swing/JOptionPane.html" rel="nofollow noreferrer">JOptionPane Class</a></p>
<blockquote>
<p><code>int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)</code></p>
</blockquote>
<p>Return could be
<code>JOptionPane.YES_OPTION</code>, <code>JOptionPane.NO_OPTION</code>, <code>JOptionPane.CANCEL_OPTION</code>...</p>
| 8,108
|
<p>What I have so far is </p>
<pre><code>#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=============================================================================="
echo "Unstaging $i for the commit due to the follow parse errors"
echo "$output"
git reset -q HEAD $i
fi
fi
done
if [ $retval -gt 0 ]; then
exit $retval
fi
}
php_syntax_check
</code></pre>
|
<p>If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.</p>
<p>One way to do this could be:</p>
<pre><code>git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
find $TMPDIR -name '*.php' -print | xargs -n 1 php -l
</code></pre>
<p>Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: <a href="https://stackoverflow.com/questions/2412450/git-pre-commit-hook-changed-added-files/3068990#3068990">Git pre-commit hook : changed/added files</a>).</p>
|
<p>If you've got the php5-cli installed you can write your pre-commit in PHP and use the syntax your more familiar with.</p>
<p>Just do something more like.</p>
<pre><code>#!/usr/bin/php
<?php /* Your pre-commit check. */ ?>
</code></pre>
| 6,499
|
<p>How can one determine, in code, how long the machine is locked?</p>
<p>Other ideas outside of C# are also welcome.</p>
<hr>
<p>I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.</p>
<p>I'll write it up anyway and see if it works. Thanks everyone!</p>
|
<p>I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:</p>
<pre><code>Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
</code></pre>
|
<p>Below is the 100% working code to find if the PC is locked or not.</p>
<p>Before using this use the namespace <code>System.Runtime.InteropServices</code>.</p>
<pre><code>[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);
[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);
public static bool IsWorkstationLocked()
{
const int DESKTOP_SWITCHDESKTOP = 256;
int hwnd = -1;
int rtn = -1;
hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);
if (hwnd != 0)
{
rtn = SwitchDesktop(hwnd);
if (rtn == 0)
{
// Locked
CloseDesktop(hwnd);
return true;
}
else
{
// Not locked
CloseDesktop(hwnd);
}
}
else
{
// Error: "Could not access the desktop..."
}
return false;
}
</code></pre>
| 6,677
|
<p>I'm running my workstation on Server 2008 and a few servers in Hyper-V VM's on that server. I connect to my corporate LAN using VPN from the main OS (the host) but my VM's aren't seeing the servers in the corporate LAN. Internet and local access to my home network work fine. Each of the VMs has one virtual network adapter. </p>
<p>What should I try to make it work?</p>
<p>Maybe I need to provide more details, please ask if needed.</p>
<p><strong>More details:</strong></p>
<ul>
<li>cannot start multiple VPN connections </li>
<li>not using NAT through the host</li>
<li>VM gets IP address from the home network router (DHCP)</li>
</ul>
|
<p>Like I said you need to setup some routes. Add a route to your Corp LAN via your Host as the gateway. Just the fact alone you telling me that it gets it from home DHCPP tells me that is the issue. Your VM's only see 1 default gateway, and that is to the internet. The VM's have no idea whatsoever that the Host has a VPN on it. Adding that route (on VM machines) causes any requests that your VM's make to the subnet of your corp network to route through your host rather than the home router.</p>
<p>Adding something like this:</p>
<pre><code>route ADD 10.0.0.0 MASK 255.0.0.0 192.168.1.30
</code></pre>
<p>on your VM'S would do this: Any requests made to the 10.<em>.</em>.* network would route through the computer with the IP address of 192.168.1.30. So replace the 10.0.0.0 and subnet with your corp lan, and the 192 ip with your hosts IP. That should take care of the issue.</p>
|
<p>Setup some routes in your routing tablke. It really depends on how its setup but if you can access your corp network fine on the host, then setup the routes in your vm machines.</p>
<p>Also, as I am not familiar with that VM, are the network adapters like VMWares bridged adapaters? If so you need to setup the route to route to your host.</p>
| 15,139
|
<p>So what is the easiest way to accomplish this?</p>
|
<p>We use <a href="http://www.statsvn.org/" rel="nofollow noreferrer">StatSVN</a> and set up a scheduled task to create nightly reports.</p>
|
<p>Path of least resistance is to download <a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">Tortoise</a>, which supports this out of the box. </p>
<p>From their features page:</p>
<blockquote>
<p>Can create a graph of
all revisions/commits. You can then
easily see where you created a
tag/branch or modified a file/folder
Graphs of commit statistics of the
project Easy comparing of two branches
or tags</p>
</blockquote>
| 28,888
|
<p>Here is what I am trying to do:
Given a date, a day of the week, and an integer <code>n</code>, determine whether the date is the <code>n</code>th day of the month.</p>
<p>For example:</p>
<ul>
<li><p>input of <code>1/1/2009,Monday,2</code>
would be false because <code>1/1/2009</code> is not the second Monday</p></li>
<li><p>input of
<code>11/13/2008,Thursday,2</code>
would return true because it is the second Thursday</p></li>
</ul>
<p>How can I improve this implementation?</p>
<pre><code>private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
int d = date.Day;
return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}
</code></pre>
|
<p>You could change the check of the week so the function would read:</p>
<pre><code>private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
</code></pre>
<p>Other than that, it looks pretty good and efficient.</p>
|
<p>In <a href="https://stackoverflow.com/questions/288513/how-do-i-determine-if-a-given-date-is-nth-weekday-of-the-month/288542#288542">this answer</a>, the following code needs to be flipped:</p>
<pre><code>// Complete the gap to the nth week
dt = dt.AddDays((nth - 1) * 7);
if(dt.Month != month)
{
// we skip to the next month, we throw an exception
throw new ArgumentOutOfRangeException(”The given month has less than ” nth.ToString() ” ”
day_of_the_week.ToString() “s”);
}
</code></pre>
| 36,729
|
<p>I have a .net client application which is connected to a remote database.
Is it safe to keep a single connection open for the lifetime of the client (hours)?</p>
<p>Does the answer hold if I have multiple (10 or 100) clients running?</p>
|
<p>Absolutely it is safe to do this. This is how client-server applications work. If you are using a three-tier application, the application server will keep a pool of connections open anyway.</p>
<p>Scalability is an issue, or at least used to be in the days that machines had less memory than modern kit. With a two-tier (client-server) application, each client opened a connection and held it open. This had several effects:</p>
<ul>
<li><p>Memory was used per-connection, so
large numbers of (relatively) idle
connections would use up machine
memory. However, a modern 64-bit
server can have tens or hundreds of
GB of memory, so it could support a
very large number of such
connections.</p></li>
<li><p>If a transaction was left
uncommitted on the client machine,
the locks would be held open for as
long as the transaction was open.
This led to a class of problems when
someone could start a transaction,
go off to lunch and forget they had
left something open. This would
lock any records referenced by the
transaction for hours at a time.</p></li>
<li><p>Transactions could, however easily
cover multiple acceses to the
database, which is harder to do with
a conneciton pool.</p></li>
</ul>
<p>A pooled architecture, which is common on 3-tier architectures has a finite number of connections between the application server and the database. Queries simply use the next available connection and updates are committed immediately. This uses less resources as you only have a finite number of connections open, and (in conjunction with an <a href="https://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking#129397">optimistic concurrency</a> strategy) will eliminate a large of potential application concurrency issues.</p>
<p>In order to use <a href="http://en.wikipedia.org/wiki/Long-running_transaction" rel="noreferrer">long transactions</a> (i.e. transactions that cover more than one call to the database) one has to de-couple the transaction from the connection. This is the basic architecture of a TP monitor and there are some standard protocols such as <a href="http://www.opengroup.org/publications/catalog/c193.htm" rel="noreferrer">XA</a> or <a href="http://msdn.microsoft.com/en-us/library/cc229116%28PROT.10%29.aspx" rel="noreferrer">OLE Transactions</a> to support this. If this type of externally managed transaction is unavailable the application has to construct a <a href="http://en.wikipedia.org/wiki/Compensating_transaction" rel="noreferrer">compensating transaction</a> that undoes the changes made by the application's transaction. This type of architecture is often used by <a href="http://en.wikipedia.org/wiki/Workflow_application" rel="noreferrer">workflow management systems.</a></p>
|
<p>Depends on the database and what you're doing with it. There is an expense to opening and closing any connection for the most part. For example, if you're using SQLCE on a mobile device (SQL Server Compact Edition) then it's actually a recommended approach to leave the connection open on the device since the expense of opening and closing it isn't worth the hassle.</p>
<p>Now in contrast, if you're working with a multi-user database you're going to want to manage those connections more carefully. As already mentioned, ADO.Net connection pooling does a pretty good job of helping you manage efficiency.</p>
| 40,303
|
<p><sup><strong>Note:</strong> This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).</sup></p>
<p>We're building a web API that's programmatically generated from a C# class. The class has method <code>GetFooBar(int a, int b)</code> and the API has a method <code>GetFooBar</code> taking query params like <code>&a=foo &b=bar</code>. </p>
<p>The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?</p>
|
<p>Surprised no one mentioned C# 4.0 optional parameters that work like this:</p>
<pre><code>public void SomeMethod(int a, int b = 0)
{
//some code
}
</code></pre>
<p><strong>Edit:</strong> I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.</p>
|
<p>You can try this too<br/>
Type 1<br/>
<code>public void YourMethod(int a=0, int b = 0)
{
//some code
}</code></p>
<p><br/>
Type 2 <br/>
<code>public void YourMethod(int? a, int? b)
{
//some code
}
</code></p>
| 24,359
|
<p>Let me first of all say that I'm NOT interested in a flame war about what is better: .NET or Java... PLEASE don't post if you want to tell me how killer .NET is or how Microsoft is the evil empire so there is no way that a developer with a soul could write .NET or whatever. We've all heard it far too much before.</p>
<p>What I'm interested is who out there in the industry can really accurately and fairly compare and contrast the details of the two platforms. I'm looking for the rare industry luminaries who are experts in both platforms and discuss the two in reasonable terms. The only dude I'm aware of in this realm is Ted Neward if that gives you an idea of what I'm looking for. Ultimately I'm interested in their opinion of how the two platforms influence each other and what new things happening on one side are working well (which might give me insight about how the other platform is likely to evolve). </p>
|
<p><a href="http://martinfowler.com/" rel="nofollow noreferrer">Martin Fowler</a> has written about both.<br>
<a href="http://www.xprogramming.com/" rel="nofollow noreferrer">Ron Jeffries</a> would be another who has written a lot about java and has more recently written a fair bit about C#</p>
|
<p>The company I work for has about half of it's development in Java (internal apps) and half in .Net (public facing apps). What is it that you want to know? there are several people in the company I work at that can contrast and compare. I admit to not knowing Java all that well though. Are you looking for specific articles, bloggers, or books?</p>
| 49,810
|
<p>I have a client-server app where the client is on a Windows Mobile 6 device, written in C++ and the server is on full Windows and written in C#. </p>
<p>Originally, I only needed it to send messages from the client to the server, with the server only ever sending back an acknowledgement that it received the message. Now, I would like to update it so that the server can actually send a message to the client to request data. As I currently have it set up so the client is only in receive mode after it sends data to the server, this doesn't allow for the server to send a request at any time. I would have to wait for client data. My first thought would be to create another thread on the client with a separate open socket, listening for server requests...just like the server already has in respect the client. Is there a way, within the same thread and using the same socket, to all the server to send requests at any time?</p>
<p>Can you use something to the effect of <code>WaitForMultipleObjects()</code> and pass it a receive buffer and an event that tells it there is data to be sent?</p>
|
<p>When I needed to write an application with a client-server model where the clients could leave and enter whenever they want, (I assume that's also the case for your application as you use mobile devices) I made sure that the clients send an <em>online</em> message to the server, indicating they were connected and ready to do whatever they needed doing.</p>
<p>at that time the server could send messages back to the client trough the same open connection.</p>
<p>Also, but I don't know if that is applicable for you, I had some sort of <em>heartbeat</em> the clients sent to the server, letting it know it was still online. That way the server knows when a client was forcibly disconnected from the network and it could mark that client back as offline.</p>
|
<p>I'm not clear on whether or not you're wanting to add the asynchronous bits to the server in C# or the client in C++.</p>
<p>If you're talking about doing this in C++, desktop Windows platforms can do socket I/O asynchronously through the API's that use overlapped I/O. For sockets, WSASend, WSARecv both allow async I/O (read the documentation on their LPOVERLAPPED parameters, which you can populate with events that get set when the I/O completes).</p>
<p>I don't know if Windows Mobile platforms support these functions, so you might have to do some additional digging.</p>
| 2,364
|
<p>I believe that quantifying the productivity increase (extra working hours) is the most effective way to do this.</p>
<p>My case in point: I have a fast machine at home and a slow one at work. My estimate is that I would gain about 30 minutes a day of extra productivity at work if I had my home machine at work. This productivity would come from less waiting to do all the tasks that I do. (An extra 30 minutes a day is about 3 weeks a year.)</p>
<p>Problem: I need to measure this.</p>
<p>Is there a software utility that can monitor and scientifically quantify time taken by tasks on a machine?</p>
|
<p>Break it down into pieces you can quantify. For example, I compile every 4 minutes and each compile would save 10 seconds. But after a while I get bored of waiting to seconds so I go to Stack Overflow and I'm there for two minutes. Sometimes I'll start talking to Jim and that takes 4 minutes for both of us. So 15 times an hour * 8 hours * 10 seconds = 12 minutes + 5 trips to stack overflow = 22 minutes + 4 conversations with Jim = 38 minutes for me and 16 for Jim. </p>
<p>The next step is to see whether it's worth it to buy a new computer. Let's round it off to an hour a day and you cost the company $100k per year in salary and benefits. One eighth of your hours are wasted so that's $12,500 per year in wasted productivity between you and Jim that could be saved by getting you a faster computer.</p>
<p>But you're not going to throw the computer out. The boss's new admin doesn't need a brand new PC, and buying her a computer would cost $1,000. Your computer costs $3,000 so it's really only costing the company $2,000.</p>
<p>It's not difficult to make it look like a no-brainer. The goal is to put it into dollars, but of course that doesn't guarantee you anything.</p>
|
<p>On *nix, I'd use <code>time</code> when doing builds and such.</p>
<p>Snagging the output of that is very simple, and easy to compare machine to machine.</p>
<p>Also - you can time certain "non-work" things, for example a build of GCC or KDE or something else fairly big from source.</p>
<p><strong>Additionally</strong> - there have been some related questions (can't find them atm) on multiple monitors: make sure you add that in, too :)</p>
| 31,241
|
<p>I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy. Pages typically present HTML content. But, some will execute programming.</p>
<p><em>Examples:</em> <br></p>
<ol>
<li>a "contact us" form </li>
<li>a report generator</li>
</ol>
<p>How should I represent/reference the programming within the database? Should I have a varchar value of a Web User Control (.ascx) name? Or a Web Form (.aspx) name? Something else? Or should it just be an integer or other such ID in a dictionary within my application?</p>
<p>Can I make an ASP.NET Site Map Provider with this structure?</p>
<p>See more information here: <a href="https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation">Which is the best database schema for my navigation?</a></p>
|
<p>You might consider inserting placeholders like <code><my:contact-us-form/></code> in the database on specific pages; that way the database can describe all the static text content instead of completely replacing that database-driven content with an <code>.ascx</code> control.</p>
|
<p>Our development team has had success with defining the name of a Web User Control in the database. Upon page load it checks too see what controls to dynamically load from the database. </p>
<p>We use Web User Controls instead of Web Forms in order to ensure we can use the control on any page.</p>
<p>You can also dynamically build a site map using ASP.Net's provider. <a href="http://www.codeproject.com/KB/aspnet/dynamicsitemap.aspx" rel="nofollow noreferrer">CodeProject</a> has a good example.</p>
| 8,087
|
<p>Nearly all programming languages used are <a href="http://en.wikipedia.org/wiki/Turing_Complete" rel="noreferrer">Turing Complete</a>, and while this affords the language to represent any <a href="http://en.wikipedia.org/wiki/Computability_theory_(computer_science)" rel="noreferrer">computable</a> algorithm, it also comes with its own set of <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">problems</a>. Seeing as all the algorithms I write are intended to halt, I would like to be able to represent them in a language that guarantees they will halt.</p>
<p><a href="http://en.wikipedia.org/wiki/Regular_Expression" rel="noreferrer">Regular expressions</a> used for matching strings and <a href="http://en.wikipedia.org/wiki/Finite_state_machine" rel="noreferrer">finite state machines</a> are used when <a href="http://en.wikipedia.org/wiki/Lexing" rel="noreferrer">lexing</a>, but I'm wondering if there's a more general, broadly language that's not Turing complete?</p>
<p><strong>edit:</strong> I should clarify, by 'general purpose' I don't necessarily want to be able to write all halting algorithms in the language (I don't think that such a language would exist) but I suspect that there are common threads in halting proofs that can be generalized to produce a language in which all algorithms are guaranteed to halt.</p>
<p>There's also another way to tackle this problem - eliminate the need for theoretically infinite memory. Once you limit the amount of memory the machine is allowed, the number of states the machine is in is finite and countable, and therefore you can determine if the algorithm will halt (by not allowing the machine to move into a state it's been in before).</p>
|
<p>Don't listen to the naysayers. There are very good reasons one might prefer a non-Turing complete language in some contexts, if you want to guarantee termination, or simplify code, for example by removing the possibility of runtime errors. Sometimes, just ignoring things may not be sufficient. </p>
<p>The paper <a href="http://www.jucs.org/jucs_10_7/total_functional_programming/jucs_10_07_0751_0768_turner.pdf" rel="noreferrer">Total Functional Programming</a> argues more or less persuasively that in fact we should almost always prefer such a restricted language because the compiler's guarantees are so much stronger. Being able to prove a program halts can be significant in and of itself, but really this is the product of the much easier reasoning that the simpler languages afford. As one component in a hierarchy of languages of varying capability, the range of utility of non-universal languages is quite broad.</p>
<p>Another system that addresses this layering concept much more fully is <a href="http://www-fp.cs.st-andrews.ac.uk/hume/index.shtml" rel="noreferrer">Hume</a>. The <a href="http://www-fp.cs.st-andrews.ac.uk/hume/report/hume-report.pdf" rel="noreferrer">Hume Report</a> gives a full description of the system and its five layers of progressively more complete, and progressively less safe, languages.</p>
<p>And finally, don't forget <a href="http://pll.cpsc.ucalgary.ca/charity1/www/home.html" rel="noreferrer">Charity</a>. It's a bit abstract, but it is also a very interesting approach to a useful but not universal programming language, which is based very directly on concepts from category theory.</p>
|
<p>Any non-Turing-complete language wouldn't be very useful as a general purpose language. You might be able to find something that bills itself as a general purpose language without being Turing-complete but I've never seen one.</p>
| 40,708
|
<p>I am working on a .NET-based server component that talks to a set of destinations (equity options exchanges, to be specific) using a variety of destination-specific protocols. The next destination we plan to add uses CORBA, so I am researching .NET libraries that can speak CORBA.</p>
<p>So far I have found three possibilities:</p>
<ul>
<li><a href="http://iiop-net.sourceforge.net/" rel="noreferrer">IIOP.NET</a> is an open-source project that seems to be mature and fairly active.</li>
<li><a href="http://j-integra.intrinsyc.com/products/espresso/" rel="noreferrer">J-Integra Espresso</a> is one of Intrinsyc's suite of Microsoft <-> Java interoperability tools.</li>
<li><a href="http://www.borland.com/us/products/visibroker/index.html" rel="noreferrer">VisiBroker for .NET</a> (previously named 'Janeva') is a module of Borland's VisiBroker CORBA package.</li>
</ul>
<p>Does anyone have any experience with any of these, good or bad?</p>
<p>Are there other options?</p>
<p>I could use one of the C++-based CORBA libraries (<a href="http://omniorb.sourceforge.net/" rel="noreferrer">omniORB</a> and <a href="http://www.theaceorb.com/" rel="noreferrer">TAO</a> seem to be the top two, but there are others) via mixed native-managed C++/CLI code, but the data needs to get to and from the managed core of the server at some point, adding a performance cost for marshalling, and using native C++ libraries in a mixed-code scenario tends to be fairly painful.</p>
<p>Update - we have started to use IIOP.NET, and it is looking pretty good so far. Performance for the most recent version (1.9 sp1) seems acceptable, and the API is reasonably easy to use. I will definitely look at <a href="http://www.ikvm.net/" rel="noreferrer">IKVM</a> as suggested by Todd Stout - that looks like a very interesting possibility if IIOP.NET doesn't pan out.</p>
<p>Update #2 (July 2010) - we have been using IIOP.NET in production for a while, with good results. The IIOP.NET project isn't exactly what I would call active, but then again neither is CORBA, so there doesn't seem to be a big need for a lot more development.</p>
|
<p>IIOP.NET is a good opensource project unfortenely the project stoped in 2007.
The project doesn´t have much documentation, but it works.</p>
<p>I´m using valuetype in CORBA and IIOP.NET works well.</p>
|
<p>IONA ORBIX is the only one I have experience with.</p>
<p>It works as well as any CORBA broker could be expected too, but, its expensive.</p>
| 44,312
|
<p>When using the following function (compare 2 user's group membership), I get results that do not make sense.</p>
<pre><code>function Compare-ADUserGroups <br>
{ #requires -pssnapin Quest.ActiveRoles.ADManagement
param (
[string] $FirstUser = $(Throw "logonname required."),
[string] $SecondUser = $(Throw "logonname required.")
)
$a = (Get-QADUser $FirstUser).MemberOf
$b = (Get-QADUser $SecondUser).MemberOf
$c = Compare-Object -referenceObject $a -differenceObject $b
$c | Sort-Object InputObject
}
</code></pre>
<p>When I call this (Compare-ADUserGroups User1 User2), I get a result set similar to the following:</p>
<ul>
<li>CN=[All Users],OU=adm,DC=OSUMC,DC=EDU <=</li>
<li>CN=[All Users],OU=adm,DC=OSUMC,DC=EDU =></li>
<li>CN=Extended Users,OU=MSG,DC=OSUMC,DC=EDU <=</li>
<li>CN=Extended Users,OU=MSG,DC=OSUMC,DC=EDU =></li>
<li>CN=LCS2005,OU=Distribution Lists,DC=OSUMC,DC=EDU <=</li>
<li>CN=LCS2005,OU=Distribution Lists,DC=OSUMC,DC=EDU =></li>
</ul>
<p>I would expect these to not show given that they are equal and I am not using the -IncludeEqual parameter. Any ideas on why these are showing up?</p>
|
<p>There's <em>something</em> in them which is throwing off the comparison. You'll see something similar if you run...</p>
<p>get-process | export-clixml c\procs.xml
Diff (get-process) (import-clixml c:\procs.xml)</p>
<p>Because SOME properties of those objects - things like VM and PM, for example, change in the brief interval between the two Get-Process runs. So it's possible that you're running into something similar, where some properties between the two objects are differing. By default, Compare-Object looks at <em>every</em> property.</p>
<p>An alternative is to use the -property param of Compare-Object to just compare specific properties, rather than comparing the <em>entire</em> object. Compare-Object can definitely be a bit tricky in this regard, because of the way it works with object properties rather than simply working with text.</p>
|
<p>My best guess is that the MemberOf property provided by <code>Get-QADUser</code> is probably returning an object instead of just the distinguished name of the group as a string. Here is the script that I use for comparing Active Directory Group memberships:</p>
<pre><code># Compare the group memberships of 2 Active Directory Users or the user memberships of 2 Active Directory Groups.
# Requires the ActiveDirectory PowerShell module from the Microsoft's Remote Server Administration Tools.
Import-Module ActiveDirectory
function Get-ComparisonResult ($name1, $name2, $sideIndicator)
{
$comparisonResult = $null
switch ($_.SideIndicator)
{
'<=' { $comparisonResult = "$($name1) Only" }
'==' { $comparisonResult = "$($name1) and $($name2)" }
'=>' { $comparisonResult = "$($name2) Only" }
}
return $comparisonResult
}
function Compare-ADUserGroupMembership($userName1, $userName2)
{
$userComparisonResultColumn = @{ name = 'Comparison Result'; expression = { Get-ComparisonResult $user1.DisplayName $user2.DisplayName $_.SideIndicator } }
$groupNameColumn = @{ name = 'Group Name'; expression = { (Get-ADGroup $_.InputObject).Name } }
$user1 = Get-ADUser $userName1 -Properties memberOf, displayName
$user2 = Get-ADUser $userName2 -Properties memberOf, displayName
$userGroupComparison = Compare-Object -IncludeEqual $user1.MemberOf $user2.MemberOf | Select $userComparisonResultColumn, $groupNameColumn
return $userGroupComparison
}
function Compare-ADGroupMembership($groupName1, $groupName2)
{
$groupComparisonResultColumn = @{ name = 'Comparison Result'; expression = { Get-ComparisonResult $groupName1 $groupName2 $_.SideIndicator } }
$userNameColumn = @{ name = 'User Name'; expression = { $_.InputObject.name } }
$groupMembers1 = Get-ADGroupMember $groupName1
$groupMembers2 = Get-ADGroupMember $groupName2
$groupMemberComparison = Compare-Object -IncludeEqual $groupMembers1 $groupMembers2 | Select $groupComparisonResultColumn, $userNameColumn
return $groupMemberComparison
}
Compare-ADUserGroupMembership 'userone' 'usertwo' | ft -AutoSize
Compare-ADGroupMembership 'Group One' 'Group Two' | ft -AutoSize
</code></pre>
| 45,515
|
<p>I would like to use an ajax toolkit/framework like ZK (www.zkoss.org) or GWT. But I don't know whether it's possible to bundle resources in a JAR? Do you know which one support such resource loading?</p>
|
<p>Not sure what your goal is, but if its to bundle a web application into one file, then you can do that with a WAR file - assuming your deploying onto a java webcontainer like tomcat or jboss.</p>
|
<p>My goal is to summarize the Java-classes and also their Templates-files for the view of various application modules, each in one Java-Jar-File. These modules I use in another application, which of course I summarize in a WAR-File for Deployment. I would like to know which ajax-Framework/Toolkit does support this.</p>
| 25,573
|
<p>I've got HTML code that roughly looks like this:</p>
<pre><code><li id="someid-11">
<img src="..." alt="alt" />
<h2><a href="somelink"> sometext </a>
<span><a class="editcontent" href="?action=editme">Edit</a></span>
</h2>
<div id="11" class="content">
<!-- // content goes here -->
<div class="bottom_of_entry"> </div>
</li>
</code></pre>
<p>I'm using the a.editcontent to activate an edit-in-place method on div.content.
My current selector looks like this</p>
<pre><code>jQuery('a.editcontent').bind('click', (function(){
jQuery(this).parent('span').parent('h2').next('.content').trigger('edit');
}
</code></pre>
<p>It works, but its ugly. There must be some better way to do that, right?</p>
|
<p>I recommended the Sprintstar Solution. but if you don't like it, use this:</p>
<pre><code>$("a.editcontent").click(function(){
$(this).parents("h2").next(".content").trigger("edit");
});
</code></pre>
<p>If you have more that one "h2":</p>
<pre><code>$("a.editcontent").click(function(){
$(this).parents("h2:first").next(".content").trigger("edit");
});
</code></pre>
|
<p>I think its hard to read because you're having to go up from one element back down to another. If you reference both from a common container, those paths will seem more meaningful.</p>
<pre><code>var listitem11 = $("#someid-11");
listitem11.find('a.editcontent').bind('click'), (function(){
listitem11.find('.content').trigger('edit');
}
</code></pre>
<p>Now I suspect you have multiple list items to deal with, and in that case you'll need an enclosing loop where you didn't need one before. Still I think that puts you ahead.</p>
| 48,921
|
<p>I would like to experiment with ideas about distributed file synchronization/replication. To make it efficient when the user is working, I would like to implement some kind of daemon to monitor changes in some directory (e.g. /home/user/dirToBeMonitored or c:\docs and setts\user\dirToBeMonitored). So, I could be able to know which filename was added/changed/deleted at every time (or within a reasonable interval).</p>
<p>Is this possible with any high-medium level language?. Do you know some API (and in which language?) to do this?</p>
<p>Thanks.</p>
|
<p><em>A bonified answer, albeit one that requires a largish library dependency (well-worth it IMO)!</em></p>
<p>QT provides the <a href="http://doc.trolltech.com/4.4/qfilesystemwatcher.html" rel="nofollow noreferrer">QFileSystemwatcher</a> class, which uses the native mechanism of the underlying platform. </p>
<p>Even better, you can use the QT language bindings for Python or Ruby. <a href="http://www.rkblog.rk.edu.pl/w/p/pyqt4-text-editor-final-changes/" rel="nofollow noreferrer">Here</a> is a simple PyQT4 application which uses <a href="http://doc.trolltech.com/4.4/qfilesystemwatcher.html" rel="nofollow noreferrer">QFileSystemWatcher</a>. </p>
<p><strong>Notes</strong></p>
<ul>
<li>A good reference on on <a href="http://aralbalkan.com/1675" rel="nofollow noreferrer">creating deployable PyQT4 apps</a>, especially on OSX but should work for Windows also.</li>
<li>Same solution previously posted <a href="https://stackoverflow.com/questions/61253/how-to-be-notified-of-file-directory-change-in-c-c-ideally-using-posix/61300#61300">here</a>. </li>
<li>Other cross-platform toolkits may also do the trick (for example <a href="http://www.gnome.org/" rel="nofollow noreferrer">Gnome</a>'s <a href="http://library.gnome.org/devel/gio/unstable/" rel="nofollow noreferrer">GIO</a> has <a href="http://library.gnome.org/devel/gio/unstable/GFileMonitor.html" rel="nofollow noreferrer">GFileMonitor</a>, although it is UNIX only and doesn't support OSX's <a href="http://en.wikipedia.org/wiki/FSEvents" rel="nofollow noreferrer">FSEvents</a> mechanism afaik).</li>
</ul>
|
<p>In Linux it is called <a href="http://linux.die.net/man/7/inotify" rel="nofollow noreferrer">inotify</a>.</p>
| 18,807
|
<p>Does python have the ability to create dynamic keywords?</p>
<p>For example:</p>
<pre><code>qset.filter(min_price__usd__range=(min_price, max_price))
</code></pre>
<p>I want to be able to change the <strong>usd</strong> part based on a selected currency.</p>
|
<p>Yes, It does. Use <code>**kwargs</code> in a function definition.</p>
<p>Example:</p>
<pre><code>def f(**kwargs):
print kwargs.keys()
f(a=2, b="b") # -> ['a', 'b']
f(**{'d'+'e': 1}) # -> ['de']
</code></pre>
<p>But why do you need that?</p>
|
<p>Yes, sort of.
In your filter method you can declare a wildcard variable that collects all the unknown <a href="http://www.python.org/doc/2.5.2/tut/node6.html#SECTION006720000000000000000" rel="nofollow noreferrer">keyword arguments</a>. Your method might look like this:</p>
<pre><code>def filter(self, **kwargs):
for key,value in kwargs:
if key.startswith('min_price__') and key.endswith('__range'):
currency = key.replace('min_price__', '').replace('__range','')
rate = self.current_conversion_rates[currency]
self.setCurrencyRange(value[0]*rate, value[1]*rate)
</code></pre>
| 43,819
|
<p>HI,</p>
<p>I have a large table from which i can query to get the following table</p>
<pre><code>type no of times type occurs
101 450
102 562
103 245
</code></pre>
<p>also i can get another table</p>
<pre><code>code no of times code occurs
0 1222
1 750
2 355
</code></pre>
<p>but now i want to write a query which could get me the following table</p>
<pre><code>type no of timescode1occurs %of timescode1 occurs out of %of times code1 occurs out of
no of times type occurs no of times code occcurs
101 50 11% 6%
102 75 13% 10%
</code></pre>
<p>How can i write a query to get this?</p>
<p>Thanks</p>
|
<p>I think you want this:</p>
<pre><code>req.Credentials = CredentialCache.DefaultCredentials;
</code></pre>
|
<p>You're going to need to enable Integrated Windows Authentication.</p>
<p>I don't know what happens in ASP.NET MVC, but in ASP.NET Web Forms impersonation is turned on by:</p>
<pre><code><identity impersonate="true">
</code></pre>
<p>in web.config.</p>
| 46,338
|
<p>What is your single favorite mocking library for Python?</p>
|
<p>I've only used one, but I've had good results with Michael Foord's Mock: <a href="http://www.voidspace.org.uk/python/mock/" rel="noreferrer">http://www.voidspace.org.uk/python/mock/</a>.</p>
<p>Michael's introduction says it better than I could:</p>
<blockquote>
<p>There are already several Python mocking libraries available, so why another one?</p>
<p>Most mocking libraries follow the 'record -> replay' pattern of mocking. I prefer the 'action -> assertion' pattern, which is more readable and intuitive particularly when working with the Python unittest module.</p>
<p>...</p>
<p>It also provides utility functions / objects to assist with testing, particularly monkey patching.</p>
</blockquote>
|
<p>I've used <a href="http://pmock.sourceforge.net/" rel="nofollow noreferrer">pMock</a> in the past, and didn't mind it, it had pretty decent docs too. However, Foord's Mock as mentioned above is also nice.</p>
| 12,354
|
<p>I'm working on an application that is implemented as an HTA. I have a series of links that I would like to have open in the system's default web browser. Using <code><a href="url" target="_blank"></code> opens the link in IE regardless of the default browser.</p>
<p>Is there a way to use the default browser? Using JavaScript is an option.</p>
|
<p>Create a shell and attempt to run a URL.</p>
<p>This works for me (save as whatever.hta and execute it) on my system. Clicking on the button opens Google in Firefox:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>HTA Test</title>
<hta:application applicationname="HTA Test" scroll="yes" singleinstance="yes">
<script type="text/javascript">
function openURL()
{
var shell = new ActiveXObject("WScript.Shell");
shell.run("http://www.google.com");
}
</script>
</head>
<body>
<input type="button" onclick="openURL()" value="Open Google">
</body>
</html>
</code></pre>
|
<p>Nope, sadly I believe this is a browser specific implementation that will open new links with target="_blank" within the same browser.</p>
<p>If you wanted to open it in the default browser, then you would need to interact with the OS, which JavaScript cannot do.</p>
| 22,421
|
<p>Here is a little test program: </p>
<pre><code>#include <iostream>
class Test
{
public:
static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};
int main()
{
Test k;
k.DoCrash(); // calling a static method like a member method...
std::system("pause");
return 0;
}
</code></pre>
<p>On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".</p>
<p>As far as I know, static member methods shouldn't be called on instanced object.</p>
<ol>
<li>Am I wrong? Is this code correct from the standard point of view?</li>
<li>If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?</li>
</ol>
|
<p>The standard states that it is not necessary to call the method through an instance, that does not mean that you cannot do it. There is even an example where it is used:</p>
<p>C++03, 9.4 static members</p>
<blockquote>
<p>A static member s of class X may be referred to using the
qualified-id expression X::s; it is
not necessary to use the class member access syntax (5.2.5) to refer
to a static member. A static member
may
be referred to using the class member access syntax, in which
case the object-expression is
evaluated.</p>
</blockquote>
<pre><code>class process {
public:
static void reschedule();
};
process& g();
void f()
{
process::reschedule(); // OK: no object necessary
g().reschedule(); // g() is called
}
</code></pre>
|
<p>static methods can be called also using an object of the class, just like it can be done in Java. Nevertheless, you shouldn't do this. Use the scope operator like <code>Test::DoCrash();</code> Maybe you think of namespaces:</p>
<pre><code>namespace Test {
void DoCrash() {
std::cout << "Crashed!!" << std::endl;
}
};
</code></pre>
<p>which can only be called by <code>Test::DoCrash();</code> from outside that namespace if the function is not imported explicitly using a <code>using directive/declaration</code> into the scope of the caller.</p>
| 42,163
|
<p>I am looking for either a FireFox extension, or a similar program, that allows you to craft GET and POST requests. The user would put in a form action, and as many form key/value pairs as desired. It would also send any cookie information (or send the current cookies from any domain the user chooses.) The Web Developer add-on is almost what I'm looking for; It let's you quickly see the form keys, but it doesn't let you change them or add new ones (which leads to a lot of painful JavaScript in the address bar...)</p>
|
<p>If you're a windows user, use <a href="http://www.fiddler2.com/fiddler2/version.asp" rel="nofollow noreferrer">Fiddler</a>. It is invaluable for looking at the raw Http requests and responses. It also has the ability to create requests with the request builder and it has an auto responder also, so you can intercept requests. It even lets you inspect HTTPS traffic and it has a built in event scripting engine, where you can create your own rules.</p>
|
<p>If you've got Greasemonkey installed you might want to try the XSS Assistant user script: <a href="http://www.whiteacid.org/greasemonkey/#xss_assistant" rel="nofollow noreferrer">http://www.whiteacid.org/greasemonkey/#xss_assistant</a></p>
| 3,655
|
<p>I'm currently using AntLR to parse some files with a proprietary language.
I have a need of highlighting sections of it on an editor (think of highlighting a method in a Java class, for instance).</p>
<p>Does anyone has a hint on how to get them?
Say I have this code:</p>
<pre><code>function test(param1, param2) {
}
</code></pre>
<p>as function is a keyword, the first position I get in the parser is the one of the identifier "test". How can I get the positions from there up to the ending curly brace? The parameters list is dynamic, as one would expect, so you don't know in advance its length.</p>
<p>Thank you!</p>
|
<p>If I understand your question, I think you can use attribute 'pos' on each token</p>
<pre><code>func: FUNCTION ID '(' ID (',' ID)* ')' {
System.out.println("Position = " + $FUNCTION.pos);
}
</code></pre>
<p>which refers to the character position within the line counting from zero.</p>
|
<p>Not quite following why the first position you are getting is the position of test. You should easily be able to get the character offset of the "function" token if you designed the pattern specification correctly. Can you list the relevant parts of the specification?</p>
| 35,632
|
<p>The type 'x' is defined in an assembly that is not referenced. You must add a reference to assembly 'abc123'.</p>
<p>I have a .NET 2.0 web application that references my assembly 'abc123'. The assembly exists in the GAC and I've verified that it is the correct(same) version. The rest of application has no issues except for one .aspx page. The page in question has a repeater that displays a user control as one of its "fields". Upon binding a list of type y to the repeater I pass the user control a list of type x (a property of y) as shown here:</p>
<pre><code><uc1:usercontrol id="ucusercontrol " runat="server" myPublicUserControlProperty='<%#Eval("CollectionOfX") %>'/>
</code></pre>
<p>On the user control's property set, I bind the list of type x to a gridview in the user control.</p>
<p>One strange thing to note is that this report works fine on my development pc but not on any servers once I deploy. My pc is Windows XP, IIS6, VS2005. The servers are Windows Server 2003, IIS6.</p>
<p>I hope I explained that well enough. Thanks in advance for any insight you can provide.</p>
|
<p>I'm Mike's coworker, and we worked out a solution.</p>
<p>The type X is defined in his assembly, that is only in the GAC. Even though his ASP.NET web appplication did have a reference, it was failing to load from the GAC only for this UserControl. The rest of the application worked as expected. We confirmed the failed loading by placing a copy of the assembly in the bin directory, and everything worked. We removed the assembly, and the problem came back. </p>
<p>Our solution was to manually add an entry to the web.config in the assemblies section to point ASP.NET to the GAC. </p>
<p>It looks like any time you reference a type in the page (not the code-behind), you need the assembly information defined in the web.config file or in a page directive.</p>
<pre><code><assemblies>
<add assembly="MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[MyPublicKeyToken]"/>
</assemblies>
</code></pre>
|
<p>I had the exact same error, but I had a <strong>public</strong> constructor in my class that used as a parameter, an object from another project.</p>
<p>I resolved the problem by making that constructor internal.</p>
| 36,088
|
<p>Everytime i retrieve data from a mysql stored procedure with a concat function an error will occur after binding the datagridview to the datatable that holds the returned rows.</p>
|
<p>I suppose you should make an alias for selected value:</p>
<pre><code>select concat(column1, column2) as concatenated from table1
</code></pre>
|
<p>I suppose you should make an alias for selected value:</p>
<pre><code>select concat(column1, column2) as concatenated from table1
</code></pre>
| 48,211
|
<p>Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that?</p>
<p>I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements?</p>
|
<p>In MySQL there's no best way than to poll (you create a specific table to simplify the polling though), in other databases you can have triggers that have impact outside the database. In MySQL <a href="http://dev.mysql.com/doc/refman/5.0/en/triggers.html" rel="noreferrer">triggers</a> can only do stuff inside the database itself (for instance, populating the helper table).</p>
|
<p>For those who are doing this in go. You can enable binlog and read binlog for new insert/update/delete on any table. There is a go package <a href="https://github.com/siddontang/go-mysql" rel="nofollow noreferrer">here</a> that does the trick. And <a href="https://github.com/JackShadow/go-binlog-example" rel="nofollow noreferrer">here</a> is a sample implementation.</p>
| 20,200
|
<p>I am looking at connecting to a openSuse 11.1 Beta 3 virtual machine from my Vista 64-bit development workstation. I found UltraVNC Viewer to be the only option for this purpose. Is there any other clients that I can use to connect from Vista to openSuse/other Linux installs? </p>
<p>Note: Bandwidth is not a worry, the connection will be using a Gigabit network.</p>
|
<p>I don't know about Vista but I have successfully used <a href="http://sourceforge.net/projects/xming" rel="nofollow noreferrer">X-Ming</a> on Windows XP to talk to a Debian box.</p>
|
<p>I will double Adam's suggestion to use XMing. You can also enable X11-Forwarding in SSH and use, say, PuTTy, to open up different X applications running on the SUSE box (this, if I remember correctly, requires some sort of a X server to be running on the Windows box, and for which, I have been using <a href="http://www.straightrunning.com/XmingNotes/" rel="nofollow noreferrer">Xming</a>.</p>
<p>That aside, I've used <a href="http://www.tightvnc.com/" rel="nofollow noreferrer">tightVNC</a> before to export X displays on Linux boxes over to Windows.</p>
| 30,996
|
<p><strong>This question isn't about unit-testing. And it is for a desktop product.</strong></p>
<p>This is about testing of the gui and testing that the right stuff is input in the right text box at the right time.</p>
<p>A company I used to work at used WinRunner (different department so I don't know much more that that), but that has now been shutdown by HP but they don't seem that bothered whether you stay with HP or go elsewhere. You can't read about the product until you've signed up which is annoying.</p>
<p>The tool has to work with MFC (non-negotiable) and the ideal tool will also...</p>
<ul>
<li>be automated.</li>
<li>be scriptable.</li>
<li>work with different screen resolutions automatically.</li>
<li>be able to 'spy' on individual static text boxes, etc.</li>
<li>intuitive enough so non-programmers can create the scripts.</li>
<li>have reporting tools, including email of individual users.</li>
</ul>
<p>What do other SO users do for automated GUI testing?</p>
|
<p>We use the <a href="http://safsdev.sourceforge.net/Default.htm" rel="noreferrer">SAFS framework</a> for Rational Robot (RRAFS). There are also SAFS implementations for WinRunner (WRAFS) and it looks like they have a new "Image-Based Testing" implementation, which I'm not familiar with.</p>
<p>This framework does a nice job of seperating the UI implementation from the test scripts. I've tested four releases of a web application developed by two different teams (one team using classic ASP, one using ASP.NET) and I only had to change the application map of my UI objects, the tests themselves didn't need to change.</p>
<p>That said, the language of the framework is cumbersome and takes getting used to. It's not very robust, in terms of language constructs, but with some effort you can do anything you need to. It's sort of like "programming" in Windows Batch language, but for tests ;)</p>
<p>To address your individual requirements above:</p>
<p>1) <strong>The tool has to work with MFC (non-negotiable).</strong>
The SAFS framework uses a 3rd party "record-playback" tool to drive the tests, like Rational Robot or Mercury WinRunner. If that tool can interact with MFC apps, then the framework can. I don't know how the "Image-Based Testing" implementation drives the tests, but I'd guess it can also work with MFC.</p>
<p>2) <strong>be automated.</strong>
The SAFS framework integrates with the <a href="http://staf.sourceforge.net/" rel="noreferrer">STAF framework</a>, which will allow you to automate the execution of your tests. I have a proof-of-concept test that uses STAF to start a VM image from a pool of images, install the application under test, run the RRAFS test, and put the results on a web server for others to get at.</p>
<p>3) <strong>be scriptable.</strong>
Yes, but as mentioned, it's not the most robust programming language. I wrote an Excel add-in that our testers use to write their tests that simplifies things a little bit.</p>
<p>4) <strong>work with different screen resolutions automatically.</strong>
Yes, since it's looking "under the covers" at the UI objects and not the screen. Except for maybe the "Image-based Testing" option...</p>
<p>5) <strong>be able to 'spy' on individual static text boxes, etc.</strong>
Yes, you can wait for a UI object to appear, disapper, to have a value, for a value to be changed, etc.</p>
<p>6) <strong>intuitive enough so non-programmers can create the scripts.</strong>
With some training. We've had limited success. Some QA folks can write the tests, some struggle.</p>
<p>7) <strong>have reporting tools, including email of individual users.</strong>
Yes, using the STAF framework you can post results to a web server, send out emails, etc.</p>
|
<p>There are a lot more (open source) alternatives if you are testing a web product. For a desktop product, some popular general purpose desktop GUI automation tools below (in no particular order). I've worked with all of these personally, and they all get the job done. If you choose to go with a vendor tool, get POCs for the ones you are considering, and make the decision based on what tool is the best fit for the company in general. One tool may be a better fit for a particular application, but there may be other projects/applications to consider.</p>
<ul>
<li>QuickTest Pro (HP's successor to WinRunner)</li>
<li>Rational Functional Tester (IBM's successor to Robot)</li>
<li>TestPartner</li>
</ul>
| 27,984
|
<p>I'm pretty new to the C++ build flow, and I'm thinking of switching to use partial linking for my libraries instead of creating <code>ar</code> archives. I'm hoping to reduce link time in an inevitable final compilation step that I have, and I figure partial linking some libraries once could save me time over linking everything in that final step.</p>
<p>Is what I'm describing possible? I figure it should be something along the lines <code>ld -Ur -o mylib.o [components]</code>. Are there important build considerations that I'm not taking into account?</p>
|
<p>You lose an important effect of having the object files in an <code>ar</code> archive, which is that only the referenced objects will be linked in.</p>
<p>If you have both <code>foo.o</code> with the symbol <code>foo</code> and bar.o with the symbol <code>bar</code> in an <code>ar</code> archive, and only reference the <code>foo</code> symbol, only <code>foo.o</code> would be linked in. If you instead do a partial link, the contents of both will end up in the executable, even if <code>bar</code> is never referenced anywhere.</p>
<p>You could also try a faster linker, like <a href="http://lwn.net/Articles/274859/" rel="noreferrer">gold</a>.</p>
|
<p>The other time that you want to use ld -r to do a partial link is if you have some object files that contain static initialisation that are required to provide certain functionality but that is never called directly by any of the code.</p>
<p>If you'd like I can write up a document that showcases how this works and why it works!</p>
<p>(see run time C++ class registration for example, it uses a static register function that registers itself in a registry, which can then be used to create and return a Base* with polymorphic behaviour since it created a new object that was inherited from Base. See <a href="https://stackoverflow.com/questions/77817/c-runtime-knowledge-of-classes/77911#77911">C++ runtime knowledge of classes</a> which is an answer to a question I asked.)</p>
| 34,071
|
<p>What is a strong way to protect against sql injection for a classic asp app?</p>
<p>FYI I am using it with an access DB. (I didnt write the app)</p>
|
<p>Stored Procedures and/or prepared statements:</p>
<p><a href="https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks">https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks</a></p>
<p><a href="https://stackoverflow.com/questions/139199/can-i-protect-against-sql-injection-by-escaping-single-quote-and-surrounding-us">Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?</a></p>
<p><a href="https://stackoverflow.com/questions/1284/catching-sql-injection-and-other-malicious-web-requests">Catching SQL Injection and other Malicious Web Requests</a></p>
<p>With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.</p>
<p>Here's a link to the technique in Access:</p>
<p><a href="http://www.asp101.com/samples/storedqueries.asp" rel="nofollow noreferrer">http://www.asp101.com/samples/storedqueries.asp</a></p>
<p>Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.</p>
<p>In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:</p>
<pre><code>Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ;
</code></pre>
<p>Remember that your database needs to defend its own perimeter, and if various logins have rights to <code>INSERT/UPDATE/DELETE</code> in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)</p>
|
<p>Switching to SQL Express at the very least is a great option. It will make things much more secure. Even though using parameters and Stored Procedures can help greatly. I also recommend that you validate the inputs carefully to be sure they match what you're expecting.</p>
<p>For values like numbers it is fairly easy to extract the number to verify that it is indeed just a number. Escape all special characters for SQL. Doing this will prevent the attempted attack from working. </p>
| 18,056
|
<p>I'm looking for embedded database engine supporting <a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="nofollow noreferrer">isolating storage</a>. Currently I'm aware of VistaDB. What else you can recommend?</p>
<p>Requirements are pretty simple:</p>
<ul>
<li>xcopy deployment </li>
<li>support for isolated storage</li>
<li>preferably free</li>
</ul>
<p>Note that you don't know exact path to the file when using IS.</p>
|
<p><a href="http://www.vistadb.net" rel="nofollow noreferrer">VistaDB</a> seems to have <a href="http://www.vistadb.net/vistadb3/technical/zero-config.aspx" rel="nofollow noreferrer">support</a> for isolated storage. I've been using it for nearly a year now and am very happy with it all round.</p>
<p>It's not free but its pricing starts at <a href="https://accounts.vistadb.net/pricelist.aspx" rel="nofollow noreferrer">$60USD</a> for version 4 (very soon to be released). There is a free <a href="http://www.vistadb.net/vistadb3/vistadb-expresslimits.aspx" rel="nofollow noreferrer">Express Edition</a> but this is for non-commercial projects only. </p>
|
<p>You could do something like that with <a href="http://firebirdsql.org" rel="nofollow noreferrer">Firebird Embedded</a>.<br>
Although it does not natively support Isolated Storage, it should be pretty easy to create a new database for each user. </p>
| 13,376
|
<p>How can I add new application mapping in IIS using vbscript?</p>
<p>Thanks,</p>
|
<p>Basically you <em>could</em> use <code>adsutil.vbs</code> to manipulate the ScriptMaps within the MetaBase.</p>
<p>Unfortunately, <code>adsutil.vbs</code> is unable to set single items in LIST properties like ScriptMaps. You can only set or delete the list as a whole. Any additional processing would require your own coding.</p>
<p>A person named David Wang has made a VB script that has this capability. He explained in more detail in <a href="http://blogs.msdn.com/david.wang/archive/2004/12/02/273681.aspx" rel="nofollow noreferrer">his blog entry on the topic</a>. The script he made can be copied from there. You can modify other LIST properties with it as well.</p>
|
<p>Use a combination of ADSI with VBScript. There are several examples here: <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/library/IIS/4b976f46-3751-4f6b-ab68-5e19fa73a7b1.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/library/IIS/4b976f46-3751-4f6b-ab68-5e19fa73a7b1.mspx</a></p>
| 33,300
|
<p>This error should be a simple one but I cant seem to make it work. The problem lies in the fact that this very same code works earlier in the program. I don's see any reason for it to be sending an error on this instance and not the four previous ones. Reference the code below, and feel free to provide any criticism you may have as it should make me better. If it matters, I am using Sharp Develop 2.2.</p>
<p>Here is an example of the code that works:</p>
<pre><code>void calc2Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(tb2_fla.Text) & String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_fla.Text) & String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_e.Text))
{
MessageBox.Show("Enter either kVA and Voltage or FLA and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);
}
if (!String.IsNullOrEmpty(tb2_kva.Text) & !String.IsNullOrEmpty(tb2_e.Text))
{
decimal x, y, z;
x = decimal.Parse(tb2_kva.Text);
y = decimal.Parse(tb2_e.Text);
z = (x * 1000) / (1.732050808m * y); //the m at the end of the decimal allows for the multiplication of decimals
tb2_fla.Text = z.ToString();
tb2_fla.Text = Math.Round(z,2).ToString();
}
else
{
if (!String.IsNullOrEmpty(tb2_fla.Text) & !String.IsNullOrEmpty(tb2_e.Text))
{
decimal x, y, z;
x = decimal.Parse(tb2_fla.Text);
y = decimal.Parse(tb2_e.Text);
z = (x * y * 1.732050808m) / 1000; //the m at the end of the decimal allows for the multiplication of decimals
tb2_kva.Text = Math.Round(z,2).ToString();
}
</code></pre>
<p>Here is the example of the code that sends the error in the subject line of this post:</p>
<pre><code>void Calc4Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(tb4_fla.Text) && String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_kw.Text) & String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_e.Text))
{ //If values are entered improperly, the following message box will appear
MessageBox.Show("Enter either FLA and Voltage or kW and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);
}
if (!String.IsNullOrEmpty(tb4_fla.Text)&& !String.IsNullOrEmpty(tb4_e.Text)&& String.IsNullOrEmpty(tb4_kw.Text))
{//If the user eneters FLA and Voltage calculate for kW
decimal x, y, z;
x = decimal.Parse(tb4_fla.Text);
y = decimal.Parse(tb4_e.Text);
z = (x*y)*(.8 * 1.732050808m);
tb4_kw.Text = Math.Round(z,0).ToString();
}
if (!String.IsNullOrEmpty(tb4_kw.Text) && !String.IsNullOrEmpty(tb4_e.Text) && String.IsNullOrEmpty(tb4_fla.Text))
{;//If the user enters kW and Voltage calculate for FLA
decimal x, y, z;
x = decimal.Parse(tb4_kw.Text);
y = decimal.Parse(tb4_e.Text);
z = (1000 * x)/(y * 1.732050808m)* .8;
tb4_fla.Text = Math.Round(z,0).ToString();
}
}
</code></pre>
<p>I appreciate any help that I can get.
Thank you.</p>
|
<pre><code>.8m instead of .8
</code></pre>
|
<p>In this line here:</p>
<p>z = (x<em>y)</em>(.8 * 1.732050808m);</p>
<p>you specify .8 as a literal, but without the 'm' suffix, the literal specifies a double.</p>
<p>z = (x<em>y)</em>(.8m * 1.732050808m);</p>
<p>will fix it.</p>
| 47,477
|
<p>I want to be able to link to sharepoint documents without having to refer to the document name which may change.
Is there anyway to programmatically add a unique key to the meta-data and then somehow use this in a link?</p>
|
<p>Every library has a GUID as an identifier. You can programmatically get that GUID and get the url from that.</p>
|
<p>Every library has a GUID as an identifier. You can programmatically get that GUID and get the url from that.</p>
| 36,423
|
<p>How do I use the profiler in Visual Studio 2008?</p>
<p>I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item).</p>
<p>Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?</p>
|
<p>Microsoft has released stand-alone Profiler for VS 2008 <a href="http://www.microsoft.com/downloads/details.aspx?familyid=fd02c7d6-5306-41f2-a1be-b7dcb74c9c0b&displaylang=en" rel="noreferrer">here</a></p>
|
<p>As I understood from reading a few sites, when you use VS 2008 stand alone profiler to create <code>.vsp</code> files, you will need either VS2008 Premium or Ultimate to view <code>.vsp</code> files.</p>
<p>By the way, I installed VS2012 Release candidate which is available for free (trial version?) and I can use its profiling engine.</p>
| 8,689
|
<p>This might be a naive question. I have to manually edit a .WXS file to make it support select features from command line.</p>
<p>For example, there are 3 features in .WXS file.</p>
<pre><code><Feature Id="AllFeature" Level='1'>
<Feature Id="Feature1" Level='1'> </Feature>
<Feature Id="Feature2" Level='1'> </Feature>
<Feature Id="Feature3" Level='1'> </Feature>
</Feature>
</code></pre>
<p>Now, I want to select features from command line. Say, if I type "msiexec /i install.msi FEATURE=A", then "Feature1" and "Feature2" is installed; if I type "msiexec/i install.msi FEATURE=B", then "Feature1" and "Feature3" is installed. In this case, "A" maps to Feature 1 and 2; "B" maps to Feature 1 and 3.</p>
<p>How to accomplish this in WIX?</p>
|
<p>I would change Feature1, Feature2 and Feature3 to Components, then would declare something like this:</p>
<pre><code><Feature Id="FEATUREA" Title="Super" Level="1" >
<ComponentRef Id="Component1" />
<ComponentRef Id="Component2" />
</Feature>
<Feature Id="FEATUREB" Title="Super1" Level="1" >
<ComponentRef Id="Component1" />
<ComponentRef Id="Component3"/>
</Feature>
</code></pre>
<p>Then to Install either FeatureA or FeatureB</p>
<pre><code>msiexec /i install.msi ADDLOCAL=[FEATUREA | FEATUREB]
</code></pre>
|
<p>There are a number of properties that can control the install states of Features. Check out this MSI SDK documentation and the links from it: <a href="http://msdn.microsoft.com/en-us/library/aa367536(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa367536(VS.85).aspx</a></p>
| 30,574
|
<p>Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?</p>
<p>This is what I want to re-write:</p>
<pre><code>foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
</code></pre>
|
<p>Mine would be this in c# 3.0 :)</p>
<pre><code>var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
</code></pre>
<p>Basically, the least amount of iterations will always be:</p>
<pre><code>loop assemblies
loop types
see if implemented.
</code></pre>
|
<p>You could use some LINQ to get the list:</p>
<pre><code>var types = from type in this.GetType().Assembly.GetTypes()
where type is ISomeInterface
select type;
</code></pre>
<p>But really, is that more readable?</p>
| 4,630
|
<p>Is it possible to reload a page that was loaded thru link_to_remote? I'm doing this in my controller: <br></p>
<pre><code>def create
if captchas_verified
do_something
else
render :action=>'new'
end
</code></pre>
<p>But when the captchas is wrong, it do not render a form that is inside of the new template. By the way, in the webserver log, it shows that the templades was rendered.</p>
<p>Thanks!</p>
<p>UPDATED: Today i changed the render to:</p>
<pre><code>render(:update) { |page| page.call 'location.reload' }
</code></pre>
<p>But it makes me update the page that called the link_to_remote not the page that was opened thru the link_to_remote</p>
<p>UPDATED 2: I fixed using
page.replace_html "mydiv", :partial => "new"
instead of
page.call 'location.reload'</p>
|
<p>You need to <code>render :update</code>, rather than <code>render :action</code>.</p>
<p>I do this sort of thing all the time. Similar to the response from jdl you can use inline rjs (don't know if that's the right term) to render the page.</p>
<pre><code>render(:update) do |page|
page.replace_html("div_to_update", :partial => "name_of_template", :object => @object)
page << "alert('javascript can be inserted here as well')"
end
</code></pre>
|
<p>Something like this should do what you want.</p>
<pre><code>render :update do |page| page << 'window.location.reload()' end
</code></pre>
| 25,165
|
<p>I use a stream reader to import some data and at the moment I hardcode a small sample file in the test to do the job.</p>
<p>Is it sensible to use Mock Objects with this and how ?</p>
|
<p>I don't see any points to mock StreamReader unless you're making StreamReader derived class. If you need to provide test input via StreamReader, just read some predefined data from any suitable source.</p>
|
<p>When testing code that depends on streams, streamreaders and streamwriters I usually use the memorystream object for testing. No mocking framework needed here.</p>
| 8,753
|
<p>In <a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="noreferrer">Vim</a>, how do I insert characters at the beginning of each line in a selection?</p>
<p>For instance, I want to comment out a block of code by prepending <code>//</code> at the beginning of each line assuming my language's comment system doesn't allow block commenting like <code>/* */</code>. How would I do this?</p>
|
<ol>
<li>Press <kbd>Esc</kbd> to enter 'command mode'</li>
<li>Use <kbd>Ctrl</kbd>+<kbd>V</kbd> to enter visual block mode</li>
<li>Move <kbd>Up</kbd>/<kbd>Down</kbd>to select the columns of text in the lines you want to
comment.</li>
<li>Then hit <kbd>Shift</kbd>+<kbd>i</kbd> and type the text you want to insert.</li>
<li>Then hit <kbd>Esc</kbd>, wait 1 second and the inserted text will appear on every line.</li>
</ol>
<p>For further information and reading, check out "<a href="https://vim.wikia.com/wiki/Inserting_text_in_multiple_lines" rel="noreferrer">Inserting text in multiple lines</a>" in the Vim Tips Wiki.</p>
|
<p>Mapping of most voted answer:</p>
<p>1st visual select the desired lines, then execute <code><leader>zzz</code>, which values:</p>
<pre><code>vnoremap <leader>zzz <C-V>^I-<Space><Esc>
</code></pre>
<ul>
<li><code><C-V></code> to enter visual mode</li>
<li><code>^</code> goes to start of line ( or use '<code>0</code>' to 1st non blank)</li>
<li><code>I</code> to insert in block mode</li>
<li><code>-<Space></code> to insert '- ' (for example, edit as you need)</li>
<li><code><Esc></code> to apply same insert to all visual block lines</li>
</ul>
<p>Or of last visual selection from normal mode:</p>
<pre><code>nnoremap <leader>zzz gv<C-V>^I-<Space><Esc>
</code></pre>
| 31,584
|
<p>I know there have been a few threads on this before, but I have tried absolutely everything suggested (that I could find) and nothing has worked for me thus far...</p>
<p>With that in mind, here is what I'm trying to do:</p>
<p>First, I want to allow users to publish pages and give them each a subdomain of their choice (ex: <code>user.example.com</code>). From what I can gather, the best way to do this is to map <code>user.example.com</code> to <code>example.com/user</code> with mod_rewrite and <code>.htaccess</code> - is that correct?</p>
<p>If that is correct, can somebody give me explicit instructions on how to do this?</p>
<p>Also, I am doing all of my development locally, using MAMP, so if somebody could tell me how to set up my local environment to work in the same manner (I've read this is more difficult), I would greatly appreciate it. Honestly, I have been trying a everything to no avail, and since this is my first time doing something like this, I am completely lost.</p>
<p><em>Some of these answers have been REALLY helpful, but for the system I have in mind, manually adding a subdomain for each user is not an option. What I'm really asking is how to do this on the fly, and redirect <code>wildcard.example.com</code> to <code>example.com/wildcard</code> -- the way Tumblr is set up is a perfect example of what I'd like to do.</em></p>
|
<p>As far as how to set up the DNS subdomain wildcard, that would be a function of your DNS hosting provider. This would be different steps depending on which hosting provider you have and would be a better question for them.</p>
<p>Once you've set that up with the DNS host, from your web app you really are just URL rewriting, which can be done with some sort of module for the web server itself, such as isapi rewrite if you're on IIS (this would be the preferred route if possible). You could also handle rewriting at the application level as well (like using routing if on ASP.NET).</p>
<p>You'd rewrite the URL so <code>http://myname.example.com</code> would become <code>http://example.com/something.aspx?name=myname</code> or something. From there on out, you just handle it as if the myname value was in the query string as normal. Does that make sense? Hope I didn't misunderstand what you're after.</p>
<p>I am not suggesting that you create a subdomain for each user, but instead create a wildcard subdomain for the domain itself, so <em>anything</em>.example.com (basically <code>*.example.com</code>) goes to your site. I have several domains setup with MyDomain. Their instructions for setting this up is like this:</p>
<blockquote>
<p>Yes, you can configure a wild card but
it will only work if you set it up as
an A Record. Wildcards do not work
with a C Name. To use a wildcard, you
use the asterisks character '<em>'. For
example, if you create and A Record
using a wild card, <code>*.example.com</code>,
anything that is entered in the place
where the '</em>' is located, will resolve
to the specified IP address. So if you
enter 'www', 'ftp', 'site', or
anything else before the domain name,
it will always resolve to the IP
address</p>
</blockquote>
<p>I have some that are setup in just this way, having <code>*.example.com</code> go to my site. I then can read the base URL in my web app to see that <code>ryan.example.com</code> is what was currently accessed, or that <code>bill.example.com</code> is what was used. I can then either:</p>
<ol>
<li>Use URL rewriting so that the subdomain becomes a part of the query string OR</li>
<li>Simply read the host value from the accessed URL and perform some logic based on that value.</li>
</ol>
<p>Does that make sense? I have several sites set up in just this exact way: create the wildcard for the domain with the DNS host and then simply read the host, or base domain from the URL to decide what to display based on the subdomain (which was actually a username)</p>
<p><strong>Edit 2:</strong></p>
<p>There is no way to do this without a DNS entry. The "online world" needs to know that <code>name1.example.com</code>, <code>name2.example.com</code>,..., <code>nameN.example.com</code> all go to the IP address for your server. The only way to do this is with the appropriate DNS entry. You have to add the wildcard DNS entry for your domain with your DNS host. Then it's just a matter of you reading the subdomain from the URL and taking the appropriate action in your code.</p>
|
<blockquote>
<p>First, I want to allow users to
publish pages and give them each a
subdomain of their choice (ex:
user.mysite.com). From what I can
gather, the best way to do this is to
map user.mysite.com to mysite.com/user
with mod_rewrite and .htaccess - is
that correct?</p>
</blockquote>
<p>You may be better off using <a href="http://httpd.apache.org/docs/1.3/vhosts/" rel="nofollow noreferrer">virtual hosts</a>. That way, each user can have a webserver configuration pretty much independent of others.</p>
<p>The syntax goes something like this:</p>
<pre><VirtualHost *:80>
DocumentRoot /var/www/user
ServerName user.mysite.com
...
</VirtualHost></pre>
| 10,517
|
<p>I have a web application written using CherryPy, which is run locally on <code>127.0.0.1:4321</code>. We use mod-rewrite and mod-proxy to have Apache act as a reverse proxy; Apache also handles our SSL encryption and may eventually be used to transfer all of our static content.</p>
<p>This all works just fine for small workloads. However, I recently used <code>urllib2</code> to write a stress-testing script that would simulate a workload of 100 clients. After some time, each client gets a 503 error from Apache, indicating that Apache cannot connect to <code>127.0.0.1:4321</code>. CherryPy is functioning properly, but my Apache error log reveals lines like the following:</p>
<p><code>[Thu Oct 02 12:55:44 2008] [error] (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : proxy: HTTP: attempt to connect to 127.0.0.1:4321 (*) failed</code></p>
<p>Googling for this error reveals that Apache has probably run out of socket file descriptors. Since I only have 100 clients running, this implies that the connections are not being closed, either between my <code>urllib2</code> connection and Apache (I am definitely calling <code>.close()</code> on the return value of <code>urlopen</code>), or between Apache and CherryPy.</p>
<p>I've confirmed that my <code>urllib2</code> request is sending an HTTP <code>Connection: close</code> header, although Apache is configured with <code>KeepAlive On</code> if that matters.</p>
<p>In case it matters, I'm using Python 2.5, Apache 2.2, CherryPy 3.0.3, and the server is running on Windows Server 2003.</p>
<p>So what's my next step to stop this problem?</p>
|
<p><code>SetEnv proxy-nokeepalive 1</code> would probably tell you right away if the problem is keepalive between Apache and CP. See the <a href="http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#envsettings" rel="noreferrer">mod_proxy docs</a> for more info.</p>
|
<p>You might run the netstat command and see if you have a bunch of sockets in the TIME_WAIT state. Depending on your MaxUserPort setting you might be severly limited in the number of ports available to use. In addition the TcpTimedWaitDelay is usually set to 240 seconds so any sockets that are used cannot be reused for four minutes.</p>
<p>There's more good information here --> <a href="http://smallvoid.com/article/winnt-tcpip-max-limit.html" rel="noreferrer">http://smallvoid.com/article/winnt-tcpip-max-limit.html</a></p>
| 19,779
|
<p>I have tried:</p>
<ol>
<li>Xdebug and Eclipse. Eclipse launches a web browser, but the browser tries to access a non-existent file in Eclipse's .app bundle.</li>
<li>Xdebug and NetBeans. It does a little bit better; a browser opens a page in /tmp which says "Launching. Please wait…" but nothing happens beyond that.</li>
<li>Xdebug and debugclient, the CLI tool which comes with Xdebug. MacPorts (which I used to install PHP and Xdebug) doesn't seem to install this by itself, and when I try compiling it by hand, I get told "you have strange libedit". Installing libedit via MacPorts doesn't solve that.</li>
<li>Zend's debugger (the precise name escapes me right now) and Eclipse. I can't recall what the problem was, as this was some time ago, but it didn't work.</li>
</ol>
<p>With regards to Xdebug, at least, I'm fairly confident I've installed it correctly. It shows up with both a phpinfo() in a PHP file and a <code>php -i</code> in the CLI.</p>
<p>If anyone has managed to get PHP debugging working in some way or other on the Mac, I'd appreciate it if you could share with me how. Littering code with <code>var_dump($foo);die();</code> gets old quick. Bonus points if it can be done <em>without</em> using some bloatware editor like Eclipse, or that expensive proprietary thing Zend wants to sell me.</p>
<p>My server is connecting to PHP via FastCGI, if that makes a diff.</p>
|
<p>You may want to look into <a href="http://www.bluestatic.org/software/macgdbp/" rel="noreferrer">MacGDBp</a>. It's new, free, and the UI looks great. It utilizes the Xdebug PHP extension as well. You can find instructions in the <a href="http://www.bluestatic.org/software/macgdbp/help.php" rel="noreferrer">help</a> section, which includes Xdebug configurations, and there's also a nice overview of the app from the guys at Particletree here: <a href="http://particletree.com/notebook/silence-the-echo-with-macgdbp/" rel="noreferrer">Silence The Echo with MacGDBp</a>.</p>
|
<p>I guess I don't get bonus points, but Zend Studio works for me on my Mac connecting to Apache running in VMware.</p>
| 10,584
|
<p>Suppose I have three classes. It is valid to instantiate A, but there are also special cases B and D which subclass A, adding additional information.</p>
<p>How would I do the mapping files for this in (fluent) NHibernate?</p>
<pre><code>public class A
{
public int ID { get; set;}
public string CommonProperty1 { get; set; }
public string CommonProperty2 { get; set; }
}
public class B : A
{
public string BSpecificProperty1 { get; set; } //not null
public string BSpecificProperty2 { get; set; } //not null
}
public class D : A
{
public string DSpecificProperty { get; set; } //not null
}
</code></pre>
<p>I tried the following, but it doesn't work at all:</p>
<pre><code>public class AMap : ClassMap<A>
{
public AMap()
{
Id(x => x.ID);
Map(x => x.CommonProperty1);
Map(x => x.CommonProperty2);
}
}
public class BMap : ClassMap<B>
{
public BMap()
{
References(x => x.ID);
Map(x => x.BSpecificProperty1)
.CanNotBeNull();
Map(x => x.BSpecificProperty2)
.CanNotBeNull();
}
}
public class DMap : ClassMap<D>
{
public DMap()
{
References(x => x.ID);
Map(x => x.DSpecificProperty)
.CanNotBeNull();
}
}
</code></pre>
|
<p>I'm not sure I understand what you mean by "map a subclass one-to-one", but if you want to map inheritance where the subclasses have properties that are not nullable, you can do like this in Fluent-NHibernate:</p>
<pre><code>// Domain classes
public class Animal
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class Cat : Animal
{
public virtual int WhiskerLength { get; set; }
public virtual int ClawCount { get; set; }
}
public class Dog : Animal
{
public virtual int TailWagRate { get; set; }
}
// Mapping file
public class AnimalMap : ClassMap<Animal>
{
public AnimalMap()
{
Id(x => x.Id)
.WithUnsavedValue(0)
.GeneratedBy.Native();
Map(x => x.Name);
var catMap = JoinedSubClass<Cat>("CatId", sm => sm.Map(x => x.Id));
catMap.Map(x => x.WhiskerLength)
.CanNotBeNull();
catMap.Map(x => x.ClawCount)
.CanNotBeNull();
JoinedSubClass<Dog>("DogId", sm => sm.Map(x => x.Id))
.Map(x => x.TailWagRate)
.CanNotBeNull();
}
}
</code></pre>
<p>Since you want the subclasses' properties to be not-null, you have to use the table-per-class (joined-subclass) way of modeling the inheritance. This is because table-per-hierarchy requires all subclass properties to be nullable.</p>
<p>I hope it helps.</p>
<p>/Erik</p>
|
<p>The syntax may have changed in FNH since Erik's post, but his example is right on target. Here's some code I used based on Erik's post to work through FNH the two FNH subclass strategies I know of right now (SubClass (the commented out code below, and JoinedSubClass). As an aside, I've seen other names used to describe the same strategies, including in NHibernate docs, which is a bit confusing when this is new to you. (<a href="https://www.hibernate.org/hib_docs/nhibernate/html/inheritance.html" rel="nofollow noreferrer">https://www.hibernate.org/hib_docs/nhibernate/html/inheritance.html</a>). </p>
<pre><code>// Domain classes
public class Animal : Entity
{
public virtual string Name { get; set; }
public virtual string Unwanted { get; set; }
}
public class Cat : Animal
{
public virtual int WhiskerLength { get; set; }
public virtual int ClawCount { get; set; }
}
public class Dog : Animal
{
public virtual int TailWagRate { get; set; }
}
public class Boxer : Dog
{
public string DroolBucket { get; set; }
}
public class AnimalMapJoinedSubclassOverride : IAutoMappingOverride<Animal>
{
public void Override(AutoMap<Animal> mapping) {
mapping.Map(x => x.Name);
mapping.IgnoreProperty(x => x.Unwanted);
mapping.JoinedSubClass("CatId", CatMap.AsJoinedSubClass());
mapping.JoinedSubClass("DogId", DogMap.AsJoinedSubClass());
//mapping.DiscriminateSubClassesOnColumn("Type")
// .SubClass<Cat>("CatId", CatMap.AsSubClass())
// .SubClass<Dog>("CatId", DogMap.AsSubClass());
}
}
public class CatMap
{
public static Action<JoinedSubClassPart<Cat>> AsJoinedSubClass()
{
return part =>
{
part.Map(x => x.ClawCount).Not.Nullable();
part.Map(x => x.WhiskerLength).Not.Nullable();
};
}
public static Action<SubClassPart<Cat>> AsSubClass()
{
return part =>
{
part.Map(x => x.ClawCount);
part.Map(x => x.WhiskerLength);
};
}
}
public class DogMap
{
public static Action<JoinedSubClassPart<Dog>> AsJoinedSubClass()
{
return sub =>
{
sub.Map(x => x.TailWagRate).Not.Nullable();
};
}
public static Action<SubClassPart<Dog>> AsSubClass()
{
return sub =>
{
sub.Map(x => x.TailWagRate);
};
}
}
public class BoxerMap
{
public static Action<JoinedSubClassPart<Boxer>> AsJoinedSubClass()
{
return sub =>
{
sub.Map(x => x.DroolBucket);
};
}
public static Action<SubClassPart<Boxer>> AsSubClass()
{
return sub =>
{
sub.Map(x => x.DroolBucket);
};
}
}
</code></pre>
| 37,961
|
<p>FxCop has the <a href="http://msdn.microsoft.com/en-ca/ms182327.aspx" rel="nofollow noreferrer">CollectionPropertiesShouldBeReadOnly rule</a> that complains if your class has some kind of collection property that clients can set. Instead, it suggests making the property read-only and supplying a Clear() method and Add() or AddRange() methods for changing the contents of the collection.</p>
<p>I agree that makes for a cleaner and more controlled interface, but I'm struggling to make that interface work with the Spring framework. If I want to configure an object with a collection of collaborators, I have to expose some collection property to inject the collaborators into. I've looked through <a href="http://springframework.net/docs/1.1.2/reference/html/index.html" rel="nofollow noreferrer">the Spring documentation</a>, and I can't see any way to tell Spring to call the AddRange() method, am I missing something?</p>
<p>For now, I'm going to exclude the warning with a note that it's necessary for Spring configuration.</p>
<p><strong>Update:</strong> since I didn't get any nibbles here in the last two months, I posted the same question on the <a href="http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/1f9c8929-01eb-4388-89e8-8462b61975f1" rel="nofollow noreferrer">FxCop forum</a>.</p>
|
<p>If the collection property only has a getter exposed, we will assume the FxCop recommended patterns you list is used and add to the collection. The first pattern is also supported. </p>
<p>For generic collections this is only working if the exposed property is of the type IList. We have a <a href="http://jira.springframework.org/browse/SPRNET-878" rel="nofollow noreferrer">JIRA issue</a> for the next release to fix this. BTW, this is a very common pattern in the base class libraries (as you probably know...) which is where we first encountered the need to support this style in .NET 1.1 (which doesn't suffer from the limitation listed above). </p>
<p>Cheers,
Mark</p>
|
<p>Is the problem as bad as you think? My understanding is that FxCop will complain if you have a read/write property like this:</p>
<pre><code>public List<Foo> Items { get; set; }
</code></pre>
<p>... because users of your class would then be able to do this:</p>
<pre><code>myInstance.Items = new List<Foo>();
</code></pre>
<p>Obviously you don't want users of your class to completely reassign the list. FxCop therefore recommends this pattern:</p>
<pre><code>private List<Foo> _items = new List<Foo>();
public List<Foo> Items { get { return _items; } }
</code></pre>
<p>So now users of your class can only Add and Remove items from your list, rather than overwriting it with a new instance of List.</p>
<p>How does Spring.NET implement its collection properties? Are they really read/write like my first example? If so, it'd be interesting to see their use-cases for such a pattern, because it doesn't seem right.</p>
| 25,329
|
<p>Is there available any tool for PHP which can be used to generate code for consuming a <a href="http://en.wikipedia.org/wiki/Web_service" rel="noreferrer">web service</a> based on its <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language" rel="noreferrer">WSDL</a>? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin which does the same thing for Java.</p>
|
<p>In PHP 5 you can use <a href="http://www.php.net/manual/en/ref.soap.php" rel="noreferrer">SoapClient</a> on the WSDL to call the web service functions. <a href="http://www.php.net/manual/en/soapclient.construct.php" rel="noreferrer">For example</a>:</p>
<pre><code>$client = new SoapClient("some.wsdl");
</code></pre>
<p>and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:</p>
<pre><code>$result = $client->getTime();
</code></pre>
<p>And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.</p>
|
<p>Well, those features are specific to a tool that you are using for development in those languages.</p>
<p>You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.</p>
<p>For PHP: <a href="http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html" rel="nofollow noreferrer">http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html</a></p>
| 2,643
|
<p>I've been trimming the UI of our website by doing the following in the onload event of that control:</p>
<pre><code>btnDelete.isVisible = user.IsInRole("can delete");
</code></pre>
<p>This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over.</p>
<p>Any suggestions?</p>
|
<p>One simple suggestion would be to group controls into panels based on access rights</p>
|
<p>A quick and dirty option is using the asp:loginview controls, which can be wired up to user roles.</p>
<p>Not as elegant as the custom page class option suggested by Jonathan, and can be a bit of a performance hit if they are all over the page.</p>
| 11,487
|
<p>How to configure Tomcat 5.5 to authenticate against Win2003 Activedirectory(LDAP)</p>
<p>What changes are needed to default tomcat configuration, at least server.xml needs to be changed somehow to have IP of Win2003 server?</p>
|
<p>I don't know if "automatic" login with IE is possible.</p>
<p>But you can use a "classic" login form (Java EE style) and let Tomcat perform the login against Active Directory using a JNDI Realm.</p>
<p>change the default realm in your server.xml or set the realm in your application's context.xml like this:</p>
<pre><code> <Realm
className="org.apache.catalina.realm.JNDIRealm"
debug="99"
connectionURL="ldap://your-activedirectory-server:389"
connectionName="a user with read access to AD (optional if anonymous access is permitted)"
connectionPassword="password"
referrals="follow"
userBase="where to look for users, for instance: DC=mycompany,DC=com"
userSearch="(sAMAccountName={0})"
userSubtree="true"
roleBase="where to look for groups, for instance: DC=mycompany,DC=com"
roleName="cn"
roleSearch="(member={0})"
roleSubtree="true"/>
</code></pre>
<p>More informations here: <a href="http://tomcat.apache.org/tomcat-5.5-doc/realm-howto.html#JNDIRealm" rel="nofollow noreferrer">Apache Tomcat 5.5 Realm Configuration HOW-TO</a></p>
<p>And: <a href="http://www.jspwiki.org/wiki/ActiveDirectoryIntegration" rel="nofollow noreferrer">Active Directory Integration</a></p>
|
<p><a href="http://wiki.openi.org/index.php/Configuring_Tomcat_With_Active_Directory" rel="nofollow noreferrer">Configuring Tomcat With Active Directory</a>. Have not tried it. Good luck.</p>
| 44,718
|
<p>I'm working on a programming language, and today I got the point where I could compile the factorial function(recursive), however due to the maximum size of an integer the largest I can get is factorial(12). What are some techniques for handling integers of an arbitrary maximum size. The language currently works by translating code to C++.</p>
|
<p>If you need larger than 32-bits you could consider using 64-bit integers (long long), or use or write an arbitrary precision math library, e.g. <a href="http://gmplib.org/" rel="noreferrer">GNU MP</a>.</p>
|
<p>Other posters have given links to libraries that will do this for you, but it seem like you're trying to build this into your language. My first thought is: are you sure you need to do that? Most languages would use an add-on library as others have suggested.</p>
<p>Assuming you're writing a compiler and you do need this feature, you could implement integer arithmetic functions for arbitrarily large values in assembly.</p>
<p>For example, a simple (but non-optimal) implementation would represent the numbers as Binary Coded Decimal. The arithmetic functions could use the same algorithms as you'd use if you were doing the math with pencil and paper.</p>
<p>Also, consider using a specialized data type for these large integers. That way "normal" integers can use the standard 32 bit arithmetic.</p>
| 39,978
|
<p>Say I have an array of strings in a php array called $foo with a few hundred entries, and I have a MySQL table 'people' that has a field named 'name' with a few thousand entries. What is an efficient way to find out which strings in $foo aren't a 'name' in an entry in 'people' without submitting a query for every string in $foo? </p>
<p>So I want to find out what strings in $foo have not already been entered in 'people.'</p>
<p>Note that it is clear that all of the data will have to be on one box at one point. The goal would be doing this at the same time minimizing the number of queries and the amount of php processing.</p>
|
<p>I'd put your $foo data in another table and do a LEFT OUTER JOIN with your names table. Otherwise, there aren't a lot of great ways to do this that don't involve iteration at some point.</p>
|
<p>I'm not sure there is a more efficient way to do this other than to submit all the strings to the database.</p>
<p>Basically there are two options: get a list of all the strings in MySQL and pull them into PHP and do the comparisons, or send the list of all the strings to the MySQL server and let it do the comparisons. MySQL is going to do the comparisons much faster than PHP, unless the list in the database is a great deal smaller than the list in PHP.</p>
<p>You can either create a temporary table, but either way your pushing all the data to the database.</p>
| 27,146
|
<p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
|
<p>Nope. But you can use short integers in arrays:</p>
<pre><code>from array import array
a = array("h") # h = signed short, H = unsigned short
</code></pre>
<p>As long as the value stays in that array it will be a short integer.</p>
<ul>
<li>documentation for the <a href="http://docs.python.org/dev/library/array" rel="noreferrer">array module</a></li>
</ul>
|
<p>You can also store multiple any size of integers in a single large integer.</p>
<p>For example as seen below, in python3 on 64bit x86 system, 1024 bits are taking 164 bytes of memory storage. That means on average one byte can store around 6.24 bits. And if you go with even larger integers you can get even higher bits storage density. For example around 7.50 bits per byte with 2**20 bits wide integer.</p>
<p>Obviously you will need some wrapper logic to access individual short numbers stored in the larger integer, which is easy to implement.</p>
<p>One issue with this approach is your data access will slow down due use of the large integer operations.</p>
<p>If you are accessing a big batch of consecutively stored integers at once to minimize the access to large integers, then the slower access to long integers won't be an issue.</p>
<p>I guess use of numpy will be easier approach.</p>
<pre><code>>>> a = 2**1024
>>> sys.getsizeof(a)
164
>>> 1024/164
6.2439024390243905
>>> a = 2**(2**20)
>>> sys.getsizeof(a)
139836
>>> 2**20 / 139836
7.49861266054521
</code></pre>
| 14,627
|
<p>I am looking for any tool which will allow the performance testing/tuning of Sybase nested stored procedures. There are many tools around and of course Sybase's own for performance tuning and testing SQL but none of these can handle nested stored procedures (i.e. a stored proc calling another stored proc). Does anyone have/know of such a tool?</p>
|
<p>Inside of an ASP.Net web.config you can setup locations to add security to specific files and folders. In addition, you can remove all verbs from those directories:</p>
<pre><code><location path="Secret" allowOverride="false">
<system.web>
<authorization>
<deny users="*" />
</authorization>
<httpHandlers>
<remove path="*.*" verb="*"/>
</httpHandlers>
</system.web>
</location>
</code></pre>
<p>I have only used the authorization portion of that snippet and it works great. The handler should further lock it down and using a ISAPI filter would be able to put the finishing touches on it.</p>
|
<p>There are some things you can do with web.config like defining security settings etc...
Other times you have to use HttpModules or HttpHandlers, look here:
<a href="http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx</a></p>
<p>If not, you can find different ISAPI, but in this case you need access to IIS.
For example, the ISAPI for emulating rewrite mod apache:</p>
<p><a href="http://www.codeplex.com/IIRF" rel="nofollow noreferrer">> http://www.codeplex.com/IIRF</a></p>
<p>The other question, yes ASPNETDB.MDF in APP_Data is protected normally (it depends on your administrator). To change the path, change the connectionstring.</p>
| 40,966
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.