instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have two PHP scripts, both using the same session by calling <code>session_name('MySessID')</code>.</p> <p>When the first script calls the second script using curl, the second script hangs when <code>session_start()</code> is called.</p> <p>Why would this happend?</p>
<p>I don't totally understand why this happens, but I got it solved.</p> <p>This <a href="http://bugs.php.net/bug.php?id=44134" rel="noreferrer">bug</a> describes the same problem I'm having. I have a scripts posting to another script, <em>both using the same session</em>, which apparently stalls PHP.</p> <p>So, before I do the whole curl post script, I call the <code>session_commit</code> function, so ending the calling scripts session, and enabling the called script to restart the session.</p> <p>Whack...</p>
<p>I got bitten by this as well. I fixed it thanks to the info provided in stackoverflow.</p> <p>I had two pages, both had "session_start()" at the top and the first was calling the second with curl so I could POST variables to the second script after validation. The webserver was hanging until I added "session_write_close()".</p> <p>Code sample follows:</p> <pre><code>// IMPORTANT (OR ELSE INFINITE LOOP) - close current sessions or the next page will wait FOREVER for a write lock. session_write_close(); // We can't use GET because we can't display the password in the URL. $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $url = "http://$host$uri/formPage2.php?"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); //append URL curl_setopt($ch, CURLOPT_POST,TRUE);//We are using method POST curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_REQUEST, '', "&amp;"));//append parameters curl_exec($ch); // results will be outputted to the browser directly curl_close($ch); exit(); </code></pre>
31,514
<p>I am working on a form, which I would like to validation features like <a href="http://ui-patterns.com/pattern/InputFeedback" rel="nofollow noreferrer">This</a>. Should this all be done on clientside? or server side? I am aware of using some of MS ajax controld, however, at what point do I display the message at the top?</p> <p>I hope I explained myself.</p>
<p><strong>You <em>should</em> validate at both ends.</strong></p> <ul> <li><p>Client side to make sure feedback is immediate so users can complete it fast (a bonus for them) and you save server resources (bonus for you).</p></li> <li><p>Server side to make sure that any user-agents not using JS can check the incoming data. This is essential to stop malicious/corrupt data entering your system.</p></li> </ul> <p>If you were only going to do one, make it server side, but there are considerable benefits to the user by implementing a dual-system.</p>
<p>validation on the client-side and provide feedback when they click the submit button</p> <p>but since you cannot trust client-side validation, also validation on the server side and display feedback on postback if everything is not correct</p> <p>but since you cannot trust the calling code, also validate in the database server (stored procedures are best) and raise errors back to the calling code if something is amiss</p> <p>that way you've covered all the bases</p>
34,727
<p>How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number?</p>
<p>There's a very long answer to this in the <a href="http://tangentsoft.net/wskfaq/advanced.html#backlog" rel="noreferrer">Winsock Programmer's FAQ</a>. It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0.</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/ms739168(VS.85).aspx" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.</p> </blockquote>
14,019
<p>Being fairly new to JavaScript, I'm unable to discern when to use each of these.</p> <p>Can anyone help clarify this for me?</p>
<p>If your situation requires the use of a regular expression, use the <code>search()</code> method, otherwise; the <code>indexOf()</code> method is more performant.</p>
<p>Without a <a href="http://www.w3schools.com/js/js_regexp.asp" rel="nofollow">regex</a>, there is no practical difference between <a href="http://www.w3schools.com/jsref/jsref_indexof.asp" rel="nofollow">indexOf</a> and <a href="http://www.w3schools.com/jsref/jsref_search.asp" rel="nofollow">search</a>.</p> <p>The below example gives a live <a href="http://jsfiddle.net/xameeramir/e6q1679k/" rel="nofollow">demo</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function FromSearch() { var str = document.getElementById("demo").innerText; var n = str.search("difference"); document.getElementById("Location").innerHTML = n; } function FromindexOf() { var str = document.getElementById("demo").innerText; var n = str.indexOf("difference"); document.getElementById("Location").innerHTML = n; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p id="demo"&gt;Without a &lt;a href='http://www.w3schools.com/js/js_regexp.asp'&gt;regex&lt;/a&gt;, there is no practical difference between &lt;a href='http://www.w3schools.com/jsref/jsref_indexof.asp'&gt;indexOf&lt;/a&gt; and &lt;a href='http://www.w3schools.com/jsref/jsref_search.asp'&gt;search&lt;/a&gt; &lt;/p&gt; &lt;button onclick="FromSearch()"&gt;From search&lt;/button&gt; &lt;button onclick="FromindexOf()"&gt;From indexOf&lt;/button&gt; &lt;p&gt;Location of difference in the above sentence is:&lt;/p&gt; &lt;mark id="Location"&gt;&lt;/mark&gt;</code></pre> </div> </div> </p>
46,125
<p>I've moved from TFS to SVN (TortoiseSVN) with my current company. I really miss the "Shelve" feature of TFS. I've read various articles on how to "Shelve" with SVN, but I've read nothing that gives a very simple experience to "shelve" work.</p> <p>Ideally, I'd like extra items added to the TortoiseSVN context menu - "Shelve" &amp; "Unshelve". "Shelve" would remove the current shelve-set, and upload the working directory under a suitable path defined by user options. "Unshelve" would merge the set with the working copy.</p> <p>Does something like this exist? Can anyone suggest any ways to "hack" this feature in the GUI?</p> <p>Note: The following link doesn't really achieve the user experience I was looking for:</p> <p><a href="http://mikemason.ca/2005/03/30/" rel="noreferrer">Shelving Subversion</a></p> <p>One of the greatest things about TFS Shelve is how easy it is to use...</p>
<p>I don't believe that SVN has this feature built into the server product. I also don't believe anything like this emulated in any clients that I have used, including TortoiseSVN.</p> <p>To get around this problem, I have resorted to using a DVCS such as <a href="http://git.or.cz/" rel="nofollow noreferrer">Git</a> or <a href="http://www.selenic.com/mercurial/" rel="nofollow noreferrer">Mercurial</a>, to allow me to branch/merge/shelve locally before pushing the content back to SVN. It's arguably a bit of a kludge, but it works really well.</p>
<h2>Support Feature</h2> <p>SVN supports for shelves is <strong>experimental</strong> means, it doesn't promise backward compatibility for future releases, either its disabled by default.</p> <p>it has been <a href="https://subversion.apache.org/docs/release-notes/1.10.html#shelving" rel="nofollow noreferrer">started with version 1.10</a></p> <p>but the shelves create with 1.10 &amp; 1.11 <a href="https://subversion.apache.org/docs/release-notes/1.12.html#cmdline" rel="nofollow noreferrer">is not supported by newer version</a>, as it didn't promises so.</p> <p>so there are different underlying and you have to pay attention that this is an experimental feature and is going to be improved over the time.</p> <p>the 1.10 shelve commands start with <code>svn shelve</code> but the 1.11 &amp; 1.12 starts with <code>svn x-shelve</code>.</p> <h2>Commands</h2> <p>the <a href="https://subversion.apache.org/docs/release-notes/1.14.html#shelving" rel="nofollow noreferrer">commands</a> for new shelve are:</p> <pre class="lang-sh prettyprint-override"><code> svn x-shelf-diff svn x-shelf-drop svn x-shelf-list, x-shelves svn x-shelf-list-by-paths svn x-shelf-log svn x-shelf-save svn x-shelve svn x-unshelve </code></pre> <h2>Activating</h2> <p>for activating using this feature you have to run the command by setting the enviourment variable:</p> <pre class="lang-sh prettyprint-override"><code>#Shelving-v3, as introduced in 1.12 SVN_EXPERIMENTAL_COMMANDS=shelf3 #Shelving-v2, as introduced in 1.11 SVN_EXPERIMENTAL_COMMANDS=shelf2 </code></pre> <p>further information can be found here:</p> <p><a href="https://subversion.apache.org/docs/release-notes/1.14.html#shelving" rel="nofollow noreferrer">https://subversion.apache.org/docs/release-notes/1.14.html#shelving</a></p>
2,994
<p>It is advisable to use tables in HTML pages (now that we have CSS)?</p> <p>What are the applications of tables? What features/abilities does tables have that are not in CSS?</p> <h1>Related Questions</h1> <ul> <li><a href="https://stackoverflow.com/questions/30251/tables-instead-of-divs">Tables instead of DIVs</a></li> <li><a href="https://stackoverflow.com/questions/83073/div-vs-table">DIV vs TABLE</a> <ul> <li><a href="https://stackoverflow.com/questions/96137/divs-vs-tables-a-rebuttal-please">DIVs vs. TABLEs a rebuttal please</a></li> </ul> </li> </ul>
<p>No - not at all. But use tables for tabular data. Just don't use them for general layouting.</p> <p>But if you display tabular data, like results or maybe even a form, go ahead and use tables!</p>
<p>I am going to assume that your question is actually - <em>"Should I avoid using HTML tables for layout purposes?"</em>. The answer is: No. In fact, tables are specifically meant to be used to control layout. The drawback for using tables to control the layout of an entire page is that the source file rapidly becomes difficult to manually understand and edit. A (possible) advantage of using tables to control the entire layout is if there are specific concerns about cross-browser compatibility and rendering. I prefer to work directly with the HTML source file, and for me using CSS makes that easier than using tables for the entire layout.</p>
10,810
<p>I have a JLabel (actually, it is a JXLabel).</p> <p>I have put an icon and text on it.</p> <p><code>&lt;icon&gt;&lt;text&gt;</code></p> <p>Now I wand to add some spacing on the left side of the component, like this:</p> <p><code>&lt;space&gt;&lt;icon&gt;&lt;text&gt;</code></p> <p>I DON'T accept suggestion to move the JLabel or add spacing by modifying the image.</p> <p>I just want to know how to do it with plain java code.</p>
<p>I have found the solution!</p> <pre><code>setBorder(new EmptyBorder(0,10,0,0)); </code></pre> <p>Thanks everyone!</p>
<p>You dont need to modify the preferredSize of the JLabel, you can use the <a href="http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html" rel="nofollow noreferrer">GridBagLayout</a> Manager to specify separations between components, you only have to use the GridBagLayout in the container and add the JXLabel to it with a <a href="http://java.sun.com/javase/6/docs/api/java/awt/GridBagConstraints.html" rel="nofollow noreferrer">GridBagConstraints</a> object specifiying the insets to the left:</p> <pre><code>JPanel panel=new JPanel(new GridBagLayout()); JLabel label=new JLabel("xxxxx"); GridBagConstraints constraints=new GridBagConstraints(); constraints.insest.left=X; // X= number of pixels of separation from the left component panel.add(label,constraints); </code></pre> <p>Note that i have omitted a lot of configuration properties in the setup of the constraints, you better read the documentacion of <a href="http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html" rel="nofollow noreferrer">GridBagLayout</a></p>
18,997
<p>I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.</p> <p>What I might try right now would be:</p> <pre><code>ISessionFactoryHolder factoryHolder = ActiveRecordMediator&lt;EntityClass&gt;.GetSessionFactoryHolder(); ISession session = factoryHolder.CreateSession(typeof(EntityClass)); try { IDbCommand cmd = session.Connection.CreateCommand(); cmd.CommandText = "spName"; cmd.ExecuteNonQuery(); } catch(Exception ex) { } finally { factoryHolder.ReleaseSession(session); } </code></pre> <p>However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.</p>
<p>This works for me (stored procedure with params and dynamic result table):</p> <pre><code>// get Connection System.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder() .GetSessionFactory(typeof(Autocomplete)) .ConnectionProvider.GetConnection(); // set Command System.Data.IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "name_of_stored_procedure"; cmd.CommandType = System.Data.CommandType.StoredProcedure; // set Parameter of Stored Procedure System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("@parameter_name", System.Data.SqlDbType.NVarChar); param.Value = "value_of_parameter"; ((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param); // call Stored Procedure (without getting result) cmd.ExecuteNonQuery(); // ... or read results System.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader(); while(r.Read()) { System.Console.WriteLine("result first col: " + r.GetString(0)); } </code></pre>
<pre><code>public ArrayList DevolverCamposDeObjetoSTP(T Objeto, List&lt;Consulta&gt; Consultas, string StoredProcedureName) { ArrayList results; try { var queryString = @"EXEC " + StoredProcedureName; foreach (var consulta in Consultas) { switch (consulta.tipoCampo) { case Consulta.TipoCampo.dato: queryString = queryString + " " + consulta.Campo + " = " + "'" + consulta.Valor + "'"; break; case Consulta.TipoCampo.numero: queryString = queryString + " " + consulta.Campo + " = " + consulta.Valor; break; } queryString = queryString + ","; } queryString = queryString.Remove(queryString.Count() - 1, 1); var query = new HqlBasedQuery(typeof(T),QueryLanguage.Sql, queryString); results = (ArrayList)ActiveRecordMediator.ExecuteQuery(query); } catch (Exception exception) { throw new Exception(exception.Message); } return results; } public class Consulta { public enum TipoCampo { dato, numero } public string Campo { get; set; } public TipoCampo tipoCampo { get; set; } public string Valor { get; set; } public string Indicador { get; set; } } public void _Pruebastp() { var p = new Recurso().DevolverCamposDeObjetoSTP( new Recurso(), new List&lt;Consulta&gt; { new Consulta { Campo = "@nombre", tipoCampo = Consulta.TipoCampo.dato, Valor = "chr" }, new Consulta { Campo = "@perfil", tipoCampo = Consulta.TipoCampo.numero, Valor = "1" } }, "Ejemplo"); } </code></pre>
22,820
<p>Using MAPI functions from within managed code is officially unsupported. Apparently, MAPI uses its own memory management and it crashes and burns within managed code (see <a href="http://blogs.msdn.com/pcreehan/archive/2007/05/04/what-does-unsupported-mean.aspx" rel="noreferrer">here</a> and <a href="http://blogs.msdn.com/mstehle/archive/2007/10/03/fyi-why-are-mapi-and-cdo-1-21-not-supported-in-managed-net-code.aspx" rel="noreferrer">here</a>)</p> <p><strong>All I want to do is launch the default e-mail client</strong> with subject, body, <strong>AND one or more attachments</strong>. </p> <p>So I've been looking into <a href="http://pinvoke.net/default.aspx/mapi32.MAPISendDocuments" rel="noreferrer">MAPISendDocuments</a> and it seems to work. But I haven't been able to gather courage to actually use the function in production code.</p> <p>Has anybody used this function a lot? Do you have any horror stories?</p> <p><em>PS. No, I won't shellExecute Outlook.exe with command line arguments for attachments.</em></p> <p><em>PPS. Attachment support is a</em> requirement <em>, so Mailto: solutions do not cut it for me.</em></p>
<p>Have a separate helper EXE that takes command-line params (or pipe to its StandardInput) that does what is required and call that from your main app. This keeps the MAPI stuff outside of your main app's process space. OK, you're still mixing MAPI and .NET but in a very short-lived process. The assumption is that MAPI and the CLR start causing issues with longer-running processes.</p> <p>We use Dmitry Streblechenko's superb <a href="http://www.dimastr.com/redemption/" rel="noreferrer">Redemption Data Objects</a> library which allows us to write such "shim" code in JScript and invoke that, which keeps the CLR and MAPI worlds in separate processes, but in a supported fashion.</p> <p>@Chris Fournier re. writing an unmanaged DLL. This won't work because the issue is mixing MAPI and managed code <em>in the same process</em>.</p>
<p>For someone experienced with MAPI, it would take them less time to crank out the code to do exactly what you want from unmanaged code (read: plain C++) than typing this post and reading the response (no offense).</p> <p>You're lucky the functionality you need is limited. All you need is a simple C++ utility to take the params you need on the command-line and issue the right MAPI calls. Then, you all this utility from your managed code just as you'd to execute any other process.</p> <p>HTH</p>
2,648
<p>I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application.</p> <p>This works on all the machines I've tested it on, except one.</p> <p>The problem is that the Delphi application gets "Class not registered" when trying to create the COM object.</p> <p>Now, when I look in the registry under <code>HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID</code>, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed.</p> <p>I have tried <code>regasm /unregister delphitocsharp.dll</code>, and that removes the registry key. Then if I do <code>regasm delphitocsharp.dll</code>, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered".</p> <p>DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine.</p> <p>All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused.</p> <p>How can I fix or at least further diagnose this issue?</p>
<p>The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example:</p> <pre><code>[Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)] public class MyCOMRegisteredClass </code></pre> <p>If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you.</p>
<p>Maybe you have an old version of the assembly somewhere? Maybe in the GAC? Regasm is probably picking that up and using it.</p>
17,780
<p>I was wondering if there is any way to escape a CDATA end token (<code>]]&gt;</code>) within a CDATA section in an xml document. Or, more generally, if there is some escape sequence for using within a CDATA (but if it exists, I guess it'd probably only make sense to escape begin or end tokens, anyway). </p> <p>Basically, can you have a begin or end token embedded in a CDATA and tell the parser not to interpret it but to treat it as just another character sequence.</p> <p>Probably, you should just refactor your xml structure or your code if you find yourself trying to do that, but even though I've been working with xml on a daily basis for the last 3 years or so and I have never had this problem, I was wondering if it was possible. Just out of curiosity.</p> <p>Edit:</p> <p>Other than using html encoding...</p>
<p>Clearly, this question is purely academic. Fortunately, it has a very definite answer.</p> <p>You cannot escape a CDATA end sequence. Production rule 20 of the XML <a href="http://www.w3.org/TR/REC-xml/#sec-cdata-sect" rel="noreferrer">specification</a> is quite clear:</p> <pre><code>[20] CData ::= (Char* - (Char* ']]&gt;' Char*)) </code></pre> <p>EDIT: This product rule literally means &quot;A CData section may contain anything you want BUT the sequence ']]&gt;'. No exception.&quot;.</p> <p>EDIT2: The <a href="http://www.w3.org/TR/REC-xml/#sec-cdata-sect" rel="noreferrer">same section</a> also reads:</p> <blockquote> <p>Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using &quot;<code>&amp;lt;</code>&quot; and &quot;<code>&amp;amp;</code>&quot;. CDATA sections cannot nest.</p> </blockquote> <p>In other words, it's not possible to use entity reference, markup or any other form of interpreted syntax. The only parsed text inside a CDATA section is <code>]]&gt;</code>, and it terminates the section.</p> <p>Hence, it is not possible to escape <code>]]&gt;</code> within a CDATA section.</p> <p>EDIT3: The <a href="http://www.w3.org/TR/REC-xml/#sec-cdata-sect" rel="noreferrer">same section</a> also reads:</p> <blockquote> <p>2.7 CDATA Sections</p> <p>[Definition: CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string &quot;&lt;![CDATA[&quot; and end with the string &quot;]]&gt;&quot;:]</p> </blockquote> <p>Then there may be a CDATA section anywhere character data may occur, including multiple adjacent CDATA sections inplace of a single CDATA section. That allows it to be possible to split the <code>]]&gt;</code> token and put the two parts of it in adjacent CDATA sections.</p> <p>ex:</p> <pre><code>&lt;![CDATA[Certain tokens like ]]&gt; can be difficult and &lt;invalid&gt;]]&gt; </code></pre> <p>should be written as</p> <pre><code>&lt;![CDATA[Certain tokens like ]]]]&gt;&lt;![CDATA[&gt; can be difficult and &lt;valid&gt;]]&gt; </code></pre>
<p>See this structure:</p> <pre><code>&lt;![CDATA[ &lt;![CDATA[ &lt;div&gt;Hello World&lt;/div&gt; ]]]]&gt;&lt;![CDATA[&gt; ]]&gt; </code></pre> <p>For the inner CDATA tag(s) you must close with <code>]]]]&gt;&lt;![CDATA[&gt;</code> instead of <code>]]&gt;</code>. Simple as that.</p>
27,622
<p>Is there any difference between a binary semaphore and mutex or are they essentially the same?</p>
<p>They are <strong>NOT</strong> the same thing. They are used for different purposes!<br> While both types of semaphores have a full/empty state and use the same API, their usage is very different. </p> <p><strong>Mutual Exclusion Semaphores</strong><br> Mutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..). </p> <p>A Mutex semaphore is "owned" by the task that takes it. If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail.</p> <p>Mutexes always use the following sequence: </p> <pre> - SemTake - Critical Section - SemGive</pre> <p>Here is a simple example:</p> <pre> Thread A Thread B Take Mutex access data ... Take Mutex &lt;== Will block ... Give Mutex access data &lt;== Unblocks ... Give Mutex </pre> <p><strong>Binary Semaphore</strong><br> Binary Semaphore address a totally different question: </p> <ul> <li>Task B is pended waiting for something to happen (a sensor being tripped for example).</li> <li>Sensor Trips and an Interrupt Service Routine runs. It needs to notify a task of the trip.</li> <li>Task B should run and take appropriate actions for the sensor trip. Then go back to waiting.</li> </ul> <pre><code> Task A Task B ... Take BinSemaphore &lt;== wait for something Do Something Noteworthy Give BinSemaphore do something &lt;== unblocks </code></pre> <p>Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.<br> Again, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled.<br> It typically makes little sense for the same task to so a give and a take on the same binary semaphore.</p>
<p>Almost all of the above said it right. Let me also try my bit to clarify if somebody still has a doubt.</p> <ul> <li>Mutex -> used for serialization</li> <li>Semaphore-> synchronization.</li> </ul> <p>Purpose of both are different however, same functionality could be achieved through both of them with careful programming.</p> <p>Standard Example-> producer consumer problem.</p> <pre><code>initial value of SemaVar=0 Producer Consumer --- SemaWait()-&gt;decrement SemaVar produce data --- SemaSignal SemaVar or SemaVar++ ---&gt;consumer unblocks as SemVar is 1 now. </code></pre> <p>Hope I could clarify.</p>
8,831
<p>I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"&gt; &lt;display-name&gt;MyEAR&lt;/display-name&gt; &lt;module&gt; &lt;web&gt; &lt;web-uri&gt;war1.war&lt;/web-uri&gt; &lt;context-root&gt;/&lt;/context-root&gt; &lt;/web&gt; &lt;/module&gt; &lt;module&gt; &lt;web&gt; &lt;web-uri&gt;war2.war&lt;/web-uri&gt; &lt;context-root&gt;/war2location&lt;/context-root&gt; &lt;/web&gt; &lt;/module&gt; &lt;/application&gt; </code></pre> <p>This results in war2.war being available on <strong><a href="http://localhost:8080/war2location" rel="nofollow noreferrer">http://localhost:8080/war2location</a></strong>, which is correct, but war1.war is on <strong><a href="http://localhost:8080//" rel="nofollow noreferrer">http://localhost:8080//</a></strong> -- note the two slashes.</p> <p>What am I doing wrong?</p> <p>Note that the WARs' sun-web.xml files get ignored when contained in an EAR.</p>
<p>In Glassfish 3.0.1 you can define the default web application in the administration console: "Configuration\Virtual Servers\server\Default Web Module". The drop-down box contains all deployed war modules.</p> <p>The default web module is then accessible from <a href="http://localhost:8080/" rel="noreferrer">http://localhost:8080/</a>.</p>
<p><code>http://localhost:8080//</code> should still be a valid URL that is equivalent to <code>http://localhost:8080/</code></p> <p>I'd experiment with leaving the context-root of war1 blank (though I'm not sure if that's allowed). Or changing it to <code>&lt;context-root&gt;.&lt;/context-root&gt;</code>.</p> <p>Otherwise I'd have to say the generated URI is a bug on glassfish's part since I've never seen that using sun's.</p>
15,514
<p>I would like to know what is the difference between initializing a static member inline as in:</p> <pre><code>class Foo { private static Bar bar_ = new Bar(); } </code></pre> <p>or initializing it inside the static constructor as in:</p> <pre><code>class Foo { static Foo() { bar_ = new Bar(); } private static Bar bar_; } </code></pre>
<p>If you have a static constructor in your type, it alters type initialization due to the <a href="http://pobox.com/~skeet/csharp/beforefieldinit.html" rel="noreferrer">beforefieldinit</a> flag no longer being applied.</p> <p>It also affects initialization order - variable initializers are all executed before the static constructor.</p> <p>That's about it as far as I know though.</p>
<p>Twilight zone answer: There is a difference in <strong>order of execution</strong> between inline initializers and ctor assignment... when you mix in instance and static members and inheritance to boot.</p> <pre><code>For static members, static initializers Static ctors (execute bottom up) Base static initializer Base static ctor and so on For instance members, initializers in current class execute first Then initializers in base class execute ( up the chain) Then top-most base ctor is executed (and we walk down now. Instance ctors execute top-down) Finally current type's ctor is executed. </code></pre> <p>Example :)</p> <pre><code>public class CBase { static Talkative m_Baseob1 = new Talkative("Base Static Initializer-"); static Talkative m_Baseob2; Talkative m_Baseob3 = new Talkative("Base Inst Initializer"); Talkative m_Baseob4; static CBase() { Console.WriteLine("***MethodBegin: Static Base Ctor"); m_Baseob2 = new Talkative("Base Static Ctor"); Console.WriteLine("***MethodEnd: Static Base Ctor"); } public CBase() { Console.WriteLine("***MethodBegin: Instance Base Ctor"); m_Baseob4 = new Talkative("Base Instance Ctor"); Console.WriteLine("***MethodEnd: Instance Base Ctor"); } } public class CDerived : CBase { static Talkative m_ob1 = new Talkative("Derived Static Initializer"); static Talkative m_ob2; Talkative m_ob3 = new Talkative("Derived Inst Initializer"); Talkative m_ob4; static CDerived() { Console.WriteLine("***MethodBegin: Derived Static Ctor"); m_ob2 = new Talkative("Derived Static Ctor"); Console.WriteLine("***MethodEnd: Derived Static Ctor"); } public CDerived() { Console.WriteLine("***MethodBegin: Derived Instance Ctor"); m_ob4 = new Talkative("Derived Instance Ctor"); Console.WriteLine("***MethodEnd: Derived Instance Ctor"); } } internal class Talkative { public Talkative(string sID) { Console.WriteLine(sID + " - Talkative created" ); } } # Main function somewhere CDerived s = new CDerived(); </code></pre> <p>Output:</p> <pre><code>Derived Static Initializer - Talkative created ***MethodBegin: Derived Static Ctor Derived Static Ctor - Talkative created ***MethodEnd: Derived Static Ctor Derived Inst Initializer - Talkative created Base Static Initializer- - Talkative created ***MethodBegin: Static Base Ctor Base Static Ctor - Talkative created ***MethodEnd: Static Base Ctor Base Inst Initializer - Talkative created ***MethodBegin: Instance Base Ctor Base Instance Ctor - Talkative created ***MethodEnd: Instance Base Ctor ***MethodBegin: Derived Instance Ctor Derived Instance Ctor - Talkative created ***MethodEnd: Derived Instance Ctor </code></pre>
26,874
<p>I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:</p> <pre><code>void IndexArray( unsigned int length, std::vector&lt;unsigned int&gt;&amp; v ) { v.resize(length); for ( unsigned int i = 0; i &lt; length; ++i ) { v[i] = i; } } </code></pre> <p>But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and <strong>not</strong> using Boost)?</p>
<p>You can use the generate algorithm, for a more general way of filling up containers:</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; struct c_unique { int current; c_unique() {current=0;} int operator()() {return ++current;} } UniqueNumber; int main () { vector&lt;int&gt; myvector (8); generate (myvector.begin(), myvector.end(), UniqueNumber); cout &lt;&lt; "\nmyvector contains:"; for (vector&lt;int&gt;::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout &lt;&lt; " " &lt;&lt; *it; cout &lt;&lt; endl; return 0; } </code></pre> <p>This was shamelessly lifted and edited from <a href="http://www.cplusplus.com/reference/algorithm/generate.html" rel="noreferrer">cplusplusreference</a>.</p>
<p>If you have a C style array you can use std:copy, e.g.,</p> <pre><code>int c_array[] = {3,4,5}; const int* pbegin = &amp;c_array[0]; const size_t c_array_size = sizeof(c_array) / sizeof(c_array[0]); const int* pend = pbegin + c_array_size; std::vector&lt;int&gt; v; v.reserve(c_array_size); std::copy(pbegin, pend, std:back_inserter(v)); </code></pre>
25,461
<p>Do you have any experience of designing a Real Shared-Nothing Architecture? Would you have some readings to recommend me?</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0596102356" rel="nofollow noreferrer" rel="nofollow noreferrer">Building Scalable Web Sites</a> by <a href="http://flickr.com" rel="nofollow noreferrer">Flickr</a> architect <a href="http://www.iamcal.com/" rel="nofollow noreferrer">Cal Henderson</a> is pretty much the holy book for scalable web architectures.</p> <p>The <a href="http://danga.com/words/" rel="nofollow noreferrer">presentations</a> by <a href="http://bradfitz.com/" rel="nofollow noreferrer">Brad Fitzpatrick</a> of <a href="http://danga.com" rel="nofollow noreferrer">Danga Interactive</a>, creators of LiveJournal, are also excellent case studies. Check out <a href="http://danga.com/words/2007_06_usenix/usenix.pdf" rel="nofollow noreferrer">this one</a> first.</p>
<p>I think that <a href="http://www.sitepoint.com/blogs/2004/07/01/the-j2ee-guy-still-doesnt-get-php/" rel="nofollow noreferrer">The J2EE guy still doesn’t get PHP</a> is (still) worth a read.</p>
3,981
<p>How do you post data to an iframe?</p>
<p>Depends what you mean by "post data". You can use the HTML <code>target=""</code> attribute on a <code>&lt;form /&gt;</code> tag, so it could be as simple as:</p> <pre><code>&lt;form action="do_stuff.aspx" method="post" target="my_iframe"&gt; &lt;input type="submit" value="Do Stuff!"&gt; &lt;/form&gt; &lt;!-- when the form is submitted, the server response will appear in this iframe --&gt; &lt;iframe name="my_iframe" src="not_submitted_yet.aspx"&gt;&lt;/iframe&gt; </code></pre> <p>If that's not it, or you're after something more complex, please edit your question to include more detail.</p> <p>There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a <a href="https://stackoverflow.com/questions/2181385/ie-issue-submitting-form-to-an-iframe-using-javascript">work-around here</a>), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.</p> <p>I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.</p> <p><strong>default.asp</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Form Iframe Demo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="do_stuff.asp" method="post" target="my_frame"&gt; &lt;input type="text" name="someText" value="Some Text"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;iframe name="my_frame" src="do_stuff.asp"&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>do_stuff.asp</strong></p> <pre><code>&lt;%@Language="JScript"%&gt;&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Form Iframe Demo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% if (Request.Form.Count) { %&gt; You typed: &lt;%=Request.Form("someText").Item%&gt; &lt;% } else { %&gt; (not submitted) &lt;% } %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I would be very interested to hear of any browser that doesn't run these examples correctly.</p>
<p>If you want to change inputs in an iframe then submit the form from that iframe, do this</p> <pre><code>... var el = document.getElementById('targetFrame'); var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below if (frame_win) { doc = (window.contentDocument || window.document); } if (doc) { doc.forms[0].someInputName.value = someValue; ... doc.forms[0].submit(); } ... </code></pre> <p>Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.</p> <pre><code>function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc &amp;&amp; iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc &amp;&amp; iframe_object.document) { doc = iframe_object.document; } if (doc &amp;&amp; doc.defaultView) { return doc.defaultView; } if (doc &amp;&amp; doc.parentWindow) { return doc.parentWindow; } return undefined; } </code></pre>
20,339
<p>For example:</p> <p>script.js:</p> <pre><code>function functionFromScriptJS() { alert('inside functionFromScriptJS'); } </code></pre> <p>iframe.html:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script language="Javascript" src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe&gt; &lt;body&gt; &lt;script language="JavaScript"&gt; functionFromScriptJS(); &lt;/script&gt; &lt;/body&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;html&gt; </code></pre> <p>The above call to functionFromScriptJS() is not working.</p> <p>The first guess parent.functionFromScriptJS() is not working too.</p> <p>Is it possible to access such an external function from an iframe when the include is not in the iframe itself but in the parent document?</p> <p><strong>@Edit:</strong> So my mistake was that I put the document inside the iframe tag, and I sould have put it in a separate file and specified through the src attrubute of the tag. In this case <em>parent.functionFromScriptJS()</em> works.</p>
<p>Iframes do not support inline content. you must use the src attribute to reference a different file. The inner text of the <code>&lt;iframe&gt;</code> tag will be displayed to browsers that do not support iframes.</p> <p>Example:</p> <pre><code>&lt;iframe src="someFile.html" width="100%" height="300px"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; </code></pre> <p>Once you have your page loading then you should be able to call the script using <code>parent.functionFromScriptJS();</code></p>
<p>The best solution here I think would be not to use an iframe (although not formally deprecated, it does not appear in the XHTML 1.1 spec) and to use an AJAX get to grab the page and load it into a <code>&lt;div&gt;</code></p> <p>Then javascript functions will work as normal!</p>
44,152
<p>How do you trace/profile your .NET applications? The MSDN online help mentions Visual Studio Team (which I do not possess) and there is the Windows Performance Toolkit. But, are there other solutions you can recommend? Preferably (of course) a solution that works without changing the code (manually) and that can be integrated in Visual Studio.</p>
<p>See also <a href="https://stackoverflow.com/questions/49912/best-dotnet-memory-and-performance-profiler">this question</a>. JetBrains dotTrace is the best .NET profiler I have found (and I have tried pretty much every one there is), because it is the only one that has low enough overhead to handle a processor-intensive application. It is also simple, accurate and well-designed - highly recommended!</p>
<p>I like dotTrace3.1 It has worked really well for me.</p>
12,015
<p>In .NET there are two version numbers available when building a project, File Version and Assembly Version. How are you using these numbers? Keeping them the same? Auto-incrementing one, but manually changing the other?</p> <p>Also what about the <code>AssemblyInformationalVersion</code> attribute?</p> <p>I'd found this support Microsoft Knowledge Base (KB) article that provided some help: <a href="http://support.microsoft.com/kb/556041" rel="noreferrer">How to use Assembly Version and Assembly File Version</a>.</p>
<p>In solutions with multiple projects, one thing I've found very helpful is to have all the AssemblyInfo files point to a single project that governs the versioning. So my AssemblyInfos have a line:</p> <pre><code>[assembly: AssemblyVersion(Foo.StaticVersion.Bar)] </code></pre> <p>I have a project with a single file that declares the string:</p> <pre><code>namespace Foo { public static class StaticVersion { public const string Bar= "3.0.216.0"; // 08/01/2008 17:28:35 } } </code></pre> <p>My automated build process then just changes that string by pulling the most recent version from the database and incrementing the second last number.</p> <p>I only change the Major build number when the featureset changes dramatically.</p> <p>I don't change the file version at all.</p>
<p>I keep them the same. But then, I don't have multifile assemblies, which is when the AssemblyVersion number becomes important. I use Microsoft-style date encoding for my build numbers, rather than auto-incrementing (I don't find the number of times that something has been built to be all that important).</p>
3,556
<p>All I'm trying to do is display a separator (I've tried images &amp; stylesheets) <strong>between</strong> the primary navigation menu items in Sharepoint. Here is what I want it to look like:</p> <pre><code>Home | Menu1 | Menu2 | Menu3 </code></pre> <p>When I attempt to use the StaticTopSeparatorImageUrl (using a bar image) it results in the following:</p> <pre><code>Home | Menu1 | Menu2 | Menu3 | </code></pre> <p>This is obviously not a separator, and when I use the StaticBottomSeparatorImageUrl the opposite happens. I also tried to style the ms-topnav class to have a left border, which doesn't work because the control doesn't identify the first (or last) item in the menu...</p> <p>So, my next option was to use the Telerik RadMenu, after fighting to get it into Sharepoint I had difficulties getting it to display like the Sharepoint Menu using the SiteMapDataSource (display only the Home item and no children).</p> <p>This seems SO simple, but it is Sharepoint, so nothing is really simple. I'm wondering if there is either a way to make the default Sharepoint separator work correctly that I might have missed, or is there a GOOD Sharepoint menu replacement that actually takes styling into account?</p>
<p>I prefer to inherit from the MossMenu that the SharePoint team released and customise the menu to producte <em>exactly</em> the html I want.</p> <p><a href="http://blogs.msdn.com/sharepoint/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sharepoint/archive/2006/12/02/customizing-the-wss-3-0-moss-2007-menu-control.aspx</a></p> <p>The instructions for <a href="http://www.thesug.org/blogs/lsuslinky/Lists/Posts/Post.aspx?List=ee6ea231-5770-4c2d-a99c-c7c6e5fec1a7&amp;ID=15&amp;Source=http%3A%2F%2Fwww.thesug.org%2Fblogs%2Flsuslinky%2FLists%2FCategories%2FCategory.aspx%3FName%3DMOSS" rel="nofollow noreferrer">deployment</a> here should help.</p> <ol> <li>Take the Microsoft.SDK.SharePointServer.Samples.dll and put it in the GAC.</li> <li>Edit the web.config file and add in the following SafeControls entry: </li> <li>Copy the MossMenu.js file to \12\TEMPLATE\LAYOUTS</li> <li>Edit your MasterPage with the following: &lt;%@ Register Assembly="Microsoft.SDK.SharePointServer.Samples, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6f07a0c27c74cfa1" Namespace="Microsoft.SDK.SharePointServer.Samples" TagPrefix="Sharepoint" %></li> <li>Change the SharePoint:AspMenu tag with SharePoint:MossMenu. Leave all the config tags the same.</li> </ol>
<p>The actual splitter or separator can be customised by overriding the background image that is set to the top right (no repeating) in the topNavItem in Core.css</p> <p>Just change the image being referenced there.</p>
39,051
<p>[edit] So I used one of the javascript tooltips suggested below. I got the tips to show when you stop and hide if you move. The only problem is it works when I do this:</p> <pre><code>document.onmousemove = (function() { var onmousestop = function() { Tip('Click to search here'); document.getElementById('MyDiv').onmousemove = function() { UnTip(); }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre> <p>But I want the function to only apply to a specific div and if I change the first line to "document.getElementById('MyDiv').onmousemove = (function() {" I get a javascript error document.getElementById('MyDiv') is null What am I missing....??</p> <p>[/edit]</p> <p>I want to display a balloon style message when the users mouse stops on an element from more than say 1.5 seconds. And then if they move the mouse I would like to hide the balloon. I am trying to use some JavaScript code I found posted out in the wild. Here is the code I am using to detect when the mouse has stopped:</p> <pre><code>document.onmousemove = (function() { var onmousestop = function() { //code to show the ballon }; }, thread; return function() { clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre> <p>So I have two questions. One, does anyone have a recommended lightweight javascript balloon that will display at the cursor location. And two, the detect mouse stopped code works ok but I am stumped on how to detect that the mouse has started moving again and hide the balloon. Thanks...</p>
<p>A bit late to be answering this, but this will be helpful for those in need.</p> <p>I needed this function to be able to detect when the mouse stopped moving for a certain time to hide an HTML/JS player controller when hovering over a video. This is the revised code for the tooltip:</p> <pre><code>document.getElementById('MyDiv').onmousemove = (function() { var onmousestop = function() { Tip('Click to search here'); }, thread; return function() { UnTip(); clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre> <p>In my case, I used a bit of jQuery for selecting the elements for my player controller:</p> <pre><code>$('div.video')[0].onmousemove = (function() { var onmousestop = function() { $('div.controls').fadeOut('fast'); }, thread; return function() { $('div.controls').fadeIn('fast'); clearTimeout(thread); thread = setTimeout(onmousestop, 1500); }; })(); </code></pre>
<pre><code>document.onmousemove = (function() { if($('balloon').visible) { //mouse is moving again }....//your code follows </code></pre> <p>Using Prototype.js syntax you can determine that the mouse has moved once the balloon is visible.</p>
21,114
<p>Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="https://stackoverflow.com/a/19799236/8479">https://stackoverflow.com/a/19799236/8479</a></p> <hr> <p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p> <p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p> <p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p> <p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p> <pre><code>rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem Now use the timestamp by in a new ZIP file name. "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code </code></pre> <p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p> <p>I'm using Windows Server 2003 and Windows&nbsp;XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p>
<p>See <em><a href="http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/" rel="noreferrer">Windows Batch File (.bat) to get current date in MMDDYYYY format</a></em>:</p> <pre><code>@echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% </code></pre> <p>If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:</p> <pre><code>For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) </code></pre> <blockquote> <p>C:> .\date.bat <br /> 2008-10-14_0642</p> </blockquote> <p>If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:</p> <pre><code>@echo off for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^&gt;NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] </code></pre> <blockquote> <p>C:>test.cmd<br /> Local date is [2012-06-19 10:23:47.048]</p> </blockquote>
<p>Given a known locality, for reference in functional form. The <code>ECHOTIMESTAMP</code> call shows how to get the timestamp into a variable (<code>DTS</code> in this example.)</p> <pre><code>@ECHO off CALL :ECHOTIMESTAMP GOTO END :TIMESTAMP SETLOCAL EnableDelayedExpansion SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2! SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2! SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0! ENDLOCAL &amp; SET "%~1=%DTS%" GOTO :EOF :ECHOTIMESTAMP SETLOCAL CALL :TIMESTAMP DTS ECHO %DTS% ENDLOCAL GOTO :EOF :END EXIT /b 0 </code></pre> <p>And saved to file, timestamp.bat, here's the output:</p> <p><a href="https://i.stack.imgur.com/zc1ZI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zc1ZI.jpg" alt="enter image description here"></a></p>
24,842
<p>A table row is generated using an asp:Repeater:</p> <pre><code>&lt;asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server"&gt; &lt;itemtemplate&gt; &lt;tr id="announcementRow" class="announcementItem" runat="server"&gt;...&lt;/tr&gt; &lt;/itemtemplate&gt; &lt;/asp:repeater&gt; </code></pre> <p>Now in the data-bind i want to mark "unread" announcements with a different css class, so that the web-guy can perform whatever styling he wants to differentiate between read and unread announcements:</p> <pre><code>protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType != ListItemType.Item &amp;&amp; e.Item.ItemType != ListItemType.AlternatingItem) return; // get the associated data item Announcement announcement = (Announcement)e.Item.DataItem; WebControl row = (WebControl)e.Item.FindControl("announcementRow"); if (row != null) row.CssClass = row.CssClass + " announcementItemUnread"; } </code></pre> <p>except the cast fails at runtime: </p> <pre><code>System.InvalidCastException occurred Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'." </code></pre> <p>It turns out that <code>HtmlTableRow</code> has a different parent heirarchy than <code>WebControl</code>:</p> <pre><code>HtmlTableRow : HtmlContainerControl : HtmlControl : System.Web.UI.Control </code></pre> <p>which is ultimately where WebControl comes from</p> <pre><code>WebControl : System.Web.UI.Control </code></pre> <p>So i changed the code to try to use a System.Web.UI.Control instead:</p> <pre><code>Control row = (Control)e.Item.FindControl("announcementRow"); if (row != null) row.CssClass = row.CssClass + " announcementItemUnread"; </code></pre> <p>But <code>Control</code> doesn't contain a definition for <code>CssClass</code>:</p> <pre><code>'System.Web.UI.Control' does not contain a definition for 'CssClass' </code></pre> <p>so how do i set the css class name for a <code>&lt;TR&gt;</code> element during DataBind?</p>
<pre><code> HtmlControl htmlRow = (HtmlControl)row; htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread"; </code></pre>
<p>Cast it to HtmlTableRow</p> <pre><code>HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("announcementRow"); </code></pre>
22,172
<p>Please share you experiences regarding how you localized your WPF applications to support multiple languages and any resources that helped you in it?</p> <p>Thanks for your feedbacks.</p>
<p>For our WPF application, all of our strings are localized as resources in a <code>ResourceDictionary</code> that we put in a .xaml file named after the language (like en-US.xaml, ja-JP.xaml, etc).</p> <p>For example, somewhere in the application a button might look like this:</p> <pre><code>&lt;Button Content="{StaticResource Strings.FooDialog.BarButtonText}"/&gt; </code></pre> <p>Each <code>ResourceDictionary</code> for the different languages would contain a version of it:</p> <pre><code>&lt;sys:String x:Key="Strings.FooDialog.BarButtonText"&gt;Bar!&lt;/sys:String&gt; </code></pre> <p>The <code>ResourceDictionary</code> is dynamically connected to the <code>Application.Resources</code> at runtime like this:</p> <pre><code>private static void LoadLocalizedStrings(CultureInfo uiCulture) { ResourceDictionary stringsResourceDictionary = new ResourceDictionary(); stringsResourceDictionary.Source = new Uri(@"pack://application:,,,/Resources/Strings/" + uiCulture.Name + ".xaml"); Application.Current.Resources.MergedDictionaries.Add(stringsResourceDictionary); } </code></pre>
<p>Sorry if it is vague (above question),basically it about how you implemented it in your application and what you felt was the best way.It is basically to understand scenarios.</p>
21,411
<p>I am translating SQL Server SQL Statements into their ANSI generic equivalent at present, and am stuck with a recursive statement using a WITH statement.</p> <p>For the sake of concentrating on the issue, I'll simplify the issue as follows</p> <p>If I have two tables</p> <ol> <li><p><strong>ReportingUnit</strong></p> <ul> <li>col1: Key</li> <li>col2: ParentReportingUnitKey</li> </ul></li> <li><p><strong>Facility</strong></p> <ul> <li>col1: Key</li> <li>col2: ParentReportingUnitKey</li> </ul></li> </ol> <p>This structure is describing a hierarchy of reporting units down to a facility, where a reporting unit may have 0 .. 1 direct parent reporting units and 0 .. n child reporting units. </p> <p>A facility is a 'leaf' record, that links to a reporting unit.</p> <p>I need to craft an ANSI 92 valid SQL Statement (or at worst one that will work on Oracle, DB2 and SQL Server) that will return all facilities related to a given reporting unit anywhere up the hierarchy.</p> <p><strong>e.g.</strong></p> <ul> <li>ReportingUnit R1 has ReportingUnit children R1.1 and R1.2 </li> <li>ReportingUnit R1.1 has children R1.1.1, R1.1.2</li> <li><p>ReportingUnit R1.2 has children R1.2.1, R1.2.2</p></li> <li><p>Facility F1 has a parent reporting unit R1.1.1</p></li> <li>Facility F2 has a parent reporting unit R1.1.2</li> <li>Facility F3 has a parent reporting unit R1.2.1</li> <li>Facility F4 has a parent reporting unit R1.2.2</li> </ul> <p>Bearing in mind there are may be 0 .. n levels of recursion in the ReportingUnit table, how can I return all 4 facilities from a SQL Statement given the parameter ReportingUnit=R1?</p>
<p>I'm tolerably certain that no recursive statements were available in SQL-92; the earliest version where that was supported was SQL-99.</p> <p>Consequently, you are stuck with not using SQL-92. Why do you think SQL-92 is desirable? Is it as a base level of SQL functionality, or is there some other reason?</p> <p>Current versions of DB2 have the WITH clause and can achieve recursive queries. I believe Oracle has the WITH clause too; I'm not sure whether it can achieve recursive queries using them. Oracle also has the wholly non-standard and non-relational CONNECT BY PRIOR. I'm not sure what MS SQL Server supports.</p> <p>There is a reasonably strong chance that you will be unable to find a single syntax that is supported by all three of your specified DBMS.</p>
<p>There is no SQL-92 solution for recursive queries.</p> <p>The best option is to use one of the solutions for encoding hierarchical relationships so that you can query all descendants or ancestors, using standard SQL.</p> <p>See a brief description here: "<a href="https://stackoverflow.com/questions/192220/what-is-the-most-efficientelegant-way-to-parse-a-flat-table-into-a-tree#192462">What is the most efficient/elegant way to parse a flat table into a tree?</a>".</p> <p>Or read "<a href="https://rads.stackoverflow.com/amzn/click/com/1558609202" rel="nofollow noreferrer" rel="nofollow noreferrer">Trees and Hierarchies in SQL for Smarties</a>" by Joe Celko.</p>
40,401
<p>I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this?</p> <p>I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly.<br> What I would like is something like py2exe that does it in the script itself.</p>
<p>Check out <a href="https://github.com/pbiggar/phc" rel="nofollow noreferrer">phc: the PHP compiler</a></p> <p>If you just want to run it like a script, you may not need to compile it per se, but just run it via the command line. <a href="http://www.php.net/features.commandline" rel="nofollow noreferrer">Read running PHP via the command line.</a></p>
<p>Have a look at Facebook's <a href="http://github.com/facebook/hiphop-php#readme" rel="nofollow noreferrer">Hiphop-PHP</a>. It's able to convert PHP code into C++ then compile it with g++. Apparently, they've even gotten it to successfully compile entire WordPress installations.</p>
7,065
<p>What is the difference between <a href="https://3dprinting.stackexchange.com/questions/tagged/post-production" class="post-tag" title="show questions tagged &#39;post-production&#39;" rel="tag">post-production</a> and <a href="https://3dprinting.stackexchange.com/questions/tagged/post-processing" class="post-tag" title="show questions tagged &#39;post-processing&#39;" rel="tag">post-processing</a>, or are they synonyms? Should they be merged?<sup>1</sup></p> <p><a href="https://3dprinting.stackexchange.com/questions/tagged/post-production" class="post-tag" title="show questions tagged &#39;post-production&#39;" rel="tag">post-production</a> has no description whatsoever.</p> <p>After looking at <a href="https://meta.stackexchange.com/questions/70710/what-are-tag-synonyms-and-merged-tags-how-do-they-work">What are tag synonyms and merged tags? How do they work?</a>, We can make <a href="https://3dprinting.stackexchange.com/questions/tagged/post-processing" class="post-tag" title="show questions tagged &#39;post-processing&#39;" rel="tag">post-processing</a> the master and <a href="https://3dprinting.stackexchange.com/questions/tagged/post-production" class="post-tag" title="show questions tagged &#39;post-production&#39;" rel="tag">post-production</a> the slave <strong>synonym</strong>. This would seem to be a logical relationship given the number of questions tagged respectively. This relationship can be easily removed, if deemed to be incorrect.</p> <p>If, after some time, everyone is happy with this arrangement, then the two will be <strong>merged</strong>.</p> <p>Does that sound like a plan and does anyone have any objections..?</p> <hr> <p><sup>1</sup> This question was moved from my answer to <a href="https://3dprinting.meta.stackexchange.com/questions/151/naming-convention-for-tags-with-camelcase-or-pre-fix#answer-269">Naming convention for tags with CamelCase or Pre-Fix</a></p>
<p>These are <strong>NOT</strong> the same in a manufacturing, which 3D printing is primarily considered a part of.</p> <p>Post-Processing typically refers to additional steps that must/can be done to produce the nominally desired part. These steps can include deburr, grind, and other additive/subtractive processing on the physical part.</p> <p>Post-Production typically refers to any steps that typically do not "produce" or alter the dimensions of the product. These steps can include final visual and dimensional inspection, packaging, and sometimes even shipment.</p> <p>I would not recommend creating a synonym, but merely updating the definition of both terms.</p>
<p>Post Processing VS Post Production <strong><a href="http://fixthephoto.com/blog/retouch-tips/editing-retouching-post-processing-post-production-difference.html" rel="nofollow noreferrer">These terms are absolute synonyms. At the same time they can be interchangeable.</a></strong></p> <hr> <p>In digital video, photography, television and film, post-production refers to the tasks that must be completed or executed after the filming or shooting ends. This includes tasks such as the editing of raw footage to cut scenes, insert transition effects, working with voice and sound actors, and dubbing, to name a few of the many pre-production tasks. Post-production is the third and final step in film creation. It follows the pre-production and production phases. (<a href="https://www.webopedia.com/TERM/P/post_production.html" rel="nofollow noreferrer">source</a>)</p>
48
<p>How do I add an empty directory (that contains no files) to a Git repository?</p>
<p>Another way to make a directory stay (almost) empty (in the repository) is to create a <code>.gitignore</code> file inside that directory that contains these four lines:</p> <pre><code># Ignore everything in this directory * # Except this file !.gitignore </code></pre> <p>Then you don't have to get the order right the way that you have to do in m104's <a href="https://stackoverflow.com/a/180917/32453">solution</a>.</p> <p>This also gives the benefit that files in that directory won't show up as "untracked" when you do a git status.</p> <p>Making <a href="https://stackoverflow.com/users/554807/greenasjade">@GreenAsJade</a>'s comment persistent:</p> <blockquote> <p>I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later".</p> </blockquote>
<p>Just add a <code>readme</code> or a <code>.gitignore</code> file and then delete it, but not from terminal, from the GitHub website. That will give an empty repository.</p>
14,137
<p>I have set up Synergy on Unix systems with no problems, however when I set up a Synergy server on a Windows Server 2003 box using I get an error message that the mouse cursor is locked when trying to move to the client system. I use a Microsoft Natural keyboard in case that matters (seems Scroll Lock might be involved). Does anyone have experience with using Synergy on Windows systems that have reported mouse screen locking in the log when unable to mouse over to a client system?</p>
<p>Paul: The Scroll-lock key is the "lock the mouse to this screen and don't let it leave" key. you can change it off by adding this in the options section of the ~/.synergy.conf or /etc/synergy.conf</p> <p>keystroke(f12) = lockCursorToScreen(toggle)</p>
<p>I run the Synergy server on my Mac and the client on both a Vista machine and a GNU/Linux (Gentoo) box. On the Vista box I notice that when the screen is locked I am unable to unlock it with the shared (Mac) keyboard. But with Gentoo, this works quite seamlessly. I am not sure what the solution is though and it'd be nice to find one. </p>
29,454
<p>How secure are php Sessions? I am planning to use the native PHP sessions to authenticate users. Can users modify session data like they can $_POST and $_GET data?</p>
<p>Data only goes into a session when you as the developer have the user put it into the session via the code you write. Therefore, sessions are as secure as the data you allow into them, and how you trust and use that data. Further, sessions are based on a sessionID that the client uses to identify the session user. If someone hijacks a sessionID, then they can emulate being the user whose session ID they stole. This can happen in non SSH communication. So don't trust a session ID for identifying a user (for important stuff) unless they have logged in and the sessionID has only been transmitted in secure mode.</p> <p>The next question of security would be the "guessability" of a sessionID you sent off to the user. If you handle the stuff I mention above, by the time you get through it and the documentation you will understand how "guessable" PHP sessionIDs are.</p> <p>Finally watch out for XSS attacks. There are several posts across the internet that explain how to minimize the incidence of XSS.</p>
<p>PHP sessions are as secure as the session cookie given to the user. All the data in the session is stored server-side, so users can't arbitrarily modify them except through whatever functionality your site provides. However, PHP session cookies are a common target for cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks. Just the same, sessions are a good way to do user authentication as long as you're aware of the potential risks.</p> <p>Some Wikipedia links:</p> <p><a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">CSRF</a></p> <p><a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow noreferrer">XSS</a></p>
27,076
<p>I maintain an application which, during the course of two years, has constantly required new hardware to be even usable, due to the amount of new users / new data inserted. However, justifying the investiment is sometimes very hard to do.</p> <p>I started to wonder - how can I establish the maximum number of users a web application currently suports? </p> <p>I thought of using JMeter scripts but they can get really nasty to implement when having to simulate file transfers and decison trees. What do you guys use?</p>
<p>You can use this performance algorithm:</p> <p><a href="http://i.msdn.microsoft.com/cc500561.fig02_L(en-us).gif" rel="nofollow noreferrer">http://i.msdn.microsoft.com/cc500561.fig02_L(en-us).gif</a></p> <blockquote> <p><strong>R</strong> Response time. The total time from the user requesting a page (by clicking a link, and so on) to when the full page is rendered on the user's computer. Typically measured in seconds. Payload Total bytes sent to the browser, including markup and all resources (such as CSS, JS, and image files).</p> <p><strong>Bandwidth</strong> Rate of transfer to and from the browser. This may be asymmetrical and might represent multiple speeds if a given page is generated from multiple sources. Usually, it is averaged together to create a single bandwidth expressed in bytes per second.</p> <p><strong>AppTurns</strong> The number of resource files a given page needs. These resource files will include CSS, JS, images, and any other files retrieved by the browser in the process of rendering the page. In the equation, the HTML page is accounted for separately by adding in round-trip time (RTT) before the AppTurns expression.</p> <p><strong>RTT</strong> The time it takes to round-trip, regardless of bytes transferred. Every request pays a minimum of one RTT for the page itself. Typically measured in milliseconds.</p> <p><strong>Concurrent Requests</strong> Number of simultaneous requests a browser will make for resource files. By default, Internet Explorer performs two concurrent requests. This setting can be adjusted but rarely is.</p> <p><strong>Cs</strong> Compute time on the server. This is the time it takes for code to run, retrieve data from the database, and compose the response to be sent to the browser. Measured in milliseconds.</p> <p><strong>Cc</strong> Compute time on the client. This is the time it takes for a browser to actually render the HTML on the screen, execute JavaScript, implement CSS rules, and so on.</p> </blockquote> <p>For more details:</p> <p><a href="http://msdn.microsoft.com/en-us/magazine/cc500561.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc500561.aspx</a></p>
<p>We use HP's <a href="http://en.wikipedia.org/wiki/LoadRunner" rel="nofollow noreferrer">LoadRunner</a>. But it's not cheap, and you still have to create scripts, test cases.</p>
22,362
<p>Is it possible to assign a global hotkey to a specific feature in an Adobe AIR app, i.e. the app feature responds to the hotkey whether the app is active or not (it must be running of course, but only in the system tray).</p>
<p>I don't this it's possible with Adobe AIR itself. The only method I can think of:</p> <ol> <li>Install 3rd party hotkey application (like <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotkey</a> or <a href="http://sourceforge.net/projects/hotkeybind/" rel="nofollow noreferrer">HotKeyBind</a>)</li> <li>Configure hotkey application to make <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>Q</kbd> to launch &quot;<code>c:\programs\thvo42\coolapp.exe --hotkey q</code>&quot;</li> <li>In your AIR application, register for the <a href="http://livedocs.adobe.com/labs/air/1/aslr/flash/desktop/NativeApplication.html#event:invoke" rel="nofollow noreferrer">NativeApplication.invoke</a> event, and watch for arguments like '--hotkey q' to know that the Q hotkey was pressed, and then act accordingly.</li> </ol> <p>Of course, this is kind of a hassle, maybe with some hacking you can roll it all into a single install file.</p>
<p>SWFKit creates a wrapper around your flash/flex movie, and allows access to system DLLs and other goodies, but unfortunately it would export as an .exe, so windows only and no AIR.</p> <p>ASFAIK, there is no support for it by using AIR alone.</p>
18,541
<p><code>mkdir("/people/jason", 0700, TRUE);</code></p> <p>TRUE = Recursive in PHP 5 and the server is running 5.2.5 but I get:</p> <pre><code>Warning: mkdir() expects at most 2 parameters, 3 given in /home/net1003/public_html/admin/_createPage.inc on line 5 </code></pre>
<p>are you running this particular script through the command line interface instead? it's possible that version of PHP 4, whereas the mod_php version is 5.</p>
<p>That is all of my code.</p> <p>I want to create a directory on the web server after a user is added to the MySQL database. Each user gets their own directory with a default index.php page and I am trying to do this programatically rather than manually. </p>
26,721
<p>Is there a standard when it comes to implementing keyboard shortcuts / accelerator keys for web applications. Example: Navigating through a list of items presented in a grid Are their guidelines on how to implement this? Google has one for GMail in the "labs" section. </p> <p>Also would it make business sense in investing time for implementing keyboard shortcuts / accelerator keys in web apps</p>
<p>I have used a number of web sites and web applications that define their own keyboard shortcuts. They are usually poorly documented and offer little value over conventional mouse-based use.</p> <p>As Galwegian mentions, you should be careful of interfering with accessibility options, especially if you want to comply with <a href="http://webdesign.about.com/od/accessibility/Web_Accessibility_Web_Usability.htm" rel="nofollow noreferrer">ADA Guidelines for the Web</a>.</p> <p>You should also test your web app with respect to keyboard shortcuts in popular web browsers. Some people use these, and get annoyed when your web app overrides the browser's keys.</p> <p>I think it would be more worth your time to test <strong>tab order</strong> for web forms and other page elements. When I fill out web forms, I tend to use tab to advance to the next form field, but I find some web sites in which a tab jumps to some unexpected place on the page instead of to the visually adjacent element.</p>
<p>From an accessibility point of view, keyboard shorts are dangerous as they may interfere with the pre-programmed shortcuts of software like screen readers used by visually impaired users.</p> <p>For this reason, I either avoid their use, or ensure that you can turn off this feature.</p> <p>Good luck!</p>
38,421
<p>How do you trigger a javascript function using actionscript in flash?</p> <p>The goal is to trigger jQuery functionality from a flash movie</p>
<p>Take a look at the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html" rel="noreferrer">ExternalInterface</a>-Class. <br> From the AS3-Language Reference:</p> <blockquote> <p>The ExternalInterface class is the External API, an application programming interface that enables straightforward communication between ActionScript and the Flash Player container– for example, an HTML page with JavaScript. Adobe recommends using ExternalInterface for all JavaScript-ActionScript communication.</p> </blockquote> <p>And it's work like this:</p> <pre><code>ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript); ExternalInterface.call("sendToJavaScript", input.text); </code></pre> <p>You can submit parameters and recieve callbacks...pretty cool, right? ;)</p> <p>As I know it will also work on AS2...</p>
<p>As Jochen said ExternalInterface is the way to go and I can confirm that it works with AS2.</p> <p>If you plan to trigger navigation or anything that affects the area where the flash sits don't do it directly from the function you call from flash. Flash expects a return value from the function it calls and if the flash object does not exist when the function is completed the flash plugin will crash. </p> <p>If you need to do navigation or alter the content you can add a setTimeout call (into your js function). That will create a new thread and give flash the return value it expects.</p>
20,972
<p>I have the following autorun.inf</p> <pre><code>[Autorun] action="Blah, Inc." open=marketing.exe icon=blah.ico label="Blah, Inc." </code></pre> <p>On Vista, the autorun dialog shows "Publisher not specified". How do I specify a publisher?</p>
<p>Bogdan is right: You need to sign your executable. You can use <em>SignTool</em> from Microsoft for this. Taken from the <a href="http://msdn.microsoft.com/en-us/library/aa387764.aspx" rel="nofollow noreferrer">MSDN</a>:</p> <blockquote> <p><em>SignTool tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files. (...) The tool is installed in the \Bin folder of the Microsoft Windows Software Development Kit (SDK) installation path. SignTool is available as part of the Windows SDK, which you can download as part of the Windows SDK for Windows Server 2008 and .NET Framework 3.5.</em></p> </blockquote>
<p>You specify the publisher by signing your executable file, not by writing it in the autorun.inf file.</p> <p>How to do it...beats me, I'm a Java developer. Maybe someone else can tell you how.</p>
33,825
<p>How can i stop the host machine entering <code>standby</code> mode while my application is running?</p> <p>Is there any <code>win32 api</code> call to do this?</p>
<p>There are two APIs, depending on what version of Windows.</p> <p>XP,2000, 2003:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx</a></p> <p>Respond to PBT_APMQUERYSUSPEND.</p> <p>Vista, 2008:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx</a></p> <p>There could be many valid reasons to prevent the computer from going to sleep. For example, watching a video, playing music, compiling a long running build, downloading large files, etc. </p>
<p>This article <a href="http://www.codeguru.com/cpp/w-p/system/messagehandling/article.php/c6907" rel="nofollow noreferrer">http://www.codeguru.com/cpp/w-p/system/messagehandling/article.php/c6907</a> provides a demo of how to do this from C++ (thought he article is framed as if you want to do it from Java, and provides a Java wrapper).</p> <p>The actual code in in a zip file at <a href="http://www.codeguru.com/dbfiles/get_file/standbydetectdemo_src.zip?id=6907&amp;lbl=STANDBYDETECTDEMO_SRC_ZIP&amp;ds=20040406" rel="nofollow noreferrer">http://www.codeguru.com/dbfiles/get_file/standbydetectdemo_src.zip?id=6907&amp;lbl=STANDBYDETECTDEMO_SRC_ZIP&amp;ds=20040406</a> and the C++ part of it is under com/ha/common/windows/standbydetector.</p> <p>Hopefully it will give you enough of a direction to get started.</p>
7,992
<p>We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details.</p> <p>Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?</p>
<p>Within your overridden ProcessCmdKey how are you determining which key has been pressed?</p> <p>The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181.</p> <p>You can extract the modifiers and the key pressed by ANDing with appropriate enum values:</p> <pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData &amp; Keys.Shift) != 0; Keys unmodifiedKey = (keyData &amp; Keys.KeyCode); // rest of code goes here } </code></pre>
<p>I upvoted <a href="https://stackoverflow.com/questions/4850/c-and-arrow-keys/5026#5026">Tokabi's answer</a>, but for comparing keys there is some additional advice on <a href="https://stackoverflow.com/questions/1369312/c-keys-enumeration-confused-keys-alt-or-keys-rbutton-keys-shiftkey-keys-alt/2033796#2033796">StackOverflow.com here</a>. Here are some functions which I used to help simplify everything.</p> <pre><code> public Keys UnmodifiedKey(Keys key) { return key &amp; Keys.KeyCode; } public bool KeyPressed(Keys key, Keys test) { return UnmodifiedKey(key) == test; } public bool ModifierKeyPressed(Keys key, Keys test) { return (key &amp; test) == test; } public bool ControlPressed(Keys key) { return ModifierKeyPressed(key, Keys.Control); } public bool AltPressed(Keys key) { return ModifierKeyPressed(key, Keys.Alt); } public bool ShiftPressed(Keys key) { return ModifierKeyPressed(key, Keys.Shift); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (KeyPressed(keyData, Keys.Left) &amp;&amp; AltPressed(keyData)) { int n = code.Text.IndexOfPrev('&lt;', code.SelectionStart); if (n &lt; 0) return false; if (ShiftPressed(keyData)) { code.ExpandSelectionLeftTo(n); } else { code.SelectionStart = n; code.SelectionLength = 0; } return true; } else if (KeyPressed(keyData, Keys.Right) &amp;&amp; AltPressed(keyData)) { if (ShiftPressed(keyData)) { int n = code.Text.IndexOf('&gt;', code.SelectionEnd() + 1); if (n &lt; 0) return false; code.ExpandSelectionRightTo(n + 1); } else { int n = code.Text.IndexOf('&lt;', code.SelectionStart + 1); if (n &lt; 0) return false; code.SelectionStart = n; code.SelectionLength = 0; } return true; } return base.ProcessCmdKey(ref msg, keyData); } </code></pre>
2,684
<p>On occasion, my local Rails app loses its connection to MySQL. I get some error that the connection failed, but if I just refresh the page, it works fine. This has never happpened in my STAGE or PROD environments (I deploy to Ubuntu), so it has not been that big a deal.<br> Does this happen to anybody else? Is there something I can do to fix it? Is it MySQL or Ruby?</p>
<p>Look like the best solution to this is to install the platform specific mysql driver. <br><code>sudo gem install mysql</code></p>
<p>Look like the best solution to this is to install the platform specific mysql driver. <br><code>sudo gem install mysql</code></p>
24,003
<p>I am trying to reach methods and properties of ObjectFrame through vb.net. But when I declared this as </p> <pre><code>Dim objOLEObject As ObjectFrame </code></pre> <p>and then trying to instantiate it as </p> <pre><code>ObjOLEObject = New ObjectFrame </code></pre> <p>it shows error like:</p> <p>"<strong>429: Retriveing the COM class factory for component with CLSID {3806e95d-e47c-11-cd-8701-00aa003f0f7} failed due to the following error: 80040154</strong>"</p> <p>To resolve this we re-installed both MS-Office 2003 and VS-2005, but could not get the solution.</p> <p>Could anyone suggest me how to declare and use this in vb.net?</p> <p>Thanks.</p>
<p>Make sure the dll has been registered using regsvr32. Verify by looking in the registry for the CLSID.</p> <p>Make sure all dependant dll's are available.</p> <p>I believe this is a class not registered error.</p>
<p>Adding to what Josh is saying, have you checked that all the dependency files are present?</p> <p>This thread might help.<br> <a href="http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/88a6ea68-f476-4231-822f-27fabe59f458/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/88a6ea68-f476-4231-822f-27fabe59f458/</a></p>
47,241
<p>I'm attempting to display a "LargeIcon" view in a listview control, however the images I specify are blurry. This is what I have so far: <a href="http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg" rel="nofollow noreferrer">alt text http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg</a></p> <p>The .png files are 48x48 and that's what I have it set to display at in the ImageList properties. There's one thing that I've noticed (which is probably the cause) but I don't know how to change it. Inside the "Images Collection Editor" where you choose what images you want for the ImageList control, it looks like it's setting the wrong size for each image. <a href="http://img83.imageshack.us/img83/5218/imagepropertiesmf9.jpg" rel="nofollow noreferrer">alt text http://img83.imageshack.us/img83/5218/imagepropertiesmf9.jpg</a></p> <p>As you can see the "PhysicalDimension" and the "Size" is set to 16x16 and not abled to be manipulated. Does anyone have any ideas? Many thanks!</p>
<p>When adding a .PNG Icon format size the editor tends to pick the first entry size in that file, so it picks up the 16x16 entry and it's stretching that out. That's why you see the 16x16 in the properties there. As suggested, the support for PNG is poor, I'm often found myself rolling over to another format as well to avoid this.</p> <p>You can open the file in <strong><a href="http://www.getpaint.net/" rel="nofollow noreferrer">Paint.Net</a></strong> if you need a free editor or something more fully featured like Photoshop or Fireworks and extract the exact size you want.</p>
<p>Be sure to set the ImageList size to 48x48 px <strong>BEFORE</strong> you add the images. </p> <p>If the ImageList is set to 32x32 and you add a 48x48 image, the icon is resized to 32x32. When you change the ImageList to 48x48 afterwards, the image is just resized again, thus losing quality and going blurry.</p> <p>Also, Paint.NET (or Photoshop) can't open .ico files.</p> <p>Visual Studio/.NET can handle 32-bit PNG images fine, the built-in image editor in VS is a bit lack-lustre though.</p>
13,674
<p>I have an ASP.NET 2.0 application that is working fine in our local environment. When published to a test server, we're getting intermittent errors on the server.</p> <p>Here's the most common:</p> <p>Padding is invalid and cannot be removed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <blockquote> <p>Exception Details: System.Security.Cryptography.CryptographicException: <strong>Padding is invalid and cannot be removed.</strong></p> <p>Source Error:</p> <p>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</p> <p>Stack Trace:</p> <p>[CryptographicException: Padding is invalid and cannot be removed.]<br> System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]&amp; outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) +1545747<br> System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) +257<br> System.Security.Cryptography.CryptoStream.FlushFinalBlock() +30 System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo) +164<br> System.Web.UI.Page.DecryptString(String s) +83<br> System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +148<br> System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +358 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +64</p> </blockquote> <p>This happens on a request to a specific WebResource.axd request.</p> <p>The other error that we're seeing is this:</p> <blockquote> <p><strong>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.</strong> Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <p>Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.</p> </blockquote> <p>This error happens occasionally while posting a form.</p> <p>Now before you jump in and tell me the obvious (usual) answer to this error, consider this:</p> <ul> <li>The application is deployed to Windows Server 2003 on IIS6</li> <li>It is NOT on a web farm. Only one webserver is in use here.</li> <li>The application pool identity is a custom service account, and I did run <code>aspnet_regiss -ga &lt;username&gt;</code> on the server. No effect.</li> </ul>
<p>The error is because your appdomain was recycled/restarted. When that happens the application and the machine key is set to auto, it changes. That affects the decryption of the info in the url of the resources urls (.axd). Setting up a fixed machine key will prevent it from ever happening again.</p> <p>Please check this for more info on a similar case (the explanation is with an issue with viewstate validation, but the cause is the same one): <a href="http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx" rel="nofollow noreferrer">http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx</a></p> <p>I also had been wondering about it for quite a while. After I saw this question it got me on it again: <a href="https://stackoverflow.com/questions/617782/is-this-an-attempt-to-break-my-asp-net-sites-security/617940#617940">Is this an attempt to break my ASP.Net site&#39;s security?</a> ... which I just answered with very much the same. I had the feeling it was around some restart of something, because when we published something that recycled the application the error showed in the log, but I didn't have any other source stating its relation (today I found that case on invalidviewstate because of the machinekey change :))</p> <p>Ps. above finally explains it on single server :)</p>
<p>Ben,</p> <p>For your first problem, I found this that seems to be a bit more to the point of what you are seeing in that the problem is sporadically occurring. You should be able to find a full explanation of this at <a href="http://www.codeproject.com/KB/security/Cryptor.aspx#aes" rel="nofollow noreferrer">http://www.codeproject.com/KB/security/Cryptor.aspx#aes</a>.</p> <p>What you really need to do is set RijndaelAlg.Padding to PaddingMode.ISO10126, PaddingMode.PKCS7, or PaddingMode.ANSIX923. Any one of these 3 values should work, provided that you use the same value when encrypting and decrypting. Other values will work with some data, but not with all data. The above URL explains why.</p> <p>What I don't understand is the reason Microsoft provides options that sometimes don't work, or at least why they don't default to a reliable option.</p>
39,923
<p>I have two running processes in Windows, and each process has a pipe to the other.</p> <p>I want to serialize a complicated class and transmit it from one process to the other. I already have the serialization procedure worked out, and I understand that the pipes are sending binary streams. How should I go about sending my serialized data? I'm using WinAPI and C++.</p> <p>Should I develop a custom protocol? If so, should it be generic or unique to this particular class? Can I preserve virtual tables when sending the serialized class?</p> <p>Are there any models or design patterns that are commonly used in this case? A little bit of sample code would be greatly appreciated. Thank you!</p>
<p>Here is the tutorial for <code>boost::serialization</code>. I could imagine it would work fine sending the data over the pipe and deserializing on the other side: <a href="http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/tutorial.html" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/tutorial.html</a></p>
<p>You can use boost::asio::windows::stream_handle to organize iostream like io, and do it asynchronously.</p>
45,280
<p>As the title says, how can I find the current operating system in python?</p>
<p>I usually use <a href="https://docs.python.org/3/library/sys.html#sys.platform" rel="noreferrer"><code>sys.platform</code></a> to get the platform. <code>sys.platform</code> will distinguish between linux, other unixes, and OS X, while <code>os.name</code> is &quot;<code>posix</code>&quot; for all of them.</p> <p>For much more detailed information, use the <a href="https://docs.python.org/3/library/platform.html#module-platform" rel="noreferrer">platform module</a>. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.</p>
<p><a href="https://docs.python.org/library/os.html" rel="noreferrer">https://docs.python.org/library/os.html</a></p> <p>To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.</p>
13,562
<p>Can anyone please help me to get all the domains in Active Directory. I have tried many times, but all the programs are listing only the current working domain. </p> <p>How can I do this?</p>
<pre><code>Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, "yourDomain", "username", "password")); Forest forest = domain.Forest; DomainCollection domains = forest.Domains; </code></pre> <p>The above uses the System.DirectoryServices.ActiveDirectory namespace. It'll give you a domain collection containing all the domains that are in the same forest as your given domain.</p>
<p>You could also use System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest().Domains</p> <pre><code>var domains = Forest.GetCurrentForest().Domains.Cast&lt;Domain&gt;(); foreach (var domain in domains) { Console.WriteLine(domain.Name); } </code></pre>
41,898
<pre><code>DECLARE @p_date DATETIME SET @p_date = CONVERT( DATETIME, '14 AUG 2008 10:45:30',?) SELECT * FROM table1 WHERE column_datetime = @p_date </code></pre> <p>I need to compare date time like:</p> <pre><code>@p_date=14 AUG 2008 10:45:30 column_datetime=14 AUG 2008 10:45:30 </code></pre> <p>How can I do this?</p>
<p>The question is unclear, but it looks like you are trying to do the equality match that isn't returning the rows you expect, so I'm guessing that the problem is that the milliseconds are being problematic. There are several approaches here:</p> <ol> <li>format both values (as varchar etc) using CONVERT : expensive for CPU, can't use index </li> <li>use DATEDIFF/DATEPART to do the math - similar, but not <em>quite</em> as expensive</li> <li>create a range to search between</li> </ol> <p>The 3rd option is almost always the most efficient, since it can make good use of indexing, and doesn't require masses of CPU.</p> <p>For example, in the above, since your precision is seconds*, I would use:</p> <pre><code>DECLARE @end datetime SET @end = DATEADD(ss,1,@p_date) </code></pre> <p>then add a WHERE of the form:</p> <pre><code>WHERE column_datetime &gt;= @p_date AND column_datetime &lt; @end </code></pre> <p>This will work best if you have a clustered index on column_datetime, but should still work OK if you have a non-clustered index on column_datetime.</p> <p>[*=if @p_date includes milliseconds you'd need to think more about whether to trim those ms via <code>DATEADD</code>, or do a smaller range, etc]</p>
<p>I don't quite understand your problem, but <a href="http://msdn.microsoft.com/en-us/library/ms189794.aspx" rel="nofollow noreferrer">DateDiff</a> can be used to compare dates.</p>
34,757
<p>Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.</p> <p>A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?</p> <pre><code>routes.MapRoute("UserItems", "User/{UserID}/Items", new {controller = "User", action = "Items"}); </code></pre> <p>And on my aspx page</p> <pre><code>Html.ActionLink("Items", "UserItems", new { UserID = 1 }) </code></pre>
<p>Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:</p> <pre><code>public string ActionLink(string linkText, string actionName, object values); </code></pre> <p>Note how the second parameter is the <em>actionName</em> not the <em>routeName</em>.</p> <p>As such, try:</p> <pre><code>Html.ActionLink("Items", "Items", new { UserID = 1 }) </code></pre> <p>Alternatively, try:</p> <pre><code>&lt;a href="&lt;%=Url.RouteUrl("UserItems", new { UserId = 1 })%&gt;"&gt;Items&lt;/a&gt; </code></pre>
<p>Firstly start with looking at what URL it generates and checking it with <a href="http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx" rel="nofollow noreferrer">Phil Haack</a>'s route debug library. It will clear lots of things up.</p> <p>If you're having a bunch of routes you might want to consider naming your routes and using named routing. It will make your intent more clear when you re-visit your code and it can potentially improve parsing speed.</p> <p>Furthermore (and this is purely a personal opinion) I like to generate my links somewhere at the start of the page in strings and then put those strings in my HTML. It's a tiny overhead but makes the code much more readable in my opinion. Furthermore if you have or repeated links, you have to generate them only once.</p> <p>I prefer to put</p> <pre><code>&lt;% string action = Url.RouteUrl("NamedRoute", new { controller="User", action="Items", UserID=1});%&gt; </code></pre> <p>and later on write</p> <pre><code>&lt;a href="&lt;%=action%&gt;"&gt;link&lt;/a&gt; </code></pre>
14,465
<p>Can anybody recommend a good method for determining the Rect of some wrapped text on an iPhone? I've tried all the built-in methods for NSString in the 2.1 SDK to no avail. The size methods never return sizes that allow me to completely fit wrapped text in my custom view.</p> <p>I'm drawing some user customizable text that should always be as big as possible within the limits of my custom view. If I can determine the rect needed to completely enclose wrapped text for a given max width and font size, I can raise or lower the font size until the text is just big enough to completely fill the custom view without being clipped.</p> <p>Any help is much appreciated!</p>
<p>NSString's sizeWithFont:constrainedToSize: method might be useful:</p> <pre><code>CGSize sizeForText = [theText sizeWithFont:theFont constrainedToSize:CGSizeMake(myMaxWidth, 9999)]; </code></pre> <p>You say you've tried all the size methods, but based on your description, it sounds like what you're looking for.</p>
<p>Since you know your view size, call NSString's sizeWithFont:forWidth:lineBreakMode:, starting with your minimum font size, the width of your view, and UILineBreakModeWordWrap. Then increase the font size until the returned size is as tall as your view.</p> <p>If you want to set a maximum font size, you could also implement this as a binary search, rather than stepping up the font size.</p>
21,678
<p>I'm generating compiled getter methods at runtime for a given member. Right now, my code just assumes that the result of the getter method is a string (worked good for testing). However, I'd like to make this work with a custom converter class I've written, see below, "ConverterBase" reference that I've added.</p> <p>I can't figure out how to add the call to the converter class to my expression tree.</p> <pre><code> public Func&lt;U, string&gt; GetGetter&lt;U&gt;(MemberInfo info) { Type t = null; if (info is PropertyInfo) { t = ((PropertyInfo)info).PropertyType; } else if (info is FieldInfo) { t = ((FieldInfo)info).FieldType; } else { throw new Exception("Unknown member type"); } //TODO, replace with ability to specify in custom attribute ConverterBase typeConverter = new ConverterBase(); ParameterExpression target = Expression.Parameter(typeof(U), "target"); MemberExpression memberAccess = Expression.MakeMemberAccess(target, info); //TODO here, make the expression call "typeConverter.FieldToString(fieldValue)" LambdaExpression getter = Expression.Lambda(memberAccess, target); return (Func&lt;U, string&gt;)getter.Compile(); } </code></pre> <p>I'm looking for what to put in the second TODO area (I can handle the first :)).</p> <p>The resulting compiled lambda should take an instance of type U as a param, call the specified member access function, then call the converter's "FieldToString" method with the result, and return the resulting string.</p>
<p>Can you illustrate what (if it was regular C#) you want the expression to evaluate? I can write the expression easily enough - I just don't fully understand the question...</p> <p>(edit re comment) - in that case, it'll be something like:</p> <pre><code> ConverterBase typeConverter = new ConverterBase(); var target = Expression.Parameter(typeof(U), "target"); var getter = Expression.MakeMemberAccess(target, info); var converter = Expression.Constant(typeConverter, typeof(ConverterBase)); return Expression.Lambda&lt;Func&lt;U, string&gt;&gt;( Expression.Call(converter, typeof(ConverterBase).GetMethod("FieldToString"), getter), target).Compile(); </code></pre> <p>Or if the type refuses to bind, you'll need to inject a cast/convert:</p> <pre><code> MethodInfo method = typeof(ConverterBase).GetMethod("FieldToString"); return Expression.Lambda&lt;Func&lt;U, string&gt;&gt;( Expression.Call(converter, method, Expression.Convert(getter, method.GetParameters().Single().ParameterType)), target).Compile(); </code></pre>
<p>You need to wrap the object in an ExpressionConstant, e.g. by using Expression.Constant. Here's an example:</p> <pre><code>class MyConverter { public string MyToString(int x) { return x.ToString(); } } static void Main() { MyConverter c = new MyConverter(); ParameterExpression p = Expression.Parameter(typeof(int), "p"); LambdaExpression intToStr = Expression.Lambda( Expression.Call( Expression.Constant(c), c.GetType().GetMethod("MyToString"), p), p); Func&lt;int,string&gt; f = (Func&lt;int,string&gt;) intToStr.Compile(); Console.WriteLine(f(42)); Console.ReadLine(); } </code></pre>
41,461
<p>I have the following two files and would like the second to extend the first:</p> <ol> <li>wwwroot\site\application.cfc</li> <li>wwwroot\site\dir\application.cfc</li> </ol> <p>However, when I go to declare the component for the second file, I'm not sure what to put in the extends attribute. <strong>My problem is that several dev sites (with a shared SVN repository) are running off the same instance of ColdFusion</strong>, so I can't just create a mapping in the CF admin like so:</p> <pre><code>&lt;cfcomponent extends="site.application"&gt; </code></pre> <p>However, ColdFusion doesn't like:</p> <pre><code>&lt;cfcomponent extends="..application"&gt; </code></pre> <p>or any dynamic input like:</p> <pre><code>&lt;cfcomponent extends="#expandpath('..').#application"&gt; </code></pre> <p>Creating a runtime mapping (<a href="https://stackoverflow.com/questions/287187/extend-a-cfc-using-a-relative-path">like here</a>) doesn't seem possible either. Creating it in the base application.cfc is useless because that code hasn't yet executed by the time the inheriting cfc is being declared; and I can't create the mapping before the inheriting component is defined because there isn't yet an application to attach it to.</p> <p>Is there any way I can reference the parent directory to accomplish my extends?</p> <p>Edit to clarify: The ApplicationProxy solution doesn't work because of the bolded text above. Right now, as a workaround, we're simply not checking the \dir\application.cfc into SVN so that each developer can keep a version that extends his/her own root application.cfc. Obviously, this is not ideal.</p>
<p>Sean Corfield has <a href="http://corfield.org/blog/index.cfm/do/blog.entry/entry/Extending_Your_Root_Applicationcfc" rel="noreferrer">a blog entry explaining how to extend a root Application.cfc</a>.</p> <p>Below is the relevant information copied from that entry.</p> <hr> <p>Here's your root CFC /Application.cfc:</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset this.name = "cf7app" /&gt; &lt;cfset this.sessionmanagement = true /&gt; &lt;/cfcomponent&gt; </code></pre> <p>Here's your proxy CFC /ApplicationProxy.cfc:</p> <pre><code>&lt;cfcomponent extends="Application"&gt; &lt;/cfcomponent&gt; </code></pre> <p>It's completely empty and serves merely to create an alias for your root /Application.cfc. Here's your subdirectory CFC /app/Application.cfc:</p> <pre><code>&lt;cfcomponent extends="ApplicationProxy"&gt; &lt;cffunction name="onSessionStart"&gt; &lt;cfoutput&gt;&lt;p&gt;app.Application.onSessionStart()&lt;/p&gt;&lt;/cfoutput&gt; &lt;cfset session.counter = 0 /&gt; &lt;/cffunction&gt; &lt;cffunction name="onRequestStart"&gt; &lt;cfoutput&gt;&lt;p&gt;app.Application.onRequestStart()&lt;/p&gt;&lt;/cfoutput&gt; &lt;cfdump label="application" var="#application#"/&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <hr> <p>The root of <em>each</em> individual site should have its own Master App:</p> <pre><code>/site1/Application.cfc /site2/Application.cfc /site3/Application.cfc </code></pre> <p>All these applications are separate individual apps with nothing shared between them.</p> <p>If any of these individual sites need to have sub-applications, then there should be ApplicationProxy.cfc alonside the Master,</p> <pre><code>e.g. /site1/ApplicationProxy.cfc /site2/ApplicationProxy.cfc </code></pre> <p>Then, for each sub-application you have the one that extends the proxy:</p> <pre><code>e.g. /site1/subA/Application.cfc /site1/subB/Application.cfc /site2/subA/Application.cfc </code></pre>
<p>Edward, et-al, I referred to your comment in the post below. See <a href="https://gregoryalexander.com/blog/2021/1/30/Extending-Applicationcfcs-using-mappings-and-proxies" rel="nofollow noreferrer">https://gregoryalexander.com/blog/2021/1/30/Extending-Applicationcfcs-using-mappings-and-proxies</a></p> <p>You absolutely can extend a cfc with mappings. I had to do it myself.</p> <p>One of the most frustrating things that I have had to deal with in ColdFusion is trying to create an external application that is open to the general public and having to secure a portion of that site with an application within a subfolder and extending the logic from base application.cfc. I'll walk you through the current approach that developers use to solve this as well as showing you how to additionally use mapping when there may be a hosting provider that uses virtual directories.</p> <p>This is a rather long article, if you want to jump to the condensed summary, scroll down to the bottom of this page.</p> <p>Many years ago, the first time that I tried to perform this, I received the following message no matter what I tried: &quot;Could not find the ColdFusion component or interface xxx'. In a nutshell, the problem using this approach is that both the root and the subfolders have the same name, i.e. Application.cfc, and ColdFusion can't properly identify what component to extend. Finally, after some serious investigation, someone came up with the idea to create a proxy.cfc that resides in the same root directory as the root Application.cfc, and the Application.cfc in the subfolder extends an empty proxy.cfc that extends the root cfc like so:</p> <p>root directory: Application.cfc This root Application.cfc does not extend anything</p> <p>Also in the root directory: Proxy.cfc Proxy.cfc has the following code, it's essentially empty. The only thing that the Proxy.cfc does is to extend the Application.cfc that is in the same directory:</p> <p>Subdirectory such as a folder named admin. This subdirectory has another Application.cfc. Let's say that this component is responsible for securing the application and has login logic as well as debugging settings for example. This Application.cfc will extend the Proxy.cfc to gain the methods and properties of the Application.cfc in the root directory like so:</p> <p>This approach was a godsend and it was heavily blogged about. Ben Nadel has made a number of very helpful posts which I will share at the bottom of this article.</p> <p>This works quite well unless you're on a hosted domain or a server that uses virtual directories. In this case, we are in the same original boat in which we started from. Now we are back into the &quot;Could not find the ColdFusion component or interface xxx' hell!</p> <p>There is a solution for this tricky problem though, we need to also use mapping!</p> <p>It is a common misnomer that you can't use mapping to extend components. I am not quite sure where this misconception originally came about, but it has been proven that this is just not true. There are occasions where we must use mapping to solve some annoying problems, like here.</p> <p>This particular site is hosted by hostek.com. They are a fine company to deal with, but the server that my site is hosted on has some idiosyncrasies due to the directory structure. Here, when I use the Proxy.cfc method to extend the logic from the base Application.cfc to the Application.cfc in the admin folder I receive the dreaded 'could not find the ... component' error. When I first saw it I was dismayed thinking not this again, so I turned to ColdFusion CFC mapping. Mapping tells ColdFusion where to find the file and what the file relationships are.</p> <p>Let's review CFC structure that was just discussed. For example, imagine the following directory structure:</p> <p>root directory: i.e. <a href="http://www.gregoryalexander.com/" rel="nofollow noreferrer">www.gregoryalexander.com/</a> subdirectory: <a href="http://www.gregoryalexander.com/admin/" rel="nofollow noreferrer">www.gregoryalexander.com/admin/</a></p> <p>As discussed, we have an Application.cfc and the Proxy.cfc in the root directory, and we have the Application.cfc in the 'admin' subdirectory. The Proxy.cfc extends the Application.cfc, also in the root directory, and the Application.cfc in the subdirectory (admin) extends the Proxy.cfc in the root directory.</p> <p>root directory: contains both Application.cfc and Proxy.cfc (that extends the root Application.cfc). subdirectory: Application.cfc (that extends Proxy.cfc).</p> <p>Now we need to also add the following mapping in the root Application.cfc. This mapping logic should be near the top of the root Application.cfc, and it should not be within any of the Application.cfc event handlers (onApplicationStart, onApplicationRequest, etc). This mapping code does not need to be anywhere else other than the root Application.cfc:</p> <p>I used rootCfc to identify the Application.cfc in the root directory, whereas adminCfc applies to the Application in the admin directory. These variables can be named anything. Note that the &quot;/admin&quot; string at the end of the adminCfc mapping points to the 'admin' folder, which is a subdirectory.</p> <p>Now that we have the mappings in the root Application.cfc, we need to apply them to the extends statement in Application.cfc located in the subdirectory. In the /admin/Application.cfc template use:</p> <p>/admin/Application.cfc </p> <p>Of course, rootCfc tells the Application.cfc in the subdirectory to look for the Proxy.cfc template in the root directory. Like other 'extend' statements, you don't need to specify '.cfc' at the end of Proxy.</p> <p>You don't need to use this 'extend' mapping in either the root Proxy.cfc or Application.cfc templates. They can already find each other as they are both in the same root directory.</p> <p>/Proxy.cfc </p> <p>Summary For the sake of absolute clarity: root Application.cfc Contains the mapping logic. Has the mappings for both of the root and subdirectory. Does not use an 'extend' statement</p> <p>root Proxy.cfm A simple 'extends=&quot;Administrator&quot; works. No mapping logic.</p> <p> </p> <p>subdirectory Application.cfc The extends statement must be the mapping variable name of the folder (rootCfc), a dot (.), and finally the name of the Proxy.cfc template without the .cfc prefix (Proxy)</p> <p>My apologies for being so verbose. I annoyed myself while writing this- but not as annoyed when I was while trying to solve this problem!</p> <p>Take care!</p>
39,564
<p>MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:</p> <pre><code>SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') </code></pre> <p>and that returns a nice recordset:</p> <pre><code>XML_F52E2B61-18A1-11d1-B105-00805F49916B ---------------------------------------- &lt;col1&gt;Foo&lt;/col1&gt;&lt;col1&gt;Bar&lt;/col1&gt; </code></pre> <p>only the column name in the returned recordset is rather nasty!</p> <p>The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID). Unfortunately I cannot use * to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...</p> <p>Is there a way to force the column name in the returned recordset to something more sensible?</p>
<p>That should do:</p> <pre><code>select( SELECT col1 FROM table1 WHERE col2 = 'x' ORDER by col3 FOR XML path('') ) as myName </code></pre> <p>Not pretty but should give the result that you need</p>
<pre><code>DECLARE @XmlData XML; SET @XmlData = ( SELECT * FROM [dbo].[TABLE1] FOR XML PATH('ChildNodeDetailsResponse') ,ROOT('ParentNode') ) SELECT @XmlData AS Result </code></pre>
39,209
<p>There are two directories with source trees. What is the best software to reveal changes in them. The should be not only file names but also some file-comparison viewer. It could be better if it is free tool.</p>
<p><a href="http://www.winmerge.org/" rel="nofollow noreferrer">WinMerge</a>, While not quite up to Beyond Compare, it's close and it's open-source.</p>
<p>I've used <a href="http://www.grigsoft.com/download-windiff.htm" rel="nofollow noreferrer">windiff</a> for quick checks. it's not incredibly sophisticated, but it does the job. </p>
25,085
<p>I'm new to printing resin miniatures for Dungeons &amp; Dragons and most of my prints are successful, i.e. one or more miniatures print as expected.</p> <p>However when I have multiple minis on the build plate the one in the middle works okay but the ones on the edges don't adhere to the build plate.</p> <p>Should I limit myself to one or two minis in the center of the build plate? Or should it work and I just need to get my settings correct?</p> <p>Note I'm using a Beam 3D Prism printer.</p>
<p>You can definitely print full build plates of minis. You just need to find correct settings. If nothing sticks to the build plate - then you should increase bottom exposure time. Also check if the build plate is even. You can also sand your build plate a little bit to make adhesion better. Additionally, print with lower print speeds to increase success. Finally, if your FEP is worn out and scratched or hazy, you should replace it.</p> <p>I own a company producing 3D printing resins. We also write extensive printing guides from time to time. You can read more on finding correct settings in this <a href="https://ameralabs.com/blog/the-complete-resin-3d-printing-settings-guide-for-beginners/" rel="nofollow noreferrer">article</a> of mine.</p>
<p>I regularly print multiple models on the build plate of an Elegoo Saturn. If your built plate is level and your tank is firmly fastened down you should have no problems.</p> <p>What I have found is the my slicer (Chitubox) will sometimes corrupt the base layer if I print multiple models. With me this usually causes the bottom layer to be deformed, and to have jutting protrusions that were not on the original layer, or for the slicer not to recognize the base layer as being flat.</p> <p>The second picture shows an example of how the skate or one model was deformed. The small pieces of cured resin are corrupted data and aren't part of any model or support structure. They were not visible in Chitubox unless I manually rotated the object view and saw little visual glitches.</p> <p>I would advice that you check your sliced files.</p> <p>See the example image:</p> <p><a href="https://i.stack.imgur.com/dnTJC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dnTJC.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/gQzHT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gQzHT.jpg" alt="enter image description here" /></a></p>
1,646
<p>I am working in Vista 64 bit system.</p> <p>I have a 3rdPartyUsbDriver.sys and 3rdPartyUsbDriver.inf files.</p> <p>I have made the neccesary changes to the vendor &amp; product IDs in the inf file, to work with my custom hardware. This installs and works in 'Unsigned Driver Test mode' just fine.</p> <p>I now want to install this driver in 'Normal mode'. I do not care, if it pops up warnings that this driver is from a untrusted source.</p> <p>What is the easiest way to do this?</p>
<p>Kuler is pretty nice. I also like <a href="http://www.degraeve.com/color-palette/" rel="nofollow noreferrer">http://www.degraeve.com/color-palette/</a> for just creating a color scheme based on an image, and <a href="http://www.colourlovers.com/" rel="nofollow noreferrer">http://www.colourlovers.com/</a> for picking colors that go nicely together.</p>
<p>Color scheme from logo or any image: online tool where you can upload image/logo and it gives you out a suggested color scheme that matches your logo/image.</p> <p>Here is the link <a href="http://www.pictaculous.com/" rel="nofollow noreferrer">http://www.pictaculous.com/</a></p>
38,847
<p>I am using the following html page:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;AJAX Example&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html"; charset="iso-8859-1"&gt; &lt;/head&gt; &lt;script language="JavaScript" src="ajaxlib.js"&gt;&lt;/script&gt; &lt;!--define the ajax javascript library--&gt; &lt;body&gt; Click this &lt;a href="#" OnClick="GetEmployee()"&gt;link&lt;/a&gt; to show ajax content (will be processed backgroundly without refreshing whole page)&lt;br/&gt; &lt;!--a href=# OnClick=GetEmployee() is the javascript event on a link to execute javascript function (GetEmployee) inside ajaxlib.js--&gt; &lt;div id="Result"&gt;&lt; the result will be fetched here &gt;&lt;/div&gt; &lt;!--javascript use GetElementById function to replace the data backgroundly, we use &lt;div&gt; tag with id Result here so javascript can replace this value--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The Javascript is here: <a href="http://www.nomorepasting.com/getpaste.php?pasteid=22046" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22046</a></p> <p>And the PHP is here: <a href="http://www.nomorepasting.com/getpaste.php?pasteid=22047" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22047</a></p> <p>The problem is, everything seems logical and there are no errors, but the javascript does not seem to be called, and calling the php file directly gives a result such as this:</p> <p>Well the characters will not even paste in apparently...., but lots of little boxes with like this:</p> <pre><code>10 01 </code></pre>
<p>For starters, your <code>getEmployee()</code> function should <code>return false;</code> to prevent the default action on the <code>&lt;a&gt;</code>. The little boxes thing seems to imply that the character sets aren't matching up. Make sure that the HTML page and the PHP page both use the same character set. I'd suggest trying to make everything UTF-8.</p> <p>Edit: misread slightly - I think it's the character set PHP is outputting doesn't match the character set in your database.</p>
<p>I suggest getting Firefox + tamper data add-on.. You'll be able to see if your browser is downloading the javascript, and also view the ajax request + data to see what's going on. Also checkout the error console for javascript errors. I would start there.</p>
38,726
<p>In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:</p> <pre><code>public class A { public event EventHandler SomeEvent; public void someMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); } } public class B : A { public void someOtherMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); // &lt;&lt; why is this not possible? //Error: The event 'SomeEvent' can only appear on the left hand side of += or -= //(except when used from within the type 'A') } } </code></pre> <p>Why isn't it possible?</p> <p>And what is the common solution for this kind of situation?</p>
<p>The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.</p> <p>For an explanation of the why read <a href="https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253803">Jon Skeet's</a> answer or the <a href="http://msdn.microsoft.com/en-us/library/aa664454(VS.71).aspx" rel="noreferrer">C# specification</a> which describes how the compiler automatically creates a private field.</p> <p>Here is one possible work around.</p> <pre><code>public class A { public event EventHandler SomeEvent; public void someMethod() { OnSomeEvent(); } protected void OnSomeEvent() { EventHandler handler = SomeEvent; if(handler != null) handler(this, someArgs); } } public class B : A { public void someOtherMethod() { OnSomeEvent(); } } </code></pre> <p><strong>Edit:</strong> Updated code based upon <a href="http://msdn.microsoft.com/en-us/library/cf18x51d(VS.71).aspx" rel="noreferrer">Framework Design Guidelines section 5.4</a> and <a href="https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253806">reminders</a> by others.</p>
<p>Wrap it with a protected virtual On... method:</p> <pre><code>public class BaseClass { public event EventHandler&lt;MyArgs&gt; SomeEvent; protected virtual void OnSomeEvent() { if(SomeEvent!= null) SomeEvent(this, new MyArgs(...) ); } } </code></pre> <p>Then override this in a derived class</p> <pre><code>public class DerivedClass : BaseClass { protected override void OnSomeEvent() { //do something base.OnSomeEvent(); } } </code></pre> <p>You'll set this pattern all over .Net - all form and web controls follow it.</p> <p>Do not use the prefix Raise... - this is not consistent with MS's standards and can cause confusion elsewhere.</p>
31,636
<p>How can I allow others to create Java, .NET, Ruby, PHP, Perl web user interface components that interact with each other?</p> <p>For example, one web ui component written in .NET selects a customer, and the other web user interface components are written in Java, Ruby or PHP are able to refresh showing information about the selected customer from different systems.</p>
<p>Look up something called WebServices, SOAP and XML-RPC. Should get you well on your way.</p>
<p>Use web services to wrap common code / libraries that you want to share across the interfaces. All the listed platforms have decent support for webservices.</p>
11,948
<p>How can I test sending email from my application without flooding my inbox? </p> <p>Is there a way to tell IIS/ASP.NET how to deliver email to a local folder for inspection?</p>
<p>Yes there is a way.</p> <blockquote> <p>You can alter web.config like this so that when you send email it will instead be created as an .EML file in c:\LocalDir.</p> </blockquote> <pre><code> &lt;configuration&gt; &lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp deliveryMethod="SpecifiedPickupDirectory"&gt; &lt;specifiedPickupDirectory pickupDirectoryLocation="c:\LocalDir"/&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; &lt;/configuration&gt; </code></pre> <p>You can also create an instance of the <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx" rel="noreferrer"><code>SmtpClient</code></a> class with these same settings, if you don't want to/can't change the web.config. In C# that looks something like this:</p> <pre><code>var smtpClient = new SmtpClient(); smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; var emailPickupDirectory = HostingEnvironment.MapPath("~/EmailPickup"); if (!Directory.Exists(emailPickupDirectory)) { Directory.CreateDirectory(emailPickupDirectory) } smtpClient.PickupDirectoryLocation = emailPickupDirectory; </code></pre>
<p>Configure rules in your email client to move the messages based on the subject/sender's email address?</p>
21,452
<p>I need advice regarding subselect performance in MySQL. For a reason that I can't change, I am not able to use JOIN to create quesry filter, I can only add another AND clause in WHERE.</p> <p>What is the peformance of:</p> <pre><code>select tasks.* from tasks where some criteria and task.project_id not in (select id from project where project.is_template = 1); </code></pre> <p>compared to:</p> <pre><code>select tasks.* from tasks, project where some criteria and task.project_id = project.id and project.is_template &lt;&gt; 1; </code></pre> <p>Note that there is relatively small number of projects whete is_template = 1, and there could be large number of projects where is_template &lt;> 1.</p> <p>Is there other way to achieve the same result without subselects if I can't change anything but and filter?</p>
<p>I believe that the second is more efficient as it requires only one select, but to be sure, you should EXPLAIN each query and check the results.</p> <pre><code>EXPLAIN select tasks.* from tasks where some criteria and task.project_id not in (select id from project where project.is_template = 1); EXPLAIN select tasks.* from tasks, project where some criteria and task.project_id = project.id and project.is_template &lt;&gt; 1; </code></pre>
<p>I think the first may scale better:</p> <p>When you do a join, internally mysql makes a sort of temporary table consisting of the two tables joined according to the join conditions specified. You aren't giving a join condition, so it'll create a temp table with all tasks listed against all projects. I'm fairly sure (but do check with the explain tool) that it does this prior to applying any where clauses. </p> <p>Result: if there are 10 of each, it'll have 10 * 10 rows = 100. You can see how this gets big as numbers rise. It then applies the where to this temporary table.</p> <p>By contrast, the subquery selects only the relevant rows from each table.</p> <p>But unless scaling is a concern, I don't think it really matters. </p>
44,319
<p>I have many instances of an application installed on an IIS 6.0, Windows Server 2003 box under the same application pool. They share many of the same assemblies and can not be joined in to a single application. </p> <p>I recently added a new instance of the application and obtained a System.OutOfMemoryException when I tried to load the ASP.NET 2.0 application. </p> <p>Will using the GAC to store common assemblies fix this error or can this only be remedied by spacing the sites between different application pools?</p>
<p>Putting something in the GAC only changes the physical location of the DLL (and security settings), it doesn't change what's loaded into memory.</p> <p>Most people tend to think of the GAC as "where Microsoft puts their stuff". I haven't seen many applications created by "everybody else" that can justify using the GAC.</p> <p>You should probably start thinking about a load-balancing solution of you are putting that much RAM pressure on your machine.</p>
<p>Putting a shared assembly into the GAC saves drive space, eg. if you have 20 asp applications that use the same dll. It might be the case that you load fewer copies of teh same dll into memory as well, I'm not sure. That said, OutOfMemoryErrors are more likely to be caused by loading extremely large obejects into memory, a typical example is a DataSet. Assemblies are small in comparison to the memory you can eat up with large datasets or large xml files in memory.</p>
29,855
<p>I am using C# and trying to read a <code>CSV</code> by using this connection string;</p> <blockquote> <pre><code>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\rajesh.yadava\Desktop\orcad;Extended Properties="Text;HDR=YES;IMEX=1;FMT=Delimited" </code></pre> </blockquote> <p>This works for tab delimited data.</p> <p>I want a connection string which should for tab delimited as well as comma(,) and pipe(|).</p> <p>How can I make a generic connection string for <code>CSV</code>.</p> <p>Thanks Rajesh</p>
<p>Is the <a href="http://filehelpers.sourceforge.net/" rel="nofollow noreferrer">filehelpers</a> library an option?</p>
<p>Here's a few links from the net discussing this issue:</p> <ul> <li><a href="http://weblogs.asp.net/fmarguerie/archive/2003/10/01/29964.aspx" rel="nofollow noreferrer">Manipulating CSV Files</a></li> <li><a href="http://www.connectionstrings.com/?carrier=textfile" rel="nofollow noreferrer">ConnectionStrings.com</a></li> <li><a href="http://support.microsoft.com:80/support/kb/articles/Q262/5/37.ASP" rel="nofollow noreferrer">How To Open Delimited Text Files Using the Jet Provider's Text IIsam</a></li> </ul>
41,817
<p>can anyome help me find an elegant design for splitting, traversing and tracking objects.</p> <p>The diagram below shows an object with an initial size of 100 which is spilt into two (50, 75) then one of the child objects (75) is subsequently split into three (25, 25 ,25).</p> <p>My question is can anyone think of an elegant design that will allow me from <strong>any object</strong> to traverse the entire tree (for example to identify the root parent from any subsequently child object)? </p> <p>My current attempt (see code below) uses the instance fields Parent and Children to track the objects but it obviously doesn’t give me the functionality I require – as from Obj [Id:6] I cannot recursively find the root parent.</p> <p>Can anyone think of a solution? I don’t think a double linked list will work as the spilt parameter is not limited to just two.</p> <pre><code> Obj [Id:1, Size:100] | Split operation (50, 75) &lt;&gt; Obj [Id:2, Size:25] Obj [Id:2, Size:75] | Split operation (25, 25, 25) &lt;&gt; Obj [Id:4, Size:25] Obj [Id:5, Size:25] Obj [Id:6, Size:25] public class SplitableObj : IEquatable&lt;SplitableObj&gt; { private Guid _id = Guid.NewGuid(); private int _size; private SplitableObj _parent; private List&lt;SplitableObj&gt; _childern; public SplitableObj(int size) { _size = size; } public Guid id { get { return _id; } set { _id = value; } } public SplitableObj Parent { get { return _parent; } set { _parent = value; } } public List&lt;SplitableObj&gt; Children { get { return _childern; } set { _childern = value; } } public int Size { get { return _size; } set { _size = value; } } public IEnumerable&lt;SplitableObj&gt; Split(params int[] splits) { if (splits.Length &lt; 2) { throw new ApplicationException("splits must be least 2."); } int totalSplits = 0; foreach (int split in splits) { totalSplits += split; } if (_size != totalSplits) { throw new ApplicationException("Total splits must equal Size."); } foreach (int split in splits) { SplitableObj splitAmount = new SplitableObj(split); splitAmount.Parent = this; this.Children.Add(splitAmount); yield return splitAmount; } } public bool Equals(SplitableObj splitableObj) { if (splitableObj == null) return false; return Equals(_id, splitableObj._id); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; return Equals(obj as SplitableObj); } public override int GetHashCode() { return _id.GetHashCode(); } } </code></pre>
<p>Homework?</p> <pre><code>set RootObject to the current object. while the parent of RootObject is not undefined, set RootObject to its parent. Finally, return RootObject. </code></pre>
<p>Why you have difficulty in locating the root? go from parent to parent until parent is not set.</p> <p>BTW Are you talking about B+ trees? They auto balance using blocks of children that get split when a threshold is exceeded look at this image in wikipedia <a href="https://web.archive.org/web/20100305054914/http://upload.wikimedia.org:80/wikipedia/commons/f/fe/Btree.svg" rel="nofollow noreferrer"><img src="https://web.archive.org/web/20100305054914/http://upload.wikimedia.org:80/wikipedia/commons/f/fe/Btree.svg" alt="image"></a></p>
38,242
<p>When creating a new C++ header/source file, what information do you add to the top? For example, do you add the date, your name, a description of the file, etc.? Do you use a structured format for this information?</p> <p>e.g.</p> <pre><code>// Foo.cpp - Implementation of the Foo class // Date: 2008-25-11 // Created by: John Smith </code></pre> <p>One team I know embeds CVS commit messages to the foot of each file, but I'm not sure I want to go this far...</p>
<p>Information about who created a file and when and who edited it and when is all in source control. If your team has good practices around check-in comments, then you'll know the reasons for each change too. No need for comments for that stuff.</p> <p>I think it's 100% legit - wise, even - to put a comment block, as long as is necessary, explaining the purpose of the class/module. When the next person goes to change it, they'll have a better idea of the overall vision and whether this file is the appropriate place for their change.</p> <p>Some shops put copyright notices and other legal folderol in source file comments. This strikes me as just silly - if your (non-OSS) source code has made it onto someone else's servers without your knowledge or permission, a copyright notice is probably not going to deter them from doing anything with it. IANAL, YMMV.</p>
<p>i generally only add any "comment info" when... i don't think i'll remember or its not obvious what something is doing or when i release the source code and i actually want others to be able to use/learn from it.</p>
41,217
<p>Is it possible to convert an existing WPF Application to SilverLight automatically/with minimal effort?</p>
<p>Not really. I have found some articles regarding the <a href="http://msdn.microsoft.com/en-us/magazine/cc895632.aspx" rel="noreferrer">multi-targeting</a> option for <a href="http://blogs.msdn.com/dphill/archive/2008/08/31/hello-prism-2-0.aspx" rel="noreferrer">WPF and Silverlight</a> at the same time. At this moment, if you are not using <a href="http://www.codeplex.com/CompositeWPF" rel="noreferrer">PRISM</a>, it is quite a challenge to target both of them, fortunately achievable.</p> <p>What do you need to have in mind is that Silverlight uses a smaller (thus more limited) library than WPF.</p> <p>In response to the comments: Actually, there is already support for silverlight in PRISM (<a href="http://www.codeplex.com/CompositeWPF/Release/ProjectReleases.aspx?ReleaseId=17802" rel="noreferrer">v2</a>). The idea of PRISM is to provide guidance to developing applications not only using WPF but using <a href="http://www.codeplex.com/CompositeWPFContrib/Wiki/View.aspx?title=Prism%20to%20Silverlight" rel="noreferrer">Silverlight</a> also - Prism V2 formally was known as Composite Application Guidance for WPF and Silverlight. By using PRISM for silverlight capabilities, it would give you the warranty that your code would work on both platforms with minimal changes, if <a href="http://www.pnpguidance.net/post/Prism2Drop1CompositeWPFSilverlightApplicationGuidancePatternsPractices.aspx" rel="noreferrer">none (except maybe the different project types for visual studio)</a>.</p> <p>But of course, if you already started developing your application, you would need to change your code to use PRISM.</p>
<p>Here is a thread about this: <a href="http://silverlight.net/forums/t/3898.aspx" rel="nofollow noreferrer">http://silverlight.net/forums/t/3898.aspx</a></p>
26,068
<p>I installed Ruby and Ruby on Rails yesterday on Vista 32bit using the directions on this site: <a href="http://rubyonrails.org/down" rel="nofollow noreferrer">http://rubyonrails.org/down</a></p> <p>So I downloaded the installer, then Gems, then I downloaded rails with Gems.</p> <p>Now I can't use the Gem or Ruby commands in the command line... so I assume there's something wrong with the environment variables, but I hav eno idea how to set them up in Vista or what to put.</p> <p>Can anyone help me with this?</p>
<p>To set up the environment variables, do this</p> <ol> <li>Fire up the start menu</li> <li><strong>Right-Click</strong> on <code>Computer</code> and select <code>Properties</code></li> <li>Click <code>Advanced system settings</code> in the left-hand bar, and confirm the UAC prompt</li> <li>Select the <code>Advanced</code> tab (it's 3rd)</li> <li>Click <code>Environment Variables...</code> (at the bottom)</li> <li>In the top box (<code>User variables for XXX</code>) either find the entry for <code>PATH</code>, or click new to create the entry.<br> If there is already a <code>PATH</code> use semi-colons to seperate each directory listed in it</li> <li>Put <code>c:\ruby\bin</code> (change if you installed ruby somewhere else) in.</li> <li>Click OK a lot of times to close all the windows we opened.</li> <li>Restart your command prompt.</li> </ol> <p><code>gem</code> and <code>ruby</code> and <code>irb</code> should now all work. Whoever said that GUI tools are slower than command line tools. pshaw!</p>
<p>Add your ruby bin directory to your PATH environment variable, go to Control Panel -> System -> Advanced system settings, then go to the Advanced tab, Environment Variables, then edit your PATH variable and append the path to the ruby binaries install i.e. <strong>;C:\ruby\bin</strong></p>
21,843
<p>I think title should be good enough.</p>
<p>Tags should be used when you want to mark a milestone. The milestone could be as small as a daily build.</p> <p>Branches should be used when you want to make changes independently from another branch/trunk.</p>
<p>Branching should also be used for major milestones, such as a releases. This depends on your <a href="http://www.google.com/search?hl=en&amp;q=branching+strategy" rel="nofollow noreferrer">branching strategy</a> though.</p>
17,368
<p>I'm perplexed. At CodeRage today, Marco Cantu said that CharInSet was slow and I should try a Case statement instead. I did so in my parser and then checked with AQTime what the speedup was. I found the Case statement to be much slower.</p> <p>4,894,539 executions of:</p> <blockquote> <p>while not CharInSet (P^, [' ', #10,#13, #0]) do inc(P);</p> </blockquote> <p>was timed at 0.25 seconds.</p> <p>But the same number of executions of:</p> <blockquote> <p>while True do<br> &nbsp;&nbsp;case P^ of<br> &nbsp;&nbsp;&nbsp;&nbsp;' ', #10, #13, #0: break;<br> &nbsp;&nbsp;&nbsp;&nbsp;else inc(P);<br> &nbsp;&nbsp;end;</p> </blockquote> <p>takes .16 seconds for the "while True", .80 seconds for the first case, and .13 seconds for the else case, totaling 1.09 seconds, or over 4 times as long.</p> <p>The assembler code for the CharInSet statement is:</p> <blockquote> <p>add edi,$02<br> mov edx,$0064b290<br> movzx eax,[edi]<br> call CharInSet<br> test a1,a1<br> jz $00649f18 (back to the add statement)</p> </blockquote> <p>whereas the case logic is simply this:</p> <blockquote> <p>movzx eax,[edi]<br> sub ax,$01<br> jb $00649ef0<br> sub ax,$09<br> jz $00649ef0<br> sub ax,$03<br> jz $00649ef0<br> add edi,$02<br> jmp $00649ed6 (back to the movzx statement)</p> </blockquote> <p>The case logic looks to me to be using very efficient assembler, whereas the CharInSet statement actually has to make a call to the CharInSet function, which is in SysUtils and is also simple, being:</p> <blockquote> <p>function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean;<br> begin<br> Result := C in CharSet;<br> end;</p> </blockquote> <p>I think the only reason why this is done is because P^ in [' ', #10, #13, #0] is no longer allowed in Delphi 2009 so the call does the conversion of types to allow it.</p> <p>None-the-less I am very surprised by this and still don't trust my result.</p> <p>Is AQTime measuring something wrong, am I missing something in this comparison, or is CharInSet truly an efficient function worth using?</p> <hr> <p>Conclusion: </p> <p>I think you got it, Barry. Thank you for taking the time and doing the detailed example. I tested your code on my machine and got .171, .066 and .052 seconds (I guess my desktop is a bit faster than your laptop).</p> <p>Testing that code in AQTime, it gives: 0.79, 1.57 and 1.46 seconds for the three tests. There you can see the large overhead from the instrumentation. But what really surprises me is that this overhead changes the apparent "best" result to be the CharInSet function which is actually the worst.</p> <p>So Marcu is correct and CharInSet is slower. But you've inadvertently (or maybe on purpose) given me a better way by pulling out what CharInSet is doing with the AnsiChar(P^) in Set method. Other than the minor speed advantage over the case method, it is also less code and more understandable than using the cases.</p> <p>You've also made me aware of the possibility of incorrect optimization using AQTime (and other instrumenting profilers). Knowing this will help my decision re <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi">Profiler and Memory Analysis Tools for Delphi</a> and it also is another answer to my question <a href="https://stackoverflow.com/questions/322315/how-does-aqtime-do-it">How Does AQTime Do It?</a>. Of course, AQTime doesn't change the code when it instruments, so it must use some other magic to do it.</p> <p>So the answer is that AQTime is showing results that lead to the incorrect conclusion.</p> <hr> <p>Followup: I left this question with the "accusation" that AQTime results may be misleading. But to be fair, I should direct you to read through this question: <a href="https://stackoverflow.com/questions/1694001/is-there-a-fast-gettoken-routine-for-delphi">Is There A Fast GetToken Routine For Delphi?</a> which started off thinking AQTime gave misleading results, and concludes that it does not.</p>
<p>AQTime is an instrumenting profiler. Instrumenting profilers often aren't suitable for measuring code time, particularly in microbenchmarks like yours, because the cost of the instrumentation often outweighs the cost of the thing being measured. Instrumenting profilers, on the other hand, excel at profiling memory and other resource usage.</p> <p>Sampling profilers, which periodically check the location of the CPU, are usually better for measuring code time.</p> <p>In any case, here's another microbenchmark which indeed shows that a <code>case</code> statement is faster than <code>CharInSet</code>. However, note that the set check can still be used with a typecast to eliminate the truncation warning (actually this is the only reason that CharInSet exists):</p> <pre><code>{$apptype console} uses Windows, SysUtils; const SampleString = 'foo bar baz blah de;blah de blah.'; procedure P1; var cp: PChar; begin cp := PChar(SampleString); while not CharInSet(cp^, [#0, ';', '.']) do Inc(cp); end; procedure P2; var cp: PChar; begin cp := PChar(SampleString); while True do case cp^ of '.', #0, ';': Break; else Inc(cp); end; end; procedure P3; var cp: PChar; begin cp := PChar(SampleString); while not (AnsiChar(cp^) in [#0, ';', '.']) do Inc(cp); end; procedure Time(const Title: string; Proc: TProc); var i: Integer; start, finish, freq: Int64; begin QueryPerformanceCounter(start); for i := 1 to 1000000 do Proc; QueryPerformanceCounter(finish); QueryPerformanceFrequency(freq); Writeln(Format('%20s: %.3f seconds', [Title, (finish - start) / freq])); end; begin Time('CharInSet', P1); Time('case stmt', P2); Time('set test', P3); end. </code></pre> <p>Its output on my laptop here is:</p> <pre><code>CharInSet: 0.261 seconds case stmt: 0.077 seconds set test: 0.060 seconds </code></pre>
<p>As I know call takes same amount of processor operations as jump does if they are both using short pointers. With long pointers may be different. Call in assembler does not use stack by default. If there is enough free registers used register. So stack operations take zero time too. It is just registers which is very fast.</p> <p>In contrast case variant as I see uses add and sub operations which are quite slow and probably add most of extratime.</p>
43,153
<p>I want to use Lucene (in particular, Lucene.NET) to search for email address domains.</p> <p>E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.</p> <p>Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "[email protected]" is seen as a whole word, and you cannot search for just parts of a word.</p> <p>How can I do this?</p>
<p>No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers.</p> <p>The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created.</p> <p>Here's the source code, it's actually very simple:</p> <pre><code>class WhitespaceAndAtSymbolTokenizer : CharTokenizer { public WhitespaceAndAtSymbolTokenizer(TextReader input) : base(input) { } protected override bool IsTokenChar(char c) { // Make whitespace characters and the @ symbol be indicators of new words. return !(char.IsWhiteSpace(c) || c == '@'); } } internal class WhitespaceAndAtSymbolAnalyzer : Analyzer { public override TokenStream TokenStream(string fieldName, TextReader reader) { return new WhitespaceAndAtSymbolTokenizer(reader); } } </code></pre> <p>That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index:</p> <pre><code>IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer()); index.AddDocument(myDocument); </code></pre> <p>Performing searches should use the analyzer as well:</p> <pre><code>IndexSearcher searcher = new IndexSearcher(indexDirectory); Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com"); Hits hits = query.Search(query); </code></pre>
<p>You could a separate field that indexes the email address reversed: Index '[email protected]' as 'moc.liamg@oof' Which enables you to do a query for "moc.liamg@*" </p>
3,952
<p>I'm using libcurl in a Win32 C++ application.</p> <p>I have the curllib.vcproj project added to my solution and set my other projects to depend on it.</p> <p>How do I build it with SSL support enabled?</p>
<p>Well, since this post failed badly, I had to dig into the matter myself. </p> <p><strong><em>Also check out the other answers and comments for additional info regarding other versions etc.</em></strong></p> <p><strong>EDIT: Since I posted this Q there seems to be ready-built binaries made available from the curl homepage. Check out <a href="https://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows/5129202#5129202">James' answer</a>.</strong></p> <h2>So here goes:</h2> <p>-</p> <p><strong>Preprocessor</strong></p> <p>The following two symbols need to be fed to the preprocessor to enable SSL for libcurl:</p> <pre><code>USE_SSLEAY USE_OPENSSL </code></pre> <p>(libcurl uses OpenSSL for SSL support)</p> <p>Alternatively the symbols can be added directly to a file called setup.h in libcurl, but I'm not too happy about modifying code in 3rd party distributions unless I really have to.</p> <p>Rebuilding the libcurl library, I now got some errors about OpenSSL include files not being found. Naturally, since I haven't set up the OpenSSL distribution properly yet.</p> <p><strong>Compiling OpenSSL binaries</strong></p> <p>I downloaded the OpenSSL 0.9.8 source distribution and unpacked it.</p> <p>In the root of the source distribution there's a file called INSTALL.W32 which describes how to compile the OpenSSL binaries. The build chain requires perl, so I installed the latest version of ActivePerl.</p> <p>I had some trouble with the build, which might not be applicable to all systems, but I'll go through it here in case somebody experiences the same.</p> <p>According to INSTALL.W32:</p> <p>Run the following commandline tasks with current directory set to the source distribution root:</p> <pre><code>1&gt; perl Configure VC-WIN32 --prefix=c:/some/openssl/dir </code></pre> <p>(Where "c:/some/openssl/dir" should be replaced by the dir where OpenSSL should be installed. Don't use spaces in this path. The compilation further ahead will fail in that case)</p> <pre><code>2&gt; ms\do_ms </code></pre> <p>For me this step was unsuccessful at first, since I lacked the environment variables OSVERSION and TARGETCPU. I set these to <em>5.1.2600</em> and <em>x86</em> respectively. You may get complaint about OSVERSION being "insane", but look closer, this error is for WinCE and doesn't affect the Win32 setup. To get hold of your OS version, run the 'ver' command from a command prompt or run winver.exe.</p> <pre><code>3&gt; nmake -f ms\nt.mak (for static library) </code></pre> <p>or</p> <pre><code>3&gt; nmake -f ms\ntdll.mak (for DLL) </code></pre> <p>The source now compiles. Took approx 5 minutes on my laptop.</p> <p>When compilation is completed, the libs or binaries have been placed in:</p> <p><em>distroot/out32</em> - for static library build</p> <p>or</p> <p><em>distroot/out32dll</em> - for DLL build</p> <p><strong>Building and linking</strong></p> <p>Now, back to visual studio and point out the libs and include path for headers. The include files are located in <strong>distroot/inc32/openssl</strong>.</p> <p>Remember to add <em>libeay32.lib</em> and <em>ssleay32.lib</em> as linker input.</p> <p>Rebuild the libcurl project. </p> <p><strong>Error!</strong> </p> <p>Well at least for me with this version of OpenSSL. it complained about a struct typedef in one of the OpenSSL headers. I couldn't find any info on this. After an hour of googling I broke my own principle and commented out the typedef from the OpenSSL header, and luckily libcurl wasn't using that symbol so it built fine.</p> <p><em>Update: As pointed out by Jason, this issue seems to have dissapeared as of version 1.0.0a.</em></p> <p>Now, for confirming that SSL support is enabled for libcurl, run the following code:</p> <pre><code>curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW ); if( vinfo-&gt;features &amp; CURL_VERSION_SSL ) // SSL support enabled else // No SSL </code></pre> <hr> <p>Simple as that.</p>
<p>i did "do_nt.bat" for windows 7 rc7100 don't forget "nmake -f ms\nt.mak install" to copy the headers correctly</p> <p>thanks this did help a lot</p>
24,025
<p>I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; <code>messages (id, body)</code> and <code>messages_read (user_id, message_id)</code>.</p> <p>Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?</p> <p>Thanks!</p>
<p>Well, you could use</p> <pre><code>SELECT id FROM messages m WHERE m.id NOT IN( SELECT message_id FROM messages_read WHERE user_id = ?) </code></pre> <p>Where ? is passed in by your app.</p>
<p>Something like:</p> <pre><code>SELECT id, body FROM messages LEFT JOIN (SELECT message_id FROM messages_read WHERE user_id = ?) ON id=message_id WHERE message_id IS NULL </code></pre> <p>Slightly tricky and I'm not sure how the performance will scale up, but it should work.</p>
10,230
<p>There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.</p> <p>This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:</p> <pre><code>... we hold these truths to be self evident, that &lt;/page&gt; &lt;page&gt;all men are created equal, and are ... </code></pre> <p>So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.</p> <p>Anybody have any thoughts on this?</p>
<p>In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is <a href="http://en.wikipedia.org/wiki/Inter-process_communication" rel="noreferrer">Inter-process Communication (IPC)</a>. There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, <a href="http://en.wikipedia.org/wiki/Remote_procedure_call" rel="noreferrer">remote procedure calls (RPC)</a> and shared memory. On Windows it's also common to use <a href="http://msdn.microsoft.com/en-us/library/aa931932.aspx" rel="noreferrer">window messages</a>.</p> <p>I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can <a href="http://msdn.microsoft.com/en-us/library/ms644990.aspx" rel="noreferrer">hook on to the message loop of external processes and "spy" on the messages they are sending</a>. If your program generates a message event when the desired function is called, this could be a way to detect it.</p> <p>If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network).</p>
<p>What's the nature of that OnEmailSent event from that third party application? I mean, how do you know the application is triggering such an event?</p> <p>If <em>you</em> are planning on doing interprocess communication, the first question you should ask yourself is: Is it really necessary?</p> <p>Without questioning your motives, if you really need to do interprocess communication, you will need some sort of mechanism. The list is long, very long. From simple WM_DATA messages to custom TCP protocols to very complex Web services requiring additional infrastructures.</p> <p>This brings the question, what is it you are trying to do exactly? What is this third party application you have no control over?</p> <p>Also, the debugger has a very invasive way of debugging processes. Don't expect that to be the standard interprocess mechanism used by all other applications. As a matter of fact, it isn't.</p>
3,848
<p>I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using:</p> <pre class="lang-css prettyprint-override"><code>html, body { height: 100%; margin: 0; padding: 0; } #container { min-height: 100%; width: 100%; } </code></pre> <p>And I place something like this in the page code:</p> <pre><code>&lt;table id="container"&gt; &lt;tr&gt; &lt;td&gt; ... </code></pre> <p>This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers?</p> <p>(Adding <code>id="container"</code> to <code>td</code> doesn't help.)</p>
<p>Just use the <code>height</code> property instead of the <code>min-height</code> property when setting <code>#container</code>. Once the data gets too big, the table will automatically grow.</p>
<p>You can handle this in Javascript/JQuery.</p> <pre><code>window_height = $(window).height(); $('#container').css('min-height', window_height); </code></pre>
11,544
<p>I am trying to embed multiple external websites into one web page. Using an IFRAME works ok, but once you get past 10 embedded iframes, the memory fottprint starts to get too big.</p> <p>So I was thinking, is it possible via ajax/javascript, to re-use the same iframe to load the collection of websites one after enother, and display the results in a div on the main webpage? Or is this explicitly blocked for security reasons?</p> <p>EDIT: I don't want to go the screen scraping route, as I was planning to make this a semi public site, and I don't want to incur all the bandwidth on my server and would rather have that done on the client, if it is possible.</p>
<p>You are trying to use a hammer to put screws in the wall. Maybe some will go, but it won't be pretty. Your best option would be either a screen scraper or web services in order to retrieve the data from the external sites. Perhaps include more details about the situation such as, are the external sites your own. Do they offer syndication of their content that you are after. Are offline services available to you so you can consume this content?</p>
<p>If you are concerned about bandwidth on your server, could you do the screen scraping (basically pull down the html through an http request) and then store that in the .net cache? Even if you stored the html for each site in the cache for 15 minutes, you would only be pulling that information down 4 times an hour. You would still have to push that html down to the client, but you could at least compress it with gzip before sending it down.</p>
30,702
<p>I'm developing a client/server application in .Net 3.5 using WCF. Basically, a long running client service (on several machines) establish a duplex connection to the server over a netTcpBinding. The server then uses the callback contract of the client to perform certain on-demand oparations, to which the client responds in an asynchronous fashion (fairly standard stuff I think). I subclass the DuplexClientBase class to handle most of the communication.</p> <p>Unfortunately, when something goes wrong on either end (such as a network failure, unexpected exception, etc), the channel gets faulted/aborted and all subsequent operations fail. I've gotten around this limitation in non-duplex channels by creating a RecoveringClientBase class that automatically picks up when the client has faulted and retries the operation.</p> <p>So my question is, is there an established way of determining when a duplex channel has faulted? Where should I check this, on the server or the client? Failing that, what options do I have to ensure that the connection gets re-established?</p> <p><strong>Update:</strong> I'm looking for some advice specific to duplex channels, where the server might try to use a callback channel that was faulted. Thus, I need something that will immediately reconnect/resubscribe when something happens to the channel. At the moment I'm listening to the channel's Closing event and recreating it if the state is anything but Closed. It sort of works, but it feels hacky...</p>
<p>I have experienced flakiness in long running sessions (minutes-hours). I can't be sure that it's WCF, I'm pretty sure its network level. </p> <p>I am thinking of doing away with duplex altogether. It is a real nuisance trying to manage the state of the connection.</p> <p>I am thinking of hosting a service endpoint on the client for operations that are currently part of the callback contract. The client would contact the server with the endpoint details, the server can store these somewhere (persisted or wherever). When the server needs to contact the client, it opens a connect to the client via the stashed endpoint details. Basically, turning the duplex connection into 2 client-server connections.</p> <p>Doesn't answer your question, but I feel your pain.</p>
<p>I've had some similar problems, and to me it seems that these long-running calls are more or less unsupported.</p> <p>WCF seems to be designed to be used for short running calls. Services, which get called, do some small stuff, and be finished.</p> <p>I refactored my applications into smaller items of work. So instead of one big long running item I now got a lot of smaller items. Of course, sometimes this is not possible to achieve. Then I got to pray for stable network connections (exceptions can be caught, so faulting is not really a problem I think).</p>
25,018
<p>Ok, this has got to be a super simple problem. I just can't seem to find the answer anywhere. First - I'm not a web developer of any kind, I'm an old school c programmer - so don't flame me for what's probably something quite trivial :)</p> <p>I need to write a small proof-of-concept web app using ASP.NET. My first attempt here is to create a "Hello World!" app. So I opened up Visual Studio, and made a new web application. I have my Default.aspx file that calls a C# function that is inside the helloworld.dll created automatically by Visual Studio.</p> <p>I installed IIS on my local machine and created a virtual directory in the wwwroot subdirectory. I put the Default.aspx and helloworld.dll in that directory. Now when I browse to that page I see the following.</p> <pre><code>Server Error in '/test' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load type 'HelloWorld._Default'. Source Error: Line 1: &lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HelloWorld._Default" %&gt; Line 2: Line 3: &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; Source File: /test/default.aspx Line: 1 </code></pre> <p>Obviously, IIS doesn't know where to look for the .dll or anything like that. I just don't know how to register the .dll with IIS (or whoever manages that stuff in .net) so that it can find the functions it need.</p> <p>Can someone let me know how to "install" an ASP.NET application on IIS?</p>
<p>Your best bet is to use 'Publish website' from the Visual Studio Solution Explorer.</p> <p><a href="https://stackoverflow.com/users/2424/chris-lively">Chris Lively</a> adds: </p> <blockquote> <p>Just a minor add: Publish Website can be found by Right Clicking on the project name. The command will be named "Publish..."</p> </blockquote>
<p>I would recommend the solution of <a href="https://stackoverflow.com/users/5640/rich-b">Rich B</a>. And something else... DLLs are in a folder called "bin". Not at the root of the folder.</p>
38,045
<p>This is likely going to be an easy answer and I'm just missing something, but here goes...If I have a Type, (that is, an actual System.Type...not an instance) how do I tell if it inherits from another specific base type?</p>
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx" rel="noreferrer">IsSubclassOf</a> method of the <a href="http://msdn.microsoft.com/en-us/library/system.type_members.aspx" rel="noreferrer">System.Type</a> class.</p>
<p>EDIT: Note that the above solution will fail if the base type you are looking for is an interface. The following solution will work for any type of inheritance, be it class or interface.</p> <pre><code>// Returns true if "type" inherits from "baseType" public static bool Inherits(Type type, Type baseType) { return baseType.IsAssignableFrom(type) } </code></pre> <p>(Semi)Helpful extract from the <a href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx" rel="noreferrer">MSDN</a> article:</p> <p>true if [the argument] and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of [the argument], or if the current Type is an interface that [the argument] implements, or if [the argument] is a generic type parameter and the current Type represents one of the constraints of [the argument]. false if none of these conditions are true, or if [the argument] is a null reference (Nothing in Visual Basic). </p>
15,717
<p>How does one import CSV files via Excel VBA in a set, in groups or in multiple individual files, rather than one at a time?</p>
<p>I am a bit puzzled in that most versions of Excel will open .csv files with out any problems.</p> <pre><code>strPath = "C:\Docs\" strFile = Dir(strPath &amp; "*.csv") Do While strFile &lt;&gt; "" Workbooks.Open Filename:=strPath &amp; strFile ActiveWorkbook.SaveAs Filename:=strPath &amp; Mid(strFile, 1, InStr(strFile, ".") - 1) _ &amp; "Conv.xls", FileFormat:=xlNormal strFile = Dir Loop </code></pre>
<p>You could write a simple console application to parse a batch of csv files and save them to excel files.<br /> Not the easiest solution but it could be an option.</p>
28,300
<p>When opening Adobe Acrobat Pro, whether it be through <strong>Applescript</strong> or finder, the introductory dialog is shown. Is there a way to not show this dialog without already having checked the "Don't Show Again" option when opening a document using <strong>Applescript</strong>? </p> <p>Photoshop and Illustrator <strong>Applescript</strong> libraries have ways of setting interaction levels and not showing dialogs, but I can't seem to find the option in Acrobat.</p>
<p>Copy any applicable preferences files in ~/Library/Preferences from a machine that you have checked "Don't show again" on.</p>
<p>If it's not in the dictionary, probably not.</p>
3,031
<p>I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:</p> <ol> <li>No directories. JUST the file name.</li> <li>File name needs to be all lowercase.</li> <li>Whitespaces need to be replaced with underscores.</li> </ol> <p>Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).</p>
<p>If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at <a href="http://regexlib.com/" rel="nofollow noreferrer">http://regexlib.com/</a>. Edit to say: <a href="http://regexlib.com/REDetails.aspx?regexp_id=1934" rel="nofollow noreferrer">Here's one that might work for you</a>:</p> <pre><code>([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$ </code></pre>
<p>If you're taking a string path from the user (eg. by reading the .value of a file upload field), you can't actually be sure what the path separator character is. It might be a backslash (Windows), forward slash (Linux, OS X, BSD etc.) or something else entirely on old or obscure OSs. Splitting the path on either forward or backslash will cover the common cases, but it's a good idea to include the ability for the user to override the filename in case we guessed wrong.</p> <p>As for 'invalid characters' these too depend on the operating system. Probably the easiest path is to replace all non-alphanumerics with a placeholder such as an underscore.</p> <p>Here's what I use:</p> <pre><code>var parts= path.split('\\'); parts= parts[parts.length-1].split('/'); var filename= parts[parts.length-1].toLowerCase(); filename= filename.replace(new RegExp('[^a-z0-9]+', 'g'), '_'); if (filename=='') filename= '_' </code></pre>
15,893
<p>How do I get my project's runtime dependencies copied into the <code>target/lib</code> folder? </p> <p>As it is right now, after <code>mvn clean install</code> the <code>target</code> folder contains only my project's jar, but none of the runtime dependencies.</p>
<p>This works for me:</p> <pre class="lang-xml prettyprint-override"><code>&lt;project&gt; ... &lt;profiles&gt; &lt;profile&gt; &lt;id&gt;qa&lt;/id&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;install&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-dependencies&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${project.build.directory}/lib&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; &lt;/project&gt; </code></pre>
<p>If you're having problems related to dependencies not appearing in the WEB-INF/lib file when running on a Tomcat server in Eclipse, take a look at this:</p> <p><a href="https://stackoverflow.com/questions/4777026/classnotfoundexception-dispatcherservlet-when-launching-tomcat-maven-dependencie">ClassNotFoundException DispatcherServlet when launching Tomcat (Maven dependencies not copied to wtpwebapps)</a></p> <p>You simply had to add the Maven Dependencies in Project Properties > Deployment Assembly.</p>
12,314
<p>I've decided to add auto-update functionality to one of my applications and was looking for any existing solutions that compare the current running version with the latest version that is then downloaded from the web.</p> <p>I know <a href="http://sparkle.andymatuschak.org/" rel="noreferrer">Sparkle</a> on Mac OSX which is very nice and powerful, but was wondering whether there is something similar for Win32/MFC?</p>
<p>I just stumpled accross <a href="http://winsparkle.org/" rel="noreferrer">WinSparkle</a> which is an early stage but looks very promising.</p>
<p>In general no, windows maps things like DLLs (either your own or MFC) in such a way that you can't replace a running program. The msi installer checks the VERSIONINFO and doesn't overwrite installed files that have the same (or newer version) but you would have to quit the runnign instance.</p>
31,528
<p>I'm using markdown to edit this question right now. In some <a href="http://en.wikipedia.org/wiki/Wikipedia:How_to_edit_a_page#Wiki_markup" rel="noreferrer">wikis</a> I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use?</p>
<ul> <li><a href="http://en.wikipedia.org/wiki/Markup_language" rel="noreferrer">Markup</a> is a generic term for a language that describes a document's formatting</li> <li><a href="http://en.wikipedia.org/wiki/Markdown" rel="noreferrer">Markdown</a> is a specific markup library: <a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">http://daringfireball.net/projects/markdown/</a><br /> These days the term is more commonly used to refer to markup languages that mimic the style of the library. See: <a href="https://en.wikipedia.org/wiki/Markdown" rel="noreferrer">https://en.wikipedia.org/wiki/Markdown</a></li> </ul>
<p>Markup is a general term for content formatting - such as HTML - but markdown is a library that generates HTML markup. Take a look at <a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">Markdown</a>.</p>
4,382
<p>I was recently considering using GoogleData for a hobby project to store my service's old data, (say 24+hours old), while I keep the fresh data on my servers (hobby project==cheap home server).</p> <p>However I haven't really heard of anyone using GoogleData, so I was wondering about what other's experiences have been.</p> <p>Edit: My brief usage pattern would be to basically store (cached versions) of objects representing (historical) entities. And relatively immutable data like past events or these entities, global prototype data my objects (also relatively immutable), in order to reduce the load on my server.</p> <p>As for active entities I'd be storing changes locally and then posting them to GooglData (after 24 hours).</p> <p>Thanks</p>
<p>I did use GoogleData to store data frokm one of my project called TaskList. I use google spreadsheet specifically. It's quite hard to start with, but from google's sample, you can pretty sure knows what to do next. I did that in C#. Here's the sample apps and sdk for <a href="http://code.google.com/p/google-gdata/downloads/list" rel="nofollow noreferrer">google-gdata</a>. My advice, don't bother to read the online documentation about gdata, it explain a lot on the underlying xml structure and method to access each level (private vs public) data. You need to have a google account to start with. The way the data is read and written is quite odd comparing to standard SQL or dataset. But as an overall, the API is well design and almost everything is taken care off. Do give it a try.</p> <p>PS: No doubt it's a bit slow when accessing with all the xml overhead plus plenty of redundant tagging with gdata.</p>
<p>So, I guess nobody uses google data apparently.</p> <p>It does seem nice to store data you can't afford to host yourself though. Thus I think I'll still give it a try.</p>
18,272
<p>My program works already, I have Perl (GUI Window) where I can input data, data passed to the webpage (using to Tomcat server, JSP) and then <strong>saved</strong> it to oracle database. What I want is to make search parameter (webapp) that <strong>retrieve/extract</strong> data from the Oracle database using Perl CGI. Is it possible? Or any suggestions to solve my program? Thanks!:-)</p>
<p>Yes you can by using <a href="http://search.cpan.org/dist/DBI/" rel="nofollow noreferrer">DBI</a> and <a href="http://search.cpan.org/dist/DBD-Oracle/" rel="nofollow noreferrer">DBD::Oracle</a> modules.</p> <p>However there are some gotchas with Oracle. I remember a few fun and games with Oracle 8 so these may no longer be applicable but it did require setting ENV variables like ORACLE_HOME, ORACLE_BASE &amp; ORACLE_SID in some cases. </p> <p>The DBD::Oracle doc does go into this and also mentions another ENV variable TWO_TASK. So getting it to work may depend on....</p> <ul> <li>what version of Oracle you have running</li> <li>whether you have listener up (which I think u do need for network access like CGI?)</li> <li>what version SQL*Net your using.</li> </ul> <p>Seems daunting but all you will probably need is to add these ENV variables in the webserver (iPlanet was what I was using at that time). Alternatively from the DBD::Oracle doc it gives...</p> <pre><code>BEGIN { $ENV{ORACLE_HOME} = '/home/oracle/product/10.x.x'; $ENV{TWO_TASK} = 'DB'; } $dbh = DBI-&gt;connect('dbi:Oracle:','scott', 'tiger'); # - or - $dbh = DBI-&gt;connect('dbi:Oracle:','scott/tiger'); </code></pre> <p>PS. The above assumes you are running CGI script on same server as Oracle! If not, then those ENV variables are superfluous and you can just do this (pulled from an old script of mine!)...</p> <pre><code>my $db = DBI-&gt;connect("dbi:Oracle:host=$host;sid=$database", $user, $pass, { RaiseError =&gt; 0, PrintError =&gt; 0 } ) or croak( "Unable to connect to DB - $DBI::errstr" ); </code></pre> <p>However I do recall having to tweak something like TNLISTENER.CONF on the Oracle server (this was some years ago so memory fails me a bit!) and I'm pretty sure you need to download some client Oracle library (which you can get from their site).</p>
<p>Any specific reason for the mix in technologies? Why not use a servlet/JSP?</p> <p>If you must use Perl, then you need to choose what web-server will run your Perl script.</p> <p>Normally, this would be Apache using <a href="http://perl.apache.org/" rel="nofollow noreferrer">mod_perl</a>.</p> <p>But if you only intend to use this for a few admin scripts, then you can run Perl from tomcat as outlined <a href="http://www.wellho.net/forum/Perl-Programming/Running-Perl-CGI-scripts-under-Apache-Tomcat.html" rel="nofollow noreferrer">here</a>.</p> <p>Once you have managed to get a simple perl script running, then I would look into using <a href="http://dbi.perl.org/" rel="nofollow noreferrer">DBI/DBD::Oracle</a> to access your database?</p> <p>Hope this helps...</p>
38,617
<p>We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. </p> <p>The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them.</p> <p>These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners.</p> <p>Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way.</p> <p>I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. </p> <p>What would you do for the password generator and do you think that the transmission method in place is secure enough for it?</p> <p>Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.</p>
<h3>Password Generation</h3> <p>As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML.</p> <p>Entropy is used to measure password quality. So, choosing each bit with a random "coin-flip" will give you the best quality password. You'd want passwords to be as strong as other cryptographic keys, so I'd recommend a minimum of 128 bits of entropy. </p> <p>There are two easy methods, depending on how you want to encode the password as text (which really doesn't matter from a security standpoint).</p> <p>For <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow noreferrer">Base-64</a>, use something like this:</p> <pre><code> SecureRandom rnd = new SecureRandom(); /* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */ byte[] password = new byte[18]; rnd.nextBytes(password); String encoded = Base64.encode(password); </code></pre> <p>The following doesn't require you to come up with a Base-64 encoder. The resulting encoding is not as compact (26 characters instead of 24) and the password doesn't have as much entropy. (But 130 bits is already a lot, comparable to a password of at least 30 characters chosen by a human.)</p> <pre><code>SecureRandom rnd = new SecureRandom(); /* Bit length is multiple of log2(32) = 5. */ String encoded = new BigInteger(130, rnd).toString(32); </code></pre> <p>Creating new SecureRandom objects is computationally expensive, so if you are going to generate passwords frequently, you may want to create one instance and keep it around.</p> <h3>A Better Approach</h3> <p>Embedding the password in the XML itself seems like a mistake.</p> <p>First of all, it seems like you would want to authenticate a sender before processing any documents they send you. Suppose I hate your guts, and start sending you giant XML files to execute a denial of service attack. Do you want to have to parse the XML only to find out that I'm not a legitimate partner? Wouldn't it be better if the servlet just rejected requests from unauthenticated users up front? </p> <p>Second, the passwords of your legitimate partners were protected during transmission by HTTPS, but now they are likely stored "in the clear" on your system somewhere. That's bad security.</p> <p>A better approach would be to authenticate partners when they send you a document with credentials in the HTTP request headers. If you only allow HTTPS, you can take the password out of the document completely and put it into an <a href="http://www.ietf.org/rfc/rfc2617.txt" rel="nofollow noreferrer">HTTP "Basic" authentication</a> header instead. It's secured by SSL during transmission, and not stored on your system in the clear (you only store a one-way hash for authentication purposes).</p> <p>HTTP Basic authentication is simple, widely supported, and will be much easier for you and your partners to implement than SSL client certificates.</p> <h3>Protecting Document Content</h3> <p>If the content of the documents themselves is sensitive, they really should be encrypted by the sender, and stored by you in their encrypted form. The best way to do this is with public key cryptography, but that would be a subject for another question.</p>
<p>I'm unclear why transmitting the passwords over SSL -- via HTTPS -- is being considered "insecure" by your audit team. So when you ask for two things, it seems the second -- ensuring that the passwords are being transmitted in a secure way -- is already being handled just fine.</p> <p>As for the first, we'd have to know what about the audit exposed your passwords as insecure...</p>
12,879
<p>I believe the simplest way to request data from a server in XML format is to have a PHP/JSP/ASP.net page which actually generates XML based on HTTP GET params, and to somehow call/load this page from Flex.</p> <p>How exactly can this be achieved using the Flex library classes?</p>
<p>I'd like to add that you can also use <a href="http://livedocs.adobe.com/flex/201/langref/mx/rpc/http/mxml/HTTPService.html" rel="nofollow noreferrer">mx:HTTPService</a>. If you specify the returnFormat attribute, you would get an XML document as opposed to simple text: </p> <pre><code>&lt;mx:HTTPService resultFormat="e4x" ..../&gt; or &lt;mx:HTTPService resultFormat="xml" .../&gt; </code></pre>
<p>Never mind, found it: <a href="http://livedocs.adobe.com/flex/3/langref/flash/net/URLLoader.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/langref/flash/net/URLLoader.html</a></p>
22,345
<p>I'm pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these:</p> <ul> <li>Replace all spaces at start-of-line with a non-breaking space (<code>&amp;nbsp;</code>).</li> <li>Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces.</li> <li>Single spaces which are not at start-of-line remain untouched.</li> </ul> <p>I used the <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">Regex Coach</a> to build the matching pattern:</p> <pre><code>/( ){2,}|^( )/ </code></pre> <p>Let's assume I have this input text:</p> <pre><code>asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345 </code></pre> <p>Using a PHP regular expression replace function (like <a href="http://ch.php.net/manual/en/function.preg-replace.php" rel="nofollow noreferrer"><code>preg_replace()</code></a>), I want to get this output:</p> <pre><code>asdasd asdasd&amp;amp;nbsp;&amp;amp;nbsp;asdas1 &amp;amp;nbsp;asda234 4545&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;54 &amp;amp;nbsp;&amp;amp;nbsp;34545 345&amp;amp;nbsp;&amp;amp;nbsp;34534 34 345 </code></pre> <p>I'm happy doing simple text substitutions using regular expressions, but I'm having trouble working out how to replace multiple-times inside the match in order to get the output I desire.</p>
<p>I'd guess that it would be easier to find each space and replace it. To do that, use "look-ahead" and "look-behind" groups.</p> <p>Or, find a space (<code>\x20</code>) that is either lead by or followed by any single whitespace (<code>\s</code>); but, only replace the space.</p> <pre><code>$str = "asdasd asdasd asdas1\n asda234 4545 54\n 34545 345 34534\n34 345\n"; print preg_replace("/(?&lt;=\s)\x20|\x20(?=\s)/", "&amp;#160;", $str); </code></pre> <p>(I opted for #160 since markdown parses nbsp.)</p> <p>Results in:</p> <pre><code>asdasd asdasd&amp;#160;&amp;#160;asdas1 &amp;#160;asda234 4545&amp;#160;&amp;#160;&amp;#160;&amp;#160;54 &amp;#160;&amp;#160;34545 345&amp;#160;&amp;#160;34534 34 345 </code></pre> <p>For more info, check out <a href="http://us2.php.net/pcre" rel="nofollow noreferrer">PCRE</a> and <a href="http://perldoc.perl.org/perlre.html" rel="nofollow noreferrer">perlre</a>.</p> <hr> <p><strong>reply to comments</strong></p> <p>@<a href="https://stackoverflow.com/users/7508/sprogz"><strong>Sprogz</strong></a>: At first, I thought the same. But the example shows a <code>"\n " =&gt; "\n&amp;nbsp;"</code> between the 1st and 2nd lines.</p>
<p>You can use PHP's <code>/e</code> modifier to <em>execute</em> some code in the replacement, like this:</p> <pre><code>$str = preg_replace('/( {2,}|^ )/em', 'str_repeat("&amp;nbsp;", strlen("\1"))', $str); </code></pre> <p>I've changed the regular expression to capture the spaces. The <code>/m</code> modifer puts it into multi-line mode, so <code>^</code> matches the start of any line.</p>
25,513
<p>Someone told me it's more efficient to use <code>StringBuffer</code> to concatenate strings in Java than to use the <code>+</code> operator for <code>String</code>s. What happens under the hood when you do that? What does <code>StringBuffer</code> do differently?</p>
<p>It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens:</p> <p>When you use + with two strings, it compiles code like this:</p> <pre><code>String third = first + second; </code></pre> <p>To something like this:</p> <pre><code>StringBuilder builder = new StringBuilder( first ); builder.append( second ); third = builder.toString(); </code></pre> <p>Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this:</p> <pre><code>for( String str : strings ) { out += str; } </code></pre> <p>In this case, a new <code>StringBuilder</code> instance, and a new <code>String</code> (the new value of <code>out</code> - <code>String</code>s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single <code>StringBuilder</code> means you can just produce a single <code>String</code> and not fill up the heap with <code>String</code>s you don't care about.</p>
<p>Because Strings are imutable in Java, every time you concanate a String, new object is created in memory. SpringBuffer use the same object in memory.</p>
9,136
<p>I'm building a simple Todo List application where I want to be able to have multiple lists floating around my desktop that I can label and manage tasks in.</p> <p>The relevant UIElements in my app are:</p> <p>Window1 (Window) TodoList (User Control) TodoStackCard (User Control)</p> <p>Window1 looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class=&quot;TaskHole.App.Window1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:t=&quot;clr-namespace:TaskHole.App.Controls&quot; xmlns:tcc=&quot;clr-namespace:TaskHole.CustomControls&quot; Title=&quot;Window1&quot; Width=&quot;500&quot; Height=&quot;500&quot; Background=&quot;Transparent&quot; WindowStyle=&quot;None&quot; AllowsTransparency=&quot;True&quot; &gt; &lt;Canvas Name=&quot;maincanvas&quot; Width=&quot;500&quot; Height=&quot;500&quot; VerticalAlignment=&quot;Stretch&quot; HorizontalAlignment=&quot;Stretch&quot;&gt; &lt;ResizeGrip SizeChanged=&quot;ResizeGrip_SizeChanged&quot; /&gt; &lt;t:TodoList Canvas.Top=&quot;0&quot; Canvas.Left=&quot;0&quot; MinWidth=&quot;30&quot; Width=&quot;50&quot; Height=&quot;500&quot; x:Name=&quot;todoList&quot; TaskHover=&quot;todoList_TaskHover&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Stretch&quot;/&gt; &lt;/Canvas&gt; &lt;/Window&gt; </code></pre> <p>TodoList looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;UserControl x:Class=&quot;TaskHole.App.Controls.TodoList&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:t=&quot;clr-namespace:TaskHole.App.Controls&quot; xmlns:tcc=&quot;clr-namespace:TaskHole.CustomControls&quot; Background=&quot;Transparent&quot;&gt; &lt;StackPanel VerticalAlignment=&quot;Bottom&quot; HorizontalAlignment=&quot;Stretch&quot; MinWidth=&quot;1&quot; Grid.Row=&quot;2&quot; Height=&quot;Auto&quot; AllowDrop=&quot;True&quot;&gt; &lt;ItemsControl Name=&quot;todolist&quot; ItemsSource=&quot;{Binding}&quot;&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;VirtualizingStackPanel Name=&quot;stackPanel&quot; VerticalAlignment=&quot;Bottom&quot;&gt; &lt;/VirtualizingStackPanel&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;t:TodoStackCard x:Name=&quot;card&quot; TaskHover=&quot;card_TaskHover&quot; Orientation=&quot;Vertical&quot; VerticalContentAlignment=&quot;Top&quot; /&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <p>I have multiple instances of these windows, and I want to be able to drag any of the controls between the windows. I have tried using a Thumb control and, while this works, it only allows me to drag a control around the containing canvas.</p> <p>How do I mimic the behaviour of, say, Windows Explorer, where I can drag a file outside of the application and onto another application, all the while seeing a ghosted representation of the file under the cursor.</p> <p>Can I accomplish this purely in C# and WPF? If so/if not, how?</p>
<p>You have to call DoDragDrop to initialize the Drag And Drop framework. Jaime Rodriguez provides a guide to Drag and Drop <a href="https://web.archive.org/web/20160113133757/http://blogs.msdn.com:80/b/jaimer/archive/2007/07/12/drag-drop-in-wpf-explained-end-to-end.aspx" rel="nofollow noreferrer">here</a></p>
<p>Just as an FYI, there's a big difference to "dragging controls" around, and doing what Explorer does, which is Drag and Drop, specifically with files. That's what you'll want to look up, how to do drag and drop from a WPF app to something else. You'll need something that creates a Data Object (IDataObject) or whatever they call that in WPF world, and then you need to call DoDragDrop (again, or whatever is analogous to this in WPF) to start the dragging. Doing what explorer does is also possible, put I suspect you need ot make some lower level calls to accomplish this. Take a look at <a href="http://www.codeproject.com/KB/wtl/wtl4mfc10.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/wtl/wtl4mfc10.aspx</a> to see the stuff you need ot look for. WPF may in fact wrap all this up, but if it doesn't these are some of the things you need to look into, especially IDragSourceHelper. </p>
19,149
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
<p>For a pure python module you can find the source by looking at <code>themodule.__file__</code>. The datetime module, however, is written in C, and therefore <code>datetime.__file__</code> points to a .so file (there is no <code>datetime.__file__</code> on Windows), and therefore, you can't see the source.</p> <p>If you download a python source tarball and extract it, the modules' code can be found in the <strong>Modules</strong> subdirectory.</p> <p>For example, if you want to find the datetime code for python 2.6, you can look at</p> <pre><code>Python-2.6/Modules/datetimemodule.c </code></pre> <p>You can also find the latest version of this file on github on the web at <a href="https://github.com/python/cpython/blob/main/Modules/_datetimemodule.c" rel="noreferrer">https://github.com/python/cpython/blob/main/Modules/_datetimemodule.c</a></p>
<p>as written above in python just use help(module) ie</p> <p>import fractions</p> <p>help(fractions)</p> <p>if your module, in the example fractions, is installed then it will tell you location and info about it, if its not installed it says module not available</p> <p>if its not available it doesn't come by default with python in which case you can check where you found it for download info</p>
33,903
<pre><code>public Int64 ReturnDifferenceA() { User[] arrayList; Int64 firstTicks; IList&lt;User&gt; userList; Int64 secondTicks; System.Diagnostics.Stopwatch watch; userList = Enumerable .Range(0, 1000) .Select(currentItem =&gt; new User()).ToList(); arrayList = userList.ToArray(); watch = new Stopwatch(); watch.Start(); for (Int32 loopCounter = 0; loopCounter &lt; arrayList.Count(); loopCounter++) { DoThings(arrayList[loopCounter]); } watch.Stop(); firstTicks = watch.ElapsedTicks; watch.Reset(); watch.Start(); for (Int32 loopCounter = 0; loopCounter &lt; arrayList.Count(); loopCounter++) { DoThings(arrayList[loopCounter]); } watch.Stop(); secondTicks = watch.ElapsedTicks; return firstTicks - secondTicks; } </code></pre> <p>As you can see, this is really simple. Create a list of users, force to an array, start a watch, loop the list through and call a method, stop watch. Repeat. Finish up by returning the difference from the first run and the second.</p> <p>Now I'm calling with these:</p> <pre><code>differenceList = Enumerable .Range(0, 50) .Select(currentItem =&gt; ReturnDifferenceA()).ToList(); average = differenceList.Average(); differenceListA = Enumerable .Range(0, 50) .Select(currentItem =&gt; ReturnDifferenceA()).ToList(); averageA = differenceListA.Average(); differenceListB = Enumerable .Range(0, 50) .Select(currentItem =&gt; ReturnDifferenceA()).ToList(); averageB = differenceListB.Average(); </code></pre> <p>Now the fun part is that all averages are positive by a relatively large amount, ranging from 150k to 300k ticks.</p> <p>What I don't get is that I am going through the same list, the same way, with the same method and yet there is such a difference. Is there some kind of caching going on?</p> <p>Another interesting thing is that if I iterate through the list BEFORE the first stop watch section, the averages are around 5k or so.</p>
<p>You are running in a high level language with a runtime environment that does a lot of caching and performance optimizations, this is common. Sometimes it is called warming up the virtual machine, or warming up the server (when it is a production application). </p> <p>If something is going to be done repeatedly, then you will frequently notice the first time has a larger measured runtime and the rest should level off to a smaller amount. </p> <p>I do this in MATLAB code, and see that the first time I run a benchmark loop, it takes five seconds, and subsequent times take a fifth of a second. It's a huge difference, because it is an interpreted language that required some form of compiling, but in reality, it does not affect your performance, because the great majority will be 'second time's in any production application. </p>
<p>You say you don't get that doing it 3 times, the 2nd and 3rd times are relatively close. It seems to me that it's only the first time thru the loop that things are slow.</p>
38,974
<p>What is appropriate way to integrate SpringSecurity with Capcha ? </p> <p>I have following use case : When user will tries to login, if we he failed to login N times, captcha will be displayed, so authentication will be using three parameters : username, password, captcha. But Spring Security doesn't support built in Captcha handling. </p> <p>I just start thinking about implementation. And have following variants:</p> <ul> <li>Adding separate security filter in Spring Security filter stack, </li> <li>Entirely rewrite AuthenticationProcessingFilter to support some Captcha</li> <li>Use some programmatic authentication with interception captcha logic and then transfering username and password to Spring Security</li> </ul> <p>As a Captcha implementation I think about JCaptcha, but what your thougths?</p>
<p>As an alternative to using JCaptcha, if you'd like to use the <a href="http://recaptcha.net/" rel="nofollow noreferrer">reCAPTCHA Service</a> on your site, then check out the free Section 4.4 (<a href="http://www.manning.com/wheeler/SIP_Wheeler_MEAP_ch4.pdf" rel="nofollow noreferrer">direct PDF link</a>) of the new <a href="http://www.manning.com/wheeler/" rel="nofollow noreferrer">Spring in Practice</a> book (currently in beta). </p> <p>This shows you integration with Spring MVC and Spring Validation. Since the integration is on the front-end, w/external APIs, Spring Security doesn't really come into the picture here.</p> <p>I am not sure what your use case is? Are you hoping to use captchas as an alternative to authentication to prove "human"-ness?</p>
<p><a href="http://code.google.com/p/kaptcha/wiki/HowToUse" rel="nofollow noreferrer">Kaptcha</a> is easy to use.</p>
26,730
<p>Profiling LINQ queries and their execution plans is especially important due to the crazy SQL that can sometimes be created. </p> <p>I often find that I need to track a specific query and have a hard time finding in query analyzer. I often do this on a database which has a lot of running transactions (sometimes production server) - so just opening Profiler is no good.</p> <p>I've also found tryin to use the DataContext to trace inadequate, since it doesnt give me SQL I can actually execute myself.</p> <p>My best strategy so far is to add in a 'random' number to my query, and filter for it in the trace.</p> <p>LINQ:</p> <pre><code>where o.CompletedOrderID != "59872547981" </code></pre> <p>Profiler filter:</p> <pre><code>'TextData' like '%59872547981' </code></pre> <p>This works fine with a couple caveats :</p> <ul> <li>I have to be careful to remember to remove the criteria, or pick something that wont affect the query plan too much. Yes I know leaving it in is asking for trouble.</li> <li>As far as I can tell though, even with this approach I need to start a new trace for every LINQ query I need to track. If I go to 'File > Properties' for an existing trace I cannot change the filter criteria.</li> </ul> <p>You cant beat running a query in your app and seeing it pop up in the Profiler without any extra effort. Was just hoping someone else had come up with a better way than this, or at least suggest a less 'dangerous' token to search for than a query on a column.</p>
<p>Messing with the where clause is maybe not the best thing to do since it can and will affect the execution plans for your queries.</p> <p>Do something funky with projection into anonymous classes instead - use a unique static column name or something that will not affect the execution plan. (That way you can leave it intact in production code in case you later need to do any profiling of production code...)</p> <pre><code>from someobject in dc.SomeTable where someobject.xyz = 123 select new { MyObject = someobject, QueryTraceID1234132412='boo' } </code></pre>
<p>You can have your datacontext log out the raw SQL, which you could then search for in the profiler to examine performance.</p> <pre><code>using System.Diagnostics.Debugger; yourDataContext.Log = new DebuggerWriter(); </code></pre> <p>All of your SQL queries will be displayed in the debugger output window now.</p>
40,823
<p>I've been developing modules for DNN since version 2 and back then I was able to easily able to run my module as I developed it on my environment and still easily deploy my module as a DLL. When version 4 came out and used the web site solution (rather than the Web Application solution). It seems like there was something lost. I can continue to develop in my test environment and immediately see changes as I make them, but releasing for me has become a headache.</p> <p>I mostly do my development for one site in particular have just been using FTP deployment of the modules to the main site after I was done making changes.</p> <p>I'd like to set up a good environment for multiple developers to be able to work on the module(s). </p> <p>When adding stuff to source control, are people generally putting all of DNN into source control so they can bring the whole solution down to work on, or just their module and each person needs to set up their own dev DNN environment?</p> <p>I'd like to start getting my modules projects organized so more people could work on them and I feel a bit lost for some best practices both in doing this and deploying those changes to a live site.</p>
<p>I have a few detailed blog postings about this on my blog site, <a href="http://www.mitchelsellers.com" rel="nofollow noreferrer">mitchelsellers.com</a>.</p> <p>I personally use the WAP development model and I do NOT check the DNN solution, or any core files into source control, as I do NOT modify the core for any of my clients. When working with multiple people we create a similar environment for each person, and still can work with each of our individual projects, at times we will have completely isolated dev environments with individual databases and code, at other times I have worked with a shared dev database to resolve issues with dev module installation issues.</p> <p>With the WAP model I use a method to dynamically create my installation packages on project build using a post-build event and then I have a test installation that I use to validate that the packages occur. Debugging is then done via Attach to Process.</p>
<p>I would suggest Mitchel book if you are needing some reference material - Professional Dotnetnuke Module Programming by Wrox <a href="https://rads.stackoverflow.com/amzn/click/com/0470171162" rel="nofollow noreferrer" rel="nofollow noreferrer" title="Module Programming">Module Programming - Michel Sellers</a></p>
11,266
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
<p>Focus on <code>urllib2</code> for this, it works quite well. Don't mess with <code>httplib</code>, it's not the top-level API.</p> <p>What you're noting is that <code>urllib2</code> doesn't follow the redirect.</p> <p>You need to fold in an instance of <code>HTTPRedirectHandler</code> that will catch and follow the redirects.</p> <p>Further, you may want to subclass the default <code>HTTPRedirectHandler</code> to capture information that you'll then check as part of your unit testing.</p> <pre><code>cookie_handler= urllib2.HTTPCookieProcessor( self.cookies ) redirect_handler= HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler) </code></pre> <p>You can then use this <code>opener</code> object to POST and GET, handling redirects and cookies properly.</p> <p>You may want to add your own subclass of <code>HTTPHandler</code> to capture and log various error codes, also.</p>
<p>Besides the fact that you may be missing a cookie, there might be some field(s) in the form that you are not POSTing to the webserver. The best way would be to capture the actual POST from a web browser. You can use <a href="https://addons.mozilla.org/en-US/firefox/addon/3829" rel="nofollow noreferrer">LiveHTTPHeaders</a> or <a href="http://www.wireshark.org/" rel="nofollow noreferrer">WireShark</a> to snoop the traffic and mimic the same behaviour in your script.</p>
38,752
<p>We have a system where we want to prevent the same credit card number being registered for two different accounts. As we don't store the credit card number internally - just the last four digits and expiration date - we cannot simply compare credit card numbers and expiration dates.</p> <p>Our current idea is to store a hash (SHA-1) in our system of the credit card information when the card is registered, and to compare hashes to determine if a card has been used before.</p> <p>Usually, a salt is used to avoid dictionary attacks. I assume we are vulnerable in this case, so we should probably store a salt along with the hash.</p> <p>Do you guys see any flaws in this method? Is this a standard way of solving this problem?</p>
<p>People are over thinking the design of this, I think. Use a salted, highly secure (e.g. "computationally expensive") hash like sha-256, with a per-record unique salt.</p> <p>You should do a low-cost, high accuracy check first, then do the high-cost definitive check only if that check hits.</p> <p>Step 1:</p> <p>Look for matches to the last 4 digits (and possibly also the exp. date, though there's some subtleties there that may need addressing).</p> <p>Step 2:</p> <p>If the simple check hits, use the salt, get the hash value, do the in depth check.</p> <p>The last 4 digits of the cc# are the most unique (partly because it includes the LUHN check digit as well) so the percentage of in depth checks you will do that won't ultimately match (the false positive rate) will be very, very low (a fraction of a percent), which saves you a tremendous amount of overhead relative to the naive "do the hash check every time" design.</p>
<p>Yes, comparing hashes should work fine in this case.</p>
12,877
<p>I recently installed the Eclipse Metrics Plugin and have exported the data for one of our projects.</p> <p>It's all very good having these nice graphs but I'd really like to understand more in depth what they all mean. The definitions of the metrics only go so far to telling you what it really means.</p> <p>Does anyone know of any good resources, books, websites, etc, that can help me better understand what all the data means and give an understanding of how to improve the code where necessary?</p> <p>I'm interested in things like Efferent Coupling, and Cyclomatic Complexity, etc, rather than lines of code or lines per method.</p>
<p>I don't think that code metrics (sometimes referred to as <a href="http://en.wikipedia.org/wiki/Software_metric" rel="nofollow noreferrer">software metrics</a>) provide valuable data in terms of where you can improve.</p> <p>With code metrics it is sort of nice to see how much code you write in an hour etc., but beyond they tell you nada about the quality of the code written, its documentation and code coverage. They are pretty much a week attempt to measure where you cannot really measure.</p> <p>Code metrics also discriminate the programmers who solve the harder problems because they <em>obviously</em> managed to code less. Yet they solved the hard issues and a junior programmer whipping out lots of <em>crap code</em> looks good.</p> <p>Another example for using metrics is the very popular <a href="http://en.wikipedia.org/wiki/Ohloh" rel="nofollow noreferrer">Ohloh</a>. They employ metrics to put a price tag on an opensource project (using number of lines, etc.), which in itself is an attempt which is <em>flawed as hell</em> - as you can imagine.</p> <p>Having said all that the Wikipedia entry provides some overall insight on the topic, sorry to not answer your question in a more supportive way with a really great website or book, but I bet you got the drift that I am not a huge fan. :)</p> <p>Something to employ to help you improve would be continuous integration and adhering to some sort of standard when it comes to code, documentation and so on. That is how you can improve. Metrics are just eye candy for meetings - "look we coded that much already".</p> <p><strong>Update</strong></p> <p>Ok, well my point being efferent coupling or even cyclomatic complexity can indicate something is wrong - it doesn't have to be wrong though. It can be an indicator to refactor a class but there is no rule of thumb that tells you when.</p> <p>IMHO a rule such as 500+ lines of code, refactor or the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY principal</a> are more applicable in most cases. Sometimes it's as simple as that.</p> <p>I give you that much that since cyclomatic complexity is graphed into a flow chart, it can be an eye opener. But again, use carefully.</p>
<p>In my opinion metrics are an excellent way to find pain points in your codebase. They are very useful also to show your manager why you should spend time improving it.</p> <p>This is a post I wrote about it: <a href="http://blog.jorgef.net/2011/12/metrics-in-brownfield-applications.html" rel="nofollow">http://blog.jorgef.net/2011/12/metrics-in-brownfield-applications.html</a></p> <p>I hope it helps</p>
18,818
<p>Is there a 7-Zip command-line switch that prevents the filenames from echoing to the screen as they are added to the archive?</p>
<p>Not built in, but if you add </p> <pre><code>&lt;7z command here&gt; 2&gt;&amp;1 NUL </code></pre> <p>to the end of your command-line, it will redirect all the output into the null device and stops it echoing to the screen. This is the MS-DOS equivalent of</p> <pre><code>2&gt;&amp;1 /dev/null </code></pre> <p>in Linux and Unix systems.</p>
<p>AFAIK, there is not a switch for that, but you could hide the output redirecting it to a file, for example (DOS batch):</p> <pre><code>7z.exe ... normal parameters &gt; DumpFile.txt </code></pre> <p>This way all the output ends in DumpFile.txt and not on the screen.</p>
11,925
<p>I need to model a system where by there will be a team who will consist of users who perform roles in the team and have skills assigned to them.</p> <p><em>i.e. a team A 5 members, one performs the team leader role, all perform the reply to email role, but some have an extra skill to answer the phone</em></p> <p>I'm trying to determine how I can best model this. </p> <p>This problem must have been solved before, are there any good resources on how to model this?</p> <p>EDIT: I need to determine what a user is allowed to do, which could be because they are in a certain team, perform a certain role or have been assigned a certain skill</p>
<p>I Googled this, so take it with a grain of salt. I found this <a href="http://www.riehle.org/computer-science/research/1997/ubilab-tr-1997-1-1.pdf" rel="nofollow noreferrer">paper</a> on Role Modeling and Objects. On page 30 there is a Role Pattern. Hopefully this is not a wild goose chase for you. Here is the summary</p> <blockquote> <p>The Role pattern lets you design a Component which can be extend at runtime with new Context objects, called Roles. A Component is extended with Roles according to the Context Object pattern. The Component corresponds to a Decorator’s Component, and a Role corresponds to a Context Object. State integration of a role-playing Component is achieved by applying Property and Strategy. Property is used to define the Component’s state space, and Strategy is used to provide the Property dependent behavior.</p> </blockquote>
<p>In your example I would have at least TeamMember BaseClass and 2 interfaces (iEmail and iPhone). Any new Roles will inherit from the TeamMember class, and depending on what it can do, implements the appropriate interfaces... In short, roles would be implemented as a class that inherits from TeamMember, and skills would be implemented as an interface.</p> <p>For example, Team leader is allowed to make a phone call. Then I would have TeamLeader class inherits from TeamMember and implements the iPhone interface</p> <p><a href="http://www.rwendi.com" rel="nofollow noreferrer" title="RWendi">RWendi</a></p>
24,440