instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have a site that is using x509 client certificates (2 way SSL) to authenticate users and an LDAP directory that contains authorization information. I would like to use one of the certificate attributes to query the directory ( SSL_CLIENT_S_DN_CN to be exact ). I see how to use mod_ssl to use the user's client certificates for authentication and I see how to use mod_auth_ldap and the like to use the username from basic or form based authentication to query the LDAP store for authorization. What I haven't seen a good example for is how to use an attribute of the user's client certificate in place of the username to query the LDAP. Any ideas?</p>
<p>A module exists for apache 2.2.x: <a href="http://www.urec.fr/rubrique34.html" rel="nofollow noreferrer">modXLDAPAuth</a></p>
<p>this might help: <a href="http://httpd.apache.org/docs/2.2/mod/mod_ldap.html#settingcerts" rel="nofollow noreferrer">settingcerts</a> + <a href="http://httpd.apache.org/docs/2.2/mod/mod_authnz_ldap.html#authldapurl" rel="nofollow noreferrer">mod_authnz_ldap</a> (authldapurl)</p>
24,213
<p>What's the "right" way to do the following as a boolean expression?</p> <pre><code>for i in `ls $1/resources`; do if [ $i != "database.db" ] then if [ $i != "tiles" ] then if [ $i != "map.pdf" ] then if [ $i != "map.png" ] then svn export -q $1/resources/$i ../MyProject/Resources/$i ... </code></pre>
<p>The other solutions have a couple of common mistakes: <a href="http://www.pixelbeat.org/programming/shell_script_mistakes.html" rel="nofollow noreferrer">http://www.pixelbeat.org/programming/shell_script_mistakes.html</a></p> <ol> <li><p><code>for i in $(ls ...)</code> is redundant/problematic just do: <code>for i in $1/resources*; do ...</code></p></li> <li><p><code>[ $i != file1 -a $1 != file2 ]</code> This actually has 2 problems.</p> <p>a. The <code>$i</code> is not quoted, hence names with spaces will cause issues</p> <p>b. <code>-a</code> is inefficient if <code>stat</code>ing files as it doesn't short circuit (I know the above is not <code>stat</code>ing files).</p></li> </ol> <p>So instead try:</p> <pre class="lang-bsh prettyprint-override"><code>for i in $1/resources/*; do if [ "$i" != "database.db" ] &amp;&amp; [ "$i" != "tiles" ] &amp;&amp; [ "$i" != "map.pdf" ] &amp;&amp; [ "$i" != "map.png" ]; then svn export -q "$i" "../MyProject/Resources/$(basename $i)" fi done </code></pre>
<pre><code>for i in `ls $1/resources`; do if [ $i != "database.db" ] &amp;&amp; [ $i != "tiles" ] &amp;&amp; [ $i != "map.pdf" ] &amp;&amp; [ $i != "map.png" ]; then svn export -q $1/resources/$i ../MyProject/Resources/$i </code></pre>
7,123
<p>I'm trying to create a server control, which inherits from TextBox, that will automatically have a <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx" rel="nofollow noreferrer">CalendarExtender</a> attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.</p>
<p>I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.</p> <p>In the <code>CreateChildControls</code> method of the CompositeControl I use code similar to this:</p> <pre><code>TextBox textbox = new TextBox(); textbox.ID = this.ID + "Textbox"; textbox.Text = this.EditableField.TextValue; textbox.TextChanged += new EventHandler(HandleTextboxTextChanged); textbox.Width = new Unit(100, UnitType.Pixel); CalendarExtender calExender = new CalendarExtender(); calExender.PopupButtonID = "Image1"; calExender.TargetControlID = textbox.ID; this.Controls.Add(textbox); this.Controls.Add(calExender); </code></pre> <p>Of course make sure that the form containing this CompositeControl has a toolkit script manager.</p>
<p>When you are trying to not allow users to type anything in the textbox, but only be filled by the calendar extender and then you try to get the selected date from the textbox control it may be empty string if you have set the textbox property to ReadOnly="True".</p> <p>Its because read only controls are NOT posted back to the server. Workaround for this is the following:</p> <p>protected void Page_Load(object sender, EventArgs e)</p> <p>{</p> <p>TextBox1.Attributes.Add("readonly", "readonly");</p> <p>}</p> <p>Hope it helps.</p>
10,934
<p>At my last place of employment, I used BTS quite a bit. However, I've noticed that managers often want to use it for the wrong things, and developers are hesitant to adopt it.</p> <p>So, I'm just wondering, how's BTS being used? Please post experiences, not theories. Thanks!</p>
<p>I've worked as a consultant for one the largest oil/energy companies in Europe and they basically use BizTalk for all their messaging/integration stuff. Examples are: Invoices (electronic invoices) sent from and to partners in different formats, sync jobs between AD and third party software that maintains it's own username db and integration between support system and external customers via e-mail. So they have a pretty broad adoption of BizTalk and use a cluster of 5 servers. </p>
<p>Personally have developed for: </p> <p>Procurement: handling buying request for a hospital to different manufacturing companies. These companies would have varying xml requests sent out to different companies, where each manufacture will have it's own style. All purchases then were also made into a html/xslt report (in house receipt) showing what was bought at what prices. </p> <p>HL7: Handle a huge amount of HL7 files being processed at once (think it was setup to handled 4 at a time), processed and placed into a new folder for that day. </p>
16,562
<p>Goal: Efficiently show/hide rows based on the data in the row.</p> <ol> <li>Create a helper column that determines whether or not a row should be hidden.</li> <li>Have the formula in the helper column return an error or a number.</li> <li>Hide the helper column and write code to execute the hiding/showing.</li> </ol> <p>Question: Which one of the following methods would you expect to be faster? Column B is the helper column and will always be contiguous.</p> <pre><code> Sub SetRowVisibility1() Dim rowsToCheck As Range With ActiveSheet Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown)) End With Dim needToShow As Range, needToShow_Showing As Range Dim needToHide As Range, needToHide_Showing As Range Set needToShow = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlNumbers) Set needToHide = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlErrors) On Error Resume Next Set needToShow_Showing = needToShow.Offset(0, 1).SpecialCells(xlCellTypeVisible) Set needToHide_Showing = needToHide.Offset(0, 1).SpecialCells(xlCellTypeVisible) On Error GoTo 0 If Not needToHide_Showing Is Nothing Then needToHide_Showing.EntireRow.Hidden = True End If If Not needToShow Is Nothing Then If needToShow.Count &lt;&gt; needToShow_Showing.Count Then needToShow.EntireRow.Hidden = False End If End If End Sub Sub SetRowVisibility2() Dim rowsToCheck As Range With ActiveSheet Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown)) End With Dim needToShow As Range, needToHide As Range Dim cell As Range For Each cell In rowsToCheck If IsError(cell.Value) And (cell.EntireRow.Hidden = False) Then If needToHide Is Nothing Then Set needToHide = cell Else Set needToHide = Union(needToHide, cell) End If End If If Not IsError(cell.Value) And (cell.EntireRow.Hidden = True) Then If needToShow Is Nothing Then Set needToShow = cell Else Set needToShow = Union(needToShow, cell) End If End If Next cell If Not needToHide Is Nothing Then needToHide.EntireRow.Hidden = True If Not needToShow Is Nothing Then needToShow.EntireRow.Hidden = False End Sub </code></pre>
<p>there is a different way and that is to use th auto filter feature - after all VBA has an A in it - use the features of the application wherever possible so this bit of code is pretty short and sweet - assumes that the data is a contiguous block in columns a and b and assumes no other error handling in play. the resume next line allows for the filter to be already turned on.</p> <pre>Sub showHideRange() Dim testrange testrange = Range("A1").CurrentRegion.Address On Error Resume Next testrange.AutoFilter ActiveSheet.Range(testrange).AutoFilter Field:=2, Criteria1:="show" End Sub </pre>
<p>If you do not wish to show the user what's happening, would it not be better to perform the calculation in VBA itself, rather than in a hidden column? Granted, that would seem to lock you into option 2, which I suspect is the slower option ... most of my VBA experience is in older versions of Excel, so I've not had the pleasure of working with some of the newer features, and the tasks I've done that involved processing rows of data were done row-by-row. </p> <p>I guess one possible issue with the first sub is that if there is a problem with the worksheet or the values you're using to determine hiding/showing, the process will fail. If you check row-by-row and there is a row that causes problems, you could skip over that row and process the other ones correctly.</p>
36,656
<p>I don't understand what's wrong with my G-code. I have set the printing temperature to 195 °C but when I try to print, the target temperature is always 0 °C and printing never starts.</p> <p><a href="https://i.stack.imgur.com/hkB6E.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hkB6E.jpg" alt="enter image description here" /></a></p> <p>I have tried changing material preset to different PLA profiles but that didn't help at all.</p> <p>G-code:</p> <pre><code>;FLAVOR:RepRap ;TIME:1736 ;Filament used: 0.676205m ;Layer height: 0.1 ;Generated with Cura_SteamEngine 3.4.1 T0 M190 S50 M104 S195 M109 S195 M82 ;absolute extrusion mode G21 ;metric values G90 ;absolute positioning M82 ;set extruder to absolute mode M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z15.0 F9000 ;move the platform down 15mm G92 E0 ;zero the extruded length G1 F200 E3 ;extrude 3mm of feed stock G92 E0 ;zero the extruded length again G1 F9000 M117 Print0ng... M83 ;relative extrusion mode G1 F1500 E-6.5 ;LAYER_COUNT:96 ;LAYER:0 M107 G0 F600 X90.425 Y93.152 Z0.3 ;TYPE:SKIRT G1 F1500 E6.5 ... </code></pre> <p>In addition, the extruder and heat sensor are working. An older G-code file correctly sets 200 °C as the target temperature for the extruder.</p> <p><a href="https://i.stack.imgur.com/nQhqQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nQhqQ.jpg" alt="enter image description here" /></a></p> <p>This G-code prints just fine</p> <pre><code>;FLAVOR:RepRap ;TIME:4628 ;Filament used: 1.44191m ;Layer height: 0.15 ;Generated with Cura_SteamEngine 3.4.1 T0 M190 S60 M104 S200 M109 S200 M82 ;absolute extrusion mode G21 ;metric values G90 ;absolute positioning M82 ;set extruder to absolute mode M107 ;start with the fan off G28 X0 Y0 ;move X/Y to min endstops G28 Z0 ;move Z to min endstops G1 Z15.0 F9000 ;move the platform down 15mm G92 E0 ;zero the extruded length G1 F200 E3 ;extrude 3mm of feed stock G92 E0 ;zero the extruded length again G1 F9000 M117 Print0ng... M83 ;relative extrusion mode G1 F1500 E-6.5 ;LAYER_COUNT:80 ;LAYER:0 M107 G0 F4800 X72.96 Y99.484 Z0.3 ;TYPE:SKIRT --- </code></pre> <hr /> <p><em>Note, I have never modified the firmware or changed anything except what I can change with the frontpanel.</em></p>
<p>I got the same problem today and after a lot of troubleshooting (following the answers here) I found out that the <strong>issue was the connection to the hotbed</strong>. After I clean out the connection to the hotbed the printer started working as usual. The debugging logic was that <strong>the printer heats up the hotbed <em>before</em> setting the extruder temperature</strong>.</p> <p>Looking to your LCD the issue seems to be the same, since 33 degrees is a normal ambient temperature.</p>
<p>Double check the physical connection to the heating element and the thermistor that go in the hot end. Those wires and crimps aren't great. I had one fail on me out of the box with my A8. Re-crimping did the trick.</p>
1,219
<p>I have an input String say <code>Please go to http://stackoverflow.com</code>. The url part of the String is detected and an anchor <code>&lt;a href=""&gt;&lt;/a&gt;</code> is automatically added by many browser/IDE/applications. So it becomes <code>Please go to &lt;a href='http://stackoverflow.com'&gt;http://stackoverflow.com&lt;/a&gt;</code>.</p> <p>I need to do the same using Java.</p>
<h2>Use java.net.URL for that!!</h2> <p>Hey, why don't use the core class in java for this "java.net.URL" and let it validate the URL. </p> <p>While the following code violates the golden principle "Use exception for exceptional conditions only" it does not make sense to me to try to reinvent the wheel for something that is veeery mature on the java platform.</p> <p>Here's the code:</p> <pre><code>import java.net.URL; import java.net.MalformedURLException; // Replaces URLs with html hrefs codes public class URLInString { public static void main(String[] args) { String s = args[0]; // separate input by spaces ( URLs don't have spaces ) String [] parts = s.split("\\s+"); // Attempt to convert each item into an URL. for( String item : parts ) try { URL url = new URL(item); // If possible then replace with anchor... System.out.print("&lt;a href=\"" + url + "\"&gt;"+ url + "&lt;/a&gt; " ); } catch (MalformedURLException e) { // If there was an URL that was not it!... System.out.print( item + " " ); } System.out.println(); } } </code></pre> <p>Using the following input:</p> <pre><code>"Please go to http://stackoverflow.com and then mailto:oscarreyes@wordpress.com to download a file from ftp://user:pass@someserver/someFile.txt" </code></pre> <p>Produces the following output:</p> <pre><code>Please go to &lt;a href="http://stackoverflow.com"&gt;http://stackoverflow.com&lt;/a&gt; and then &lt;a href="mailto:oscarreyes@wordpress.com"&gt;mailto:oscarreyes@wordpress.com&lt;/a&gt; to download a file from &lt;a href="ftp://user:pass@someserver/someFile.txt"&gt;ftp://user:pass@someserver/someFile.txt&lt;/a&gt; </code></pre> <p>Of course different protocols could be handled in different ways. You can get all the info with the getters of URL class, for instance </p> <pre><code> url.getProtocol(); </code></pre> <p>Or the rest of the attributes: spec, port, file, query, ref etc. etc</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/net/URL.html" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/net/URL.html</a></p> <p>Handles all the protocols ( at least all of those the java platform is aware ) and as an extra benefit, if there is any URL that java currently does not recognize and eventually gets incorporated into the URL class ( by library updating ) you'll get it transparently!</p>
<p>To detect an URL you just need this:</p> <pre><code>if (yourtextview.getText().toString().contains("www") || yourtextview.getText().toString().contains("http://"){ your code here if contains URL;} </code></pre>
36,271
<p>Inversion of Control (IoC) can be quite confusing when it is first encountered.</p> <ol> <li>What is it?</li> <li>Which problem does it solve?</li> <li>When is it appropriate to use and when not?</li> </ol>
<p>The <strong><code>Inversion-of-Control</code> (IoC)</strong> pattern, is about providing <em>any kind</em> of <code>callback</code> (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The <strong><code>Dependency-Injection</code> (DI)</strong> pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.</p> <blockquote> <p>Every <code>DI</code> implementation can be considered <code>IoC</code>, but one should not call it <code>IoC</code>, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term &quot;IoC&quot; instead).</p> </blockquote> <p>For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:</p> <pre class="lang-cs prettyprint-override"><code>public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } } </code></pre> <p>What we've done here creates a dependency between the <code>TextEditor</code> and the <code>SpellChecker</code>. In an IoC scenario we would instead do something like this:</p> <pre class="lang-cs prettyprint-override"><code>public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; } } </code></pre> <p>In the first code example we are instantiating <code>SpellChecker</code> (<code>this.checker = new SpellChecker();</code>), which means the <code>TextEditor</code> class directly depends on the <code>SpellChecker</code> class.</p> <p>In the second code example we are creating an abstraction by having the <code>SpellChecker</code> dependency class in <code>TextEditor</code>'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:</p> <pre class="lang-cs prettyprint-override"><code>SpellChecker sc = new SpellChecker(); // dependency TextEditor textEditor = new TextEditor(sc); </code></pre> <p>Now the client creating the <code>TextEditor</code> class has control over which <code>SpellChecker</code> implementation to use because we're injecting the dependency into the <code>TextEditor</code> signature.</p>
<p>Inversion of control is an indicator for a shift of responsibility in the program.</p> <p>There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.</p> <p>The smallest IoC is passing a variable by reference, lets look at non-IoC code first:</p> <pre><code>function isVarHello($var) { return ($var === &quot;Hello&quot;); } // Responsibility is within the caller $word = &quot;Hello&quot;; if (isVarHello($word)) { $word = &quot;World&quot;; } </code></pre> <p>Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:</p> <pre><code>function changeHelloToWorld(&amp;$var) { // Responsibility has been shifted to the dependency if ($var === &quot;Hello&quot;) { $var = &quot;World&quot;; } } $word = &quot;Hello&quot;; changeHelloToWorld($word); </code></pre> <hr /> <p>Here is another example using OOP:</p> <pre><code>&lt;?php class Human { private $hp = 0.5; function consume(Eatable $chunk) { // $this-&gt;chew($chunk); $chunk-&gt;unfoldEffectOn($this); } function incrementHealth() { $this-&gt;hp++; } function isHealthy() {} function getHungry() {} // ... } interface Eatable { public function unfoldEffectOn($body); } class Medicine implements Eatable { function unfoldEffectOn($human) { // The dependency is now in charge of the human. $human-&gt;incrementHealth(); $this-&gt;depleted = true; } } $human = new Human(); $medicine = new Medicine(); if (!$human-&gt;isHealthy()) { $human-&gt;consume($medicine); } var_dump($medicine); var_dump($human); </code></pre> <p><sub>*) Disclaimer: The real world human uses a message queue.</sub></p>
2,521
<p>I have a Windows forms project and a Web Service project in my solution, and I'm trying to call the web service and return a customer object as the result. The problem is that when I try to receive the return object, I get an error that it can't convert it. For example, here is the signature for my webservice:</p> <pre><code>Public Function GetDriverByID(ByVal DriverID As Integer) As Driver </code></pre> <p>And here is the code I'm using to call it:</p> <pre><code> Dim d As Driver = mywebserviceinstance.GetDriverByID(1) </code></pre> <p>But I receive this compile-time error (wsDrivers is the name of the web reference I've added to my form project): "Value of type ProjectNamespace.Common.wsDrivers.Driver cannot be converted to ProjectNamespace.Common.Driver"</p> <p>This "Common" namespace contains the Driver class, and I'm not sure why the return class from the web service isn't just a generic "Driver", but is instead a "wsDrivers.Driver", and I can't convert it back. Anybody know how I can deal with this type mismatch?</p> <p>EDIT: Thanks for the explanations - this actually makes it clear what it's doing. However, is there any way that I can force it to use the actual type instead of the proxy (or, rather, is there any way to convert between the "real" instance and the "proxy" instance), or do I have to serialize the properties before I send them over the wire, and then manually de-serialize the return values?</p>
<p>This is actually pretty common. What's happening is that the Web Service has defined in it the definitions of all the types used in the web service. When you add a reference to that web service, it auto-generates a proxy type in a sub namespace of your namespace. That is what is being returned by your web service when you call it.</p> <p>However, you probably are also referencing the same library that the web service does seperately that contains the same type. That is the type that is expected when you Dim Driver. That's why there is a mismatch.</p>
<p>The web service reference in a VB.NET or C# project can reference <em>any</em> type of web service and is not limited to those provided by ASP.NET. That is why Visual Studio creates proxy classes for each object which can be retrieved from the web service.</p>
23,457
<p>When a user logs in to my site I want a css styled button to appear (this could be anything really, i.e. some special news text item etc), how can you do this via masterpages in asp.net? Or is there some other way you do this?</p>
<p>You haven't provided a whole lot of information about your setup simon, but assuming you're using a .NET Membership Provider, then you can use a login view to have a section of your page render differently for logged in Vs. not</p> <pre><code> &lt;asp:LoginView&gt; &lt;AnonymousTemplate&gt; Nothing Displayed &lt;/AnonymousTemplate&gt; &lt;LoggedInTemplate&gt; &lt;asp:Button ID="myButton" runat="server"&gt; &lt;/LoggedInTemplate&gt; &lt;/asp:LoginView&gt; </code></pre>
<p>This MSDN article describes how you can find and manipulate master page content from a content page. </p> <p><a href="http://msdn.microsoft.com/en-us/library/xxwa0ff0(VS.85).aspx" rel="nofollow noreferrer">MSDN</a></p>
30,105
<p>This is a nut I'm cracking these days</p> <p>Application I'm working on has some advanced processing towards SQL. One of the operations selects various metadata on the objects in the current context from different tables, based on the item names in the collection. For this, a range of "select...from...where...in()" is executed, and to prevent malicious SQL code, Sql parameters are used for constructing the contents of the "in()" clause.</p> <p>However, when the item collection for constructing the "in()" clause is larger than 2100 items, this fails due to the Sql Server limitation of max 2100 Sql parameters per query.</p> <p>One approach I'm trying out now is creating a #temp table for storing all item names and then joining the table in the original query, instead of using "where in()". This has me scratching my head on how to populate the table with the item names stored in an Array in the .NET code. Surely, there has to be some bulk way to insert everything rather than issuing a separate "insert into" for each item?</p> <p>Other than that, I'm very much interested in alternative approaches for solving this issue.</p> <p>Thanks a lot</p>
<p>One potential workaround is to use the ability to query XML and simply send all the data for your 'in' as an xml column and then join on that. </p> <p>The same approach could be used to populate your temp table, but then again, why not just use it directly.</p> <p>Here's a short sample that should illustrate:</p> <pre><code>declare @wanted xml set @wanted = '&lt;ids&gt;&lt;id&gt;1&lt;/id&gt;&lt;id&gt;2&lt;/id&gt;&lt;/ids&gt;' select * from (select 1 Id union all select 3) SourceTable where Id in(select Id.value('.', 'int') from @wanted.nodes('/ids/id') as Foo(Id)) </code></pre> <p>Simply build the xml in your application and pass it as parameter.</p>
<p>For the bulk update problem: take a look at data adapter with a data table in it. You can set a parameter that allows you to insert/update the items in the table in batches, and you can choose the nr of items in a batch <a href="http://msdn.microsoft.com/en-us/library/kbbwt18a(VS.80).aspx" rel="nofollow noreferrer">MSDN article</a></p> <p>It seems like you should take a closer look at the business problem or domain to determine a better way to filter items in your query. An IN() clause may not be the best way for you to do this. Maybe adding categories of data or filters instead of a large list of items to include would be better in your case. Without knowing more aout the business problem/context, it's hard to say.</p>
20,087
<p>Is there any online service available to validate Web Service WSDL file?</p>
<p>If you're using Eclipse, just have your WSDL in a .wsdl file, eclipse will validate it automatically.</p> <p>From the <a href="http://wiki.eclipse.org/WSDL_Validator" rel="noreferrer">Doc</a></p> <blockquote> <p>The WSDL validator handles validation according to the 4 step process defined above. Steps 1 and 2 are both delegated to Apache Xerces (and XML parser). Step 3 is handled by the WSDL validator and any extension namespace validators (more on extensions below). Step 4 is handled by any declared custom validators (more on this below as well). Each step must pass in order for the next step to run.</p> </blockquote>
<p>you might want to look at the online version of <a href="http://www.w3.org/2001/03/webdata/xsv" rel="nofollow noreferrer">xsv</a></p>
18,332
<p>I guess the real question is: </p> <p>If I don't care about dirty reads, will adding the <strong>with (NOLOCK)</strong> hint to a SELECT statement affect the performance of:</p> <ol> <li>the current SELECT statement </li> <li>other transactions against the given table</li> </ol> <p>Example:</p> <pre><code>Select * from aTable with (NOLOCK) </code></pre>
<p>1) <strong>Yes</strong>, a select with <code>NOLOCK</code> will complete faster than a normal select.</p> <p>2) <strong>Yes</strong>, a select with <code>NOLOCK</code> will allow other queries against the effected table to complete faster than a normal select.</p> <p><strong>Why would this be?</strong> </p> <p><code>NOLOCK</code> typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous. </p> <p>You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a <code>NOLOCK</code> read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed. </p> <p><em>You really have no way to know what the state of the data is.</em></p> <p>If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then <code>NOLOCK</code> is a good way to boost performance for these queries and avoid having them negatively impact database performance.</p> <p><strong>Always use the <code>NOLOCK</code> hint with great caution and treat any data it returns suspiciously.</strong> </p>
<ul> <li><p>The answer is <strong>Yes</strong> if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.</p></li> <li><p><strong>Yes</strong>. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction. </p></li> </ul> <p>Be careful to <strong>only</strong> use <code>WITH (NOLOCK)</code> in SELECT statements on tables that have a clustered index.</p> <p>WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.</p> <p>The result set can contain rows that have not yet been committed, that are often later rolled back.</p> <p>If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times. </p> <p>READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.</p>
25,794
<p>What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?</p> <p>I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.</p> <p>Based on Marius and Andy's answers I'm using the following solution:</p> <pre><code>double red = (percent &lt; 50) ? 255 : 256 - (percent - 50) * 5.12; double green = (percent &gt; 50) ? 255 : percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); </code></pre> <p>Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...</p>
<p>I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:</p> <pre><code>function setColor(p){ var red = p&lt;50 ? 255 : Math.round(256 - (p-50)*5.12); var green = p&gt;50 ? 255 : Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)"; } </code></pre>
<p>Because it's R-G-B, the colors go from integer values of -1 (white), to -16777216 for black. with red green and yellow somewhere in the middle that. Yellow is actually -256, while red is -65536 and green is -16744448. So yellow actually isn't between red and green in the RGB notation. I know that in terms of wavelenghts, green is on one side, and red is on the other side of the spectrum, but I've never seen this type of notation used in computers, as the spectrum doesn't represent all visible colours.</p>
4,466
<p>Our solution has a lot of todo comments, but unfortunately it seems the only way to sort them is by file. Sorting by project would give me a much better overview of what I'm actually responsible for. Just wondering if there's any way to do this or any add-ins that provide better functionality.</p>
<p><a href="http://www.jetbrains.com/resharper/index.html" rel="noreferrer">Resharper 4.0</a> does this for you. They have a "To-do Explorer". Uses comments to find TODO, Note and Bug comments.</p> <p><strong>Edit:</strong> Here is a link to the <a href="http://www.jetbrains.com/resharper/features/navigation_search.html#To-do_Explorer" rel="noreferrer">actual feature</a>.</p>
<p>I ended up just using trusty find-in-files for <strong><code>todo:</code></strong> which can be limited to the current project or a user defined folder set. Your wallet may vary.</p>
44,399
<p>What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product?</p>
<p>I recommend the Apache License (specifically, version 2). It is not a “copy left” license and it addresses several matters that are important to established companies and their lawyers.</p> <p>“Copy left” is the philosophy of the free software foundation requiring anything incorporating the licensed opens source code to also be licensed as open source. That philosophy is regarded as poison by established companies that want to keep their products proprietary.</p> <p>Aside from not having “copy left” provisions, the Apache license specifically addresses the grant of rights from project contributors and it expressly addresses the fact that modern companies are typically made up for more than one legal entity (for example, a parent company and its subsidiaries). Most open source licenses don’t address these points.</p> <p>Whatever license you choose, if you want your code to be “corporate friendly,” in the sense that you want it to be incorporated into commercial, non-open source products, it is essential that you avoid GPL and other “copy left” type licenses. While it would be best to consult with your own lawyer before investing time or money in a project for which this is an important factor, a quick shorthand for licenses that are and are not “copy left” can be found on the Free Software Foundation’s website. They identify which licenses they don’t find meet their standards as “copy left.” The ones FSF rejects are most likely the ones that will be corporate friendly in this sense.</p> <p>(Although the question didn’t ask this, it is worth mentioning that, with very few exceptions, even GPL and other “copy left” type licenses are perfectly corporate friendly if they are only used internally by the commercial entities and not incorporated into their products.)</p>
<p>MIT, Apache and BSD tend to be the most corporate friendly. The least corporate friendly that I have ran across are usually Q Public, GPL and Mozilla...</p>
4,814
<p>We have a SQL Server table containing Company Name, Address, and Contact name (among others).</p> <p>We regularly receive data files from outside sources that require us to match up against this table. Unfortunately, the data is slightly different since it is coming from a completely different system. For example, we have "123 E. Main St." and we receive "123 East Main Street". Another example, we have "Acme, LLC" and the file contains "Acme Inc.". Another is, we have "Ed Smith" and they have "Edward Smith" </p> <p>We have a legacy system that utilizes some rather intricate and CPU intensive methods for handling these matches. Some involve pure SQL and others involve VBA code in an Access database. The current system is good but not perfect and is cumbersome and difficult to maintain </p> <p>The management here wants to expand its use. The developers who will inherit the support of the system want to replace it with a more agile solution that requires less maintenance. </p> <p>Is there a commonly accepted way for dealing with this kind of data matching?</p>
<p>Here's something I wrote for a nearly identical stack (we needed to standardize the manufacturer names for hardware and there were all sorts of variations). This is client side though (VB.Net to be exact) -- and use the Levenshtein distance algorithm (modified for better results):</p> <pre><code> Public Shared Function FindMostSimilarString(ByVal toFind As String, ByVal ParamArray stringList() As String) As String Dim bestMatch As String = "" Dim bestDistance As Integer = 1000 'Almost anything should be better than that! For Each matchCandidate As String In stringList Dim candidateDistance As Integer = LevenshteinDistance(toFind, matchCandidate) If candidateDistance &lt; bestDistance Then bestMatch = matchCandidate bestDistance = candidateDistance End If Next Return bestMatch End Function 'This will be used to determine how similar strings are. Modified from the link below... 'Fxn from: http://ca0v.terapad.com/index.cfm?fa=contentNews.newsDetails&amp;newsID=37030&amp;from=list Public Shared Function LevenshteinDistance(ByVal s As String, ByVal t As String) As Integer Dim sLength As Integer = s.Length ' length of s Dim tLength As Integer = t.Length ' length of t Dim lvCost As Integer ' cost Dim lvDistance As Integer = 0 Dim zeroCostCount As Integer = 0 Try ' Step 1 If tLength = 0 Then Return sLength ElseIf sLength = 0 Then Return tLength End If Dim lvMatrixSize As Integer = (1 + sLength) * (1 + tLength) Dim poBuffer() As Integer = New Integer(0 To lvMatrixSize - 1) {} ' fill first row For lvIndex As Integer = 0 To sLength poBuffer(lvIndex) = lvIndex Next 'fill first column For lvIndex As Integer = 1 To tLength poBuffer(lvIndex * (sLength + 1)) = lvIndex Next For lvRowIndex As Integer = 0 To sLength - 1 Dim s_i As Char = s(lvRowIndex) For lvColIndex As Integer = 0 To tLength - 1 If s_i = t(lvColIndex) Then lvCost = 0 zeroCostCount += 1 Else lvCost = 1 End If ' Step 6 Dim lvTopLeftIndex As Integer = lvColIndex * (sLength + 1) + lvRowIndex Dim lvTopLeft As Integer = poBuffer(lvTopLeftIndex) Dim lvTop As Integer = poBuffer(lvTopLeftIndex + 1) Dim lvLeft As Integer = poBuffer(lvTopLeftIndex + (sLength + 1)) lvDistance = Math.Min(lvTopLeft + lvCost, Math.Min(lvLeft, lvTop) + 1) poBuffer(lvTopLeftIndex + sLength + 2) = lvDistance Next Next Catch ex As ThreadAbortException Err.Clear() Catch ex As Exception WriteDebugMessage(Application.StartupPath , [Assembly].GetExecutingAssembly().GetName.Name.ToString, MethodBase.GetCurrentMethod.Name, Err) End Try Return lvDistance - zeroCostCount End Function </code></pre>
<p>There's quite a few ways to tackle this that may not be obvious. The best is finding unique identifiers that you can use for matching outside of the fields with mis spellings, etc.</p> <p>Some thoughts</p> <ol> <li>The obvious, Social security number, drivers license, etc</li> <li>Email address</li> <li>Cleansed phone number (Rremove punctuation, etc)</li> </ol> <p>As far as vendors go I just answered a similar question and am pasting below.</p> <p>Each major provider does have their own solution. Oracle, IBM, SAS Dataflux, etc and each claim to be the best at this kind of problem.</p> <p>Independent verified evaluation:</p> <p>There was a study done at Curtin University Centre for Data Linkage in Australia that simulated the matching of 4.4 Million records. Identified what providers had in terms of accuracy (Number of matches found vs available. Number of false matches)</p> <p><a href="http://www.dataladder.com/Products_DataMatch_Enterprise.html" rel="nofollow">DataMatch Enterprise,</a> Highest Accuracy (>95%), Very Fast, Low Cost</p> <p><a href="http://www-03.ibm.com/software/products/us/en/ibminfoqual/" rel="nofollow">IBM Quality Stage</a> , high accuracy (>90%), Very Fast, High Cost (>$100K)</p> <p>SAS Data Flux, Medium Accuracy (>85%), Fast, High Cost (>100K) That was the best independent evaluation we could find, was very thorough.</p>
15,438
<p>If you have a table with a compound primary key that is composed of a foreign key and other table columns, how do you get ASP.NET Dynamic Data to allow the non-foreign primary key table columns to be editable?</p>
<p>LINQ to SQL does not support changing the primary key of an entity even without using Dynamic Data.</p>
<p>A primary key represents the identity of an entity. It is assumed that primary key fields are never changed. Your question suggests that you might be using primary keys incorrectly.</p>
13,197
<p>I drew a fairly simple model in Google SketchUp. I exported it as an STL. I imported it into Cura and exported as gcode. Then I printed the model.</p> <p>All of the bottom layers of the model cover the entire space instead of leaving the two open gaps that should exist. I don't know why it's happening. Do I have some weird setting in Cura? </p> <p>The section that is filled, but shouldn't be, isn't a raft. I printed without a raft because my model goes to the max extent that my printer can print and I don't have room for a raft around the edges. </p> <p>Here is what it looks like in SketchUp:</p> <p><a href="https://i.stack.imgur.com/EumMr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EumMr.png" alt="SketchUp model"></a></p> <p>Here is what it looks like in Cura. The two empty areas are shaded darker than the other empty areas of the build plate. Is that an indication of my problem?</p> <p><a href="https://i.stack.imgur.com/GGgFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GGgFE.png" alt="Cura Build Plate"></a></p> <p>Here is what was printed. The empty areas are solid and filled in as if the center piece extended to the inner edges of that area. (The jacked up corners are due to the model warping a bit and no longer being in the right position for subsequent layers.)</p> <p><a href="https://i.stack.imgur.com/4nQbY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4nQbY.jpg" alt="enter image description here"></a></p> <p>Here is a video of the layers according to Cura, and Cura clearly knows the gaps should be there:</p> <p><a href="https://youtu.be/r0a9gGFerHI" rel="nofollow noreferrer">https://youtu.be/r0a9gGFerHI</a></p>
<p>I suspect, as I am wont to do, that your problem lies in the STL created by SketchUp. It's an unfortunate aspect of that program that it creates non-manifold models which creates troubles such as this. </p> <p>Consider to load your STL file into a program suitable for showing flaws (and repairing them) to determine where the failure points lie. I'm fond of Meshmixer, but there are many others such as Netfabb with which I am less familiar.</p> <p>If you don't want to check your STL file, attach it to your post and I'll take a shot at it. </p> <p>You would also want to consider to learn a new program if you intend to perform such 3D modeling. Fusion 360 has a popular following. I'm a fan of OpenScad, but use Fusion 360, Meshmixer, Blender (only a tiny amount) and anything else I can utilize for model repair, creation and editing. Build a large repetoire of different programs and get the best of all worlds.</p> <p>SketchUp has a strong following primarily because it's rather easy to use. The same can be said of a few other programs, but SketchUp really generates trouble when it comes to 3D models.</p> <p>TinkerCAD is very much like SketchUp and will give you better final results. OnShape is another popular modeling program, but I have zero exposure to that one.</p> <p>It's not out of the question that there's a bug in Cura that's causing this problem. You are not limited to one slicer program, and you can check the results of another slicer such as Slic3r, Craftware or others.</p>
<p>You have a problem with your STL file. Check the orientation of the faces of your 3D model, if that is not the problem, search for a software to fix your stl file. Just a tip, give Fusion360 a try, it is the best!</p>
758
<p>Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?</p>
<p>Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are</p> <ol> <li><p>Changes to some of the funky stuff with models, such as the syntax for following foreign keys.</p></li> <li><p>A small set of template changes, most notably auto-escaping.</p></li> <li><p>Anything that depends on the specific structure of Django's internals. This shouldn't be an issue unless you're doing stuff like dynamically modifying Django internals to change their behavior in a way that's necessary/convenient for your project.</p></li> </ol> <p>To summarize, unless you're doing a lot of really weird and/or complex stuff, a simple upgrade should be relatively painless and only require a few changes.</p>
<p>Only simplest sites are easy to upgrade.</p> <p>Expect real pain if your site happen to be for <em>non-ASCII</em> part of the world (read: anywhere outside USA and UK). The most painful change in Django was switching from bytestrings to unicode objects internally - now you have to find all places where you use bytestrings and change this to unicode. Worst case is the template rendering, you'll never know you forgot to change one variable until you get UnicodeError.</p> <p>Other notable thing: manipulators (<em>oldforms</em>) have gone and you have no other way than to rewrite all parts with forms (<em>newforms</em>).</p> <p>If this is your case and your project is larger than 2-3 apps, I'd be rather reluctant to upgrade until really necessary.</p>
15,632
<p>I got a program that writes some data to a file using a method like the one below.</p> <pre><code> public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } </code></pre> <p>When running the program I get an error:</p> <blockquote> <p>Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea bFromProxy)</p> </blockquote> <p>Question: What code do I need to catch this and how do I grant the access?</p>
<p><strong>UPDATE:</strong></p> <p>Modified the code based on <a href="https://stackoverflow.com/a/4397002/11702">this answer</a> to get rid of obsolete methods.</p> <p>You can use the Security namespace to check this:</p> <pre><code>public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { using (FileStream fstream = new FileStream(filename, FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine("sometext"); } } else { //perform some recovery action here } } </code></pre> <p>As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)</p>
<p>Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is <em>not</em> a good thing. As a developer, I cannot use the "easy way out" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.</p> <p>Like most posters of this type of question -- I initially felt it was "hackey", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.</p> <pre><code> Private Function CheckUserAccessLevel(folder As String) As Boolean Try Dim newDir As String = String.Format("{0}{1}{2}", folder, If(folder.EndsWith("\"), "", "\"), "LookWhatICanDo") Dim lookWhatICanDo = Directory.CreateDirectory(newDir) Directory.Delete(newDir) Return True Catch ex As Exception Return False End Try </code></pre> <p>End Function</p>
15,865
<p>I'm trying to find an zip compression and encryption component with <a href="http://www.networkworld.com/careers/2004/0315manonline.html" rel="noreferrer">encryption suitable for use by the US Federal Government</a>, so I can't use Zip 2.0 encryption, it has to be AES or the like. I've already found <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="noreferrer">SharpZipLib</a> (can't do AES encyrption), and <a href="http://www.chilkatsoft.com/downloads.asp" rel="noreferrer">Chilkat</a> (can do AES encryption, but costs money). Am I missing any other options?</p>
<p>How much would you be willing to pay for AES in DotNetZip? ;)</p> <p>DotNetZip supports AES Encryption, with 128 or 256-bit keys. </p> <p><a href="http://www.codeplex.com/DotNetZip" rel="noreferrer">http://www.codeplex.com/DotNetZip</a></p> <p>Example code:</p> <pre><code> using (ZipFile zip = new ZipFile()) { zip.AddFile("ReadMe.txt"); // no password for this entry // use a password for subsequent entries zip.Password= "This.Encryption.is.FIPS.197.Compliant!"; zip.Encryption= EncryptionAlgorithm.WinZipAes256; zip.AddFile("Rawdata-2008-12-18.csv"); zip.Save("Backup-AES-Encrypted.zip"); } </code></pre> <p>The AES-encrypted zip files produced by DotNetZip can be read and extracted by WinZip, and vice-versa. </p> <p>You can also just create regular zip files without encryption. </p> <p>oh, and it's free.</p>
<p>Check out this awesome article on the <a href="http://msdn.microsoft.com/en-us/magazine/cc163290.aspx" rel="nofollow noreferrer">Stream Pipeline</a>. It not only defines a cool way to link streams to each other in a multithreaded fashion, the example used is compression followed by encryption.</p>
44,253
<p>I've used <a href="http://ondras.zarovi.cz/sql/" rel="nofollow noreferrer">WWW SQL Designer</a> several times to design databases for applications. I'm now in charge of working on an application with a lot of tables (100+ mysql tables) and I would love to be able to look at the relations between tables in a manner similar to what WWW SQL Designer provides. It seems that it comes with the provisions to hook up to a database and provide a diagram of its structure, but I've not yet been able to figure out exactly how one would do that. </p>
<p><a href="http://code.google.com/p/database-diagram/" rel="nofollow noreferrer">http://code.google.com/p/database-diagram/</a></p> <p>This takes a SQL structure (SQL dump) and shows a diagram :)</p>
<p>You could use VISIO to import the database, it will diagram it for you.</p>
14,339
<p>I'm running some java processes on Windows 2003 server R2 I'm using Apache log4j-1.2.8. All my processes called via one jar file with different parameter example</p> <pre><code> java -jar process.jar one java -jar process.jar two java -jar process.jar three </code></pre> <p>And I config log4j.properties follow</p> <pre><code>#=============================== # Declare Variables #=============================== logpath=${user.dir}/log/ simple_pattern=%d{yyyy-MM-dd HH:mm:ss.SSS}%-5x - %m%n backup_pattern='.'yyyy-MM-dd #=============================== # PROCESS &amp; STANDARD OUTPUT #=============================== log4j.logger.process.Process=NULL,proclog,procstdout log4j.appender.proclog=org.apache.log4j.DailyRollingFileAppender log4j.appender.proclog.File=${logpath}process.log log4j.appender.proclog.DatePattern=${backup_pattern} log4j.appender.proclog.layout=org.apache.log4j.PatternLayout log4j.appender.proclog.layout.conversionPattern=${simple_pattern} log4j.appender.procstdout=org.apache.log4j.ConsoleAppender log4j.appender.procstdout.layout=org.apache.log4j.PatternLayout log4j.appender.procstdout.layout.ConversionPattern=${simple_pattern} #=============================== # ONE #=============================== log4j.logger.process.log.One=NULL,one log4j.appender.one=org.apache.log4j.DailyRollingFileAppender log4j.appender.one.File=${logpath}one.log log4j.appender.one.DatePattern=${backup_pattern} log4j.appender.one.layout=org.apache.log4j.PatternLayout log4j.appender.one.layout.conversionPattern=${simple_pattern} #=============================== # TWO #=============================== log4j.logger.process.log.Two=NULL,two log4j.appender.two=org.apache.log4j.DailyRollingFileAppender log4j.appender.two.File=${logpath}two.log log4j.appender.two.DatePattern=${backup_pattern} log4j.appender.two.layout=org.apache.log4j.PatternLayout log4j.appender.two.layout.conversionPattern=${simple_pattern} #=============================== # THREE #=============================== log4j.logger.process.log.Three=NULL,three log4j.appender.three=org.apache.log4j.DailyRollingFileAppender log4j.appender.three.File=${logpath}three.log log4j.appender.three.DatePattern=${backup_pattern} log4j.appender.three.layout=org.apache.log4j.PatternLayout log4j.appender.three.layout.conversionPattern=${simple_pattern} </code></pre> <p>first time I use process appender is single logger and now i separate it to ONE, TWO and THREE logger. my processes executed by windows schedule every 1 minute.</p> <p><strong>So. I got Big problem I don't know why log4j cannot generate backup files. but when I execute manual by command line It's Ok.</strong></p>
<p>Is your log4j.properties file in the classpath when executed by the scheduler? I had a similar problem in the past, and it was due to the configuration file not being in the classpath.</p> <p>You can include it in your process.jar file, or specify its location like this:</p> <blockquote> <p>java -Dlog4j.configuration=file:///path/to/log4j.properties -jar process.jar one</p> </blockquote>
<p><strong>Many thanks, I will try again for your solution.</strong></p> <p>and Now My schedule executed my processes via bgprocess.bat </p> <p><strong>bgprocess.bat</strong></p> <pre><code>@echo off set CLASSPATH=.;%CLASSPATH% set path=C:\j2sdk1.4.2\bin;%path% javaw -jar process.jar %1 </code></pre> <p><strong>process.jar manifest.mf</strong></p> <pre><code>Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.2 Created-By: 1.4.2 (IBM Corporation) Main-Class: process.Process Class-Path: ./lib/Utility.jar ./lib/DB2LibRAD.jar ./lib/rowset.jar ./l ib/log4j-1.2.8.jar ./lib/com.ibm.mq.jar . </code></pre> <p><strong>process directory</strong></p> <pre><code> - process.jar - bgprocess.bat - lib &lt;dir&gt; - log4j-1.2.8.jar - com.ibm.mq.jar - connector.jar - DB2LibRAD.jar - rowset.jar - Utility.jar - log &lt;dir&gt; - one.log - two.log - three.log - process.log </code></pre> <p>and all log files working normally but when pass backup time it will <strong>truncated</strong> and begin new log at first line.</p>
20,847
<p>I want to implement forms authentication on an ASP.NET website, the site should seek the user on the database to get some data and then authenticate against LDAP (Active Directory) to validate the user/password combo.</p> <p>After that I need to keep a instance of class that represents the user to use it in various forms.</p> <p>I tried to do it before with a login control, that checks the previous conditions and do an <code>AuthenticateEventArgs.Authenticated = true</code> and placed the object inside the session: <code>Session ["user"] = authenticatedUser;</code> but I had problem synchronizing both of them (the session expired before the auth cookie and I got NullReferenceExceptions when the pages tried to use the now defunct session object).</p> <p>Which is the best way to accomplish this? Is there some way to sync the session timeout with the cookie lifespan? The user object should be saved in any other way? Did I miss the point?</p> <p><b>UPDATE: I cannot use windows auth provider because the site should be accesible from outside out priate network. </b></p>
<p>I would use Windows Authentication as the main authentication provider, but roll my own simple database persistence for user information.</p> <p>Your session method would work, you can adjust session timeout in IIS and match it to the authentication cookie timeout.</p> <p>Also, you can do something like this in a HTTPModule to catch edge cases (app pool recycles etc) that also clear session</p> <p>Psuedocode:</p> <pre><code>if (session["user"] == null) { Authentication.SignOut(); } </code></pre> <p>This would force the user to authenticate.</p>
<p>I set the session and auth cookie timeout values to the same value. I use sliding windows for my auth cookie. I also make it a habit to never assume that values I get out of the session are non-null before attempting to use them. I often abstract all of the session functionality out into a proxy class that contains strongly typed properties for the values I store in the session. The error handling for bad session data is localized in the proxy. </p>
25,333
<p>This is related to a question I asked the other day on <a href="https://stackoverflow.com/questions/366629/how-do-i-send-an-email-message-from-my-c-application">how to send email</a>. </p> <p>My new, related question is this... what if the user of my application is behind a firewall or some other reason why the line client.Send(mail) won't work...</p> <p>After the lines:</p> <pre><code>SmtpClient client = new SmtpClient("mysmtpserver.com", myportID); client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword"); </code></pre> <p>is there something I can do to test client before I try sending? </p> <p>I thought about putting this in a try/catch loop, but I'd rather do a test and then pop up a dialog saying: can't access smtp or something like that. </p> <p>(I'm presuming that neither I, nor potentially my application user, has the ability to adjust their firewall settings. For example... they install the app at work and don't have control over their internet at work)</p> <p>-Adeena</p>
<p>I think that if you are looking to test the SMTP it's that you are looking for a way to validate your configuration and network availability without actually sending an email. Any way that's what I needed since there were no dummy email that would of made sense.</p> <p>With the suggestion of my fellow developer I came up with this solution. A small helper class with the usage below. I used it at the OnStart event of a service that sends out emails.</p> <p>Note: the credit for the TCP socket stuff goes to Peter A. Bromberg at <a href="http://www.eggheadcafe.com/articles/20030316.asp" rel="noreferrer">http://www.eggheadcafe.com/articles/20030316.asp</a> and the config read stuff to the guys here: <a href="https://stackoverflow.com/questions/625262/c-access-programatically-system-net-settings-from-app-config">Access system.net settings from app.config programmatically in C#</a></p> <p><strong>Helper:</strong></p> <pre><code>public static class SmtpHelper { /// &lt;summary&gt; /// test the smtp connection by sending a HELO command /// &lt;/summary&gt; /// &lt;param name="config"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static bool TestConnection(Configuration config) { MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; if (mailSettings == null) { throw new ConfigurationErrorsException("The system.net/mailSettings configuration section group could not be read."); } return TestConnection(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port); } /// &lt;summary&gt; /// test the smtp connection by sending a HELO command /// &lt;/summary&gt; /// &lt;param name="smtpServerAddress"&gt;&lt;/param&gt; /// &lt;param name="port"&gt;&lt;/param&gt; public static bool TestConnection(string smtpServerAddress, int port) { IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress); IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port); using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { //try to connect and test the rsponse for code 220 = success tcpSocket.Connect(endPoint); if (!CheckResponse(tcpSocket, 220)) { return false; } // send HELO and test the response for code 250 = proper response SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName())); if (!CheckResponse(tcpSocket, 250)) { return false; } // if we got here it's that we can connect to the smtp server return true; } } private static void SendData(Socket socket, string data) { byte[] dataArray = Encoding.ASCII.GetBytes(data); socket.Send(dataArray, 0, dataArray.Length, SocketFlags.None); } private static bool CheckResponse(Socket socket, int expectedCode) { while (socket.Available == 0) { System.Threading.Thread.Sleep(100); } byte[] responseArray = new byte[1024]; socket.Receive(responseArray, 0, socket.Available, SocketFlags.None); string responseData = Encoding.ASCII.GetString(responseArray); int responseCode = Convert.ToInt32(responseData.Substring(0, 3)); if (responseCode == expectedCode) { return true; } return false; } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>if (!SmtpHelper.TestConnection(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None))) { throw new ApplicationException("The smtp connection test failed"); } </code></pre>
<p>I also had this need.</p> <p><a href="https://github.com/tallesl/SMTPConnectionTester" rel="nofollow">Here's the library I made</a> (it send a <code>HELO</code> and checks for a 200, 220 or 250):</p> <pre><code>using SMTPConnectionTest; if (SMTPConnection.Ok("myhost", 25)) { // Ready to go } if (SMTPConnectionTester.Ok()) // Reads settings from &lt;smtp&gt; in .config { // Ready to go } </code></pre>
48,729
<p>We're all familiar with the pre- and post-increment operators, e.g.</p> <pre><code>c++; // c = c + 1 ++c; // ditto </code></pre> <p>and the "combined operators" which extend this principle:</p> <pre><code>c += 5; // c = c + 5 s .= ", world"; // s = s . ", world"; e.g. PHP </code></pre> <p>I've often had a need for a 'post-combined operator', which would allow:</p> <pre><code>s =. "Hello "; // s = "Hello " . s </code></pre> <p>Obviously, this is only really useful with non-commutable operators and the meaning is altered from pre-/post-increment, even though the syntax is borrowed.</p> <p>Are you aware of any language that offers such an operator, and why isn't it more common?</p>
<p>A basic objection to the example as-given is that it'd create ambiguity:</p> <pre><code>a=-5; //'a = -5' or 'a =- 5'? b=*p; //'b = *p' or 'b =* p'? c=.5; //'c = .5' or 'c =. 5'? </code></pre> <p><strong>Edit:</strong> But no, I'm not aware of any languages that use them. Presumably this is because they were omitted from C from whence most other languages derive their basic operators.</p> <p>And yeah, I'd love to see them in the languages I use.</p>
<p>None that I know about, and I don't think that there will be, as it's a meta-meta-command.</p> <p>To explain, the original operators (for numbers) came from C where they mapped directly to machine code operations. This allowed the programmer to do optimization, since the early compiler didn't.<br> So,</p> <pre><code>x=x+1; </code></pre> <p>and</p> <pre><code>x+=1; </code></pre> <p>and </p> <pre><code>x++; </code></pre> <p>would generate three different assembler outputs. </p> <p>Now, adding += for string is a meta-command. It doesn't map to an opcode, it just follows and extends the pattern.</p>
20,816
<p>I know this specific question has been <a href="https://stackoverflow.com/questions/185235/jquery-tabs-getting-newly-selected-index">asked before</a>, but I am not getting any results using the <code>bind()</code> event on the <code>jQuery UI Tabs</code> plugin. </p> <p>I just need the <code>index</code> of the newly selected tab to perform an action when the tab is clicked. <code>bind()</code> allows me to hook into the select event, but my usual method of getting the currently selected tab does not work. It returns the previously selected tab index, not the new one:</p> <pre><code>var selectedTab = $("#TabList").tabs().data("selected.tabs"); </code></pre> <p>Here is the code I am attempting to use to get the currently selected tab:</p> <pre><code>$("#TabList").bind("tabsselect", function(event, ui) { }); </code></pre> <p><strong>When I use this code, the ui object comes back <code>undefined</code></strong>. From the documentation, this should be the object I'm using to hook into the newly selected index using ui.tab. I have tried this on the initial <code>tabs()</code> call and also on its own. Am I doing something wrong here?</p>
<p>If you need to get the tab index from outside the context of a tabs event, use this:</p> <pre><code>function getSelectedTabIndex() { return $("#TabList").tabs('option', 'selected'); } </code></pre> <p>Update: From version 1.9 'selected' is changed to 'active'</p> <pre><code>$("#TabList").tabs('option', 'active') </code></pre>
<p>take a hidden variable like <code>'&lt;input type="hidden" id="sel_tab" name="sel_tab" value="" /&gt;'</code> and on each tab's onclick event write code like ...</p> <pre><code>&lt;li&gt;&lt;a href="#tabs-0" onclick="document.getElementById('sel_tab').value=0;" &gt;TAB -1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-1" onclick="document.getElementById('sel_tab').value=1;" &gt;TAB -2&lt;/a&gt;&lt;/li&gt; </code></pre> <p>you can get the value of 'sel_tab' on posted page. :) , simple !!!</p>
38,457
<pre><code>A.Event1 := nil; A.Event2 := nil; try ... finally A.Event1 := MyEvent1; A.Event2 := MyEvent2; end; </code></pre> <p>Can something go wrong with it?</p> <p><strong>EDIT:</strong></p> <p>I've accepted Barry's answer because it answered exactly what I asked, but Vegar's answer is also correct depending on the scenario, sadly I can't accept both.</p>
<p>It entirely depends on what happens in the bit of code marked '...'. If it e.g. starts up a background thread and tries to invoke Event1 or Event2 after execution has continued into the finally block, you may get unexpected results.</p> <p>If the code is entirely single-threaded, then yes, neither Event1 nor Event2 should be triggered while the code is between the try and finally.</p> <p>However, that does assume that Event1 and Event2 properties (all Delphi events are properties of a method pointer type) do not do unusual things in their setters. A pathologically malicious event setter could squirrel away a method pointer, and still be able to invoke it, even after you later call the setter with 'nil' as the value.</p> <p>But that would be highly unusual behaviour.</p>
<p>As Barry said, the only real concern is with multithreaded concerns - other than that is perfectly normal. As VCL events setters just assign the event, nothing need to be worried.</p>
41,883
<p>Are there any good MVC frameworks for native Windows Mobile code?</p> <p>Barring that could someone link to an open source Windows Mobile or CE project that uses the MVC pattern?</p>
<p>Perhaps you could try Qt. It provides some classes for mvc programming. Here is link for MVC in Qt. <a href="http://doc.trolltech.com/4.4/model-view-programming.html" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/model-view-programming.html</a></p>
<p>Inspired by akam129, this is a <a href="http://doc.trolltech.com/qq/qq10-mvc.html" rel="nofollow noreferrer">link</a> from Qt Quarterly on MVC. </p> <p>Overview: The controls in Qt are using MVC internally, and it is possible to do MVC programming at application level by using signal-slot mechanism</p>
20,815
<p>In my vb.net program, I am using a webbrowser to show the user an HTML preview. I was previously hitting a server to grab the HTML, then returning on an asynchronous thread and raising an event to populate the WebBrowser.DocumentText with the HTML string I was returning.</p> <p>Now I set it up to grab all of the information on the client, without ever having to hit the server, and I'm trying to raise the same event. I watch the code go through, and it has the HTML string correct and everything, but when I try to do</p> <pre><code>browser.DocumentText = _emailHTML </code></pre> <p>the contents of DocumentText remain as "<code>&lt;HTML&gt;&lt;/HTML&gt;</code>"</p> <p>I was just wondering why the DocumentText was not being set. Anyone have any suggestions?</p>
<p>Try the following:</p> <pre class="lang-cs prettyprint-override"><code>browser.Navigate(&quot;about:blank&quot;); HtmlDocument doc = browser.Document; doc.Write(String.Empty); browser.DocumentText = _emailHTML; </code></pre> <p>I've found that the <code>WebBrowser</code> control usually needs to be initialized to <code>about:blank</code> anyway. The same needs to be done between navigates to different types of content (like text/xml to text/html) because the renderer is different (mshtml for text/html, something else for text/xml).</p> <p><strong>See Also</strong>: <a href="https://web.archive.org/web/20200217201946/http://geekswithblogs.net/paulwhitblog/archive/2005/12/12/62961.aspx" rel="nofollow noreferrer">C# 2.0 WebBrowser control - bug in DocumentText?</a></p>
<p>please refer to this answer <a href="https://stackoverflow.com/questions/4737823/c-filenotfoundexception-on-webbrowser/4738244#4738244">c# filenotfoundexception on webbrowser?</a></p>
21,021
<p>I have a folder in NTFS that contains tens of thousands of files. I've deleted all files in that folder, save 1. I ran contig.exe to defragment that folder so now it's in 1 fragment only. However, the size of that folder is still 8MB in size. This implies that there's a lot of gap in the index. Why is that? If I delete that one file, the size of the index automatically goes to zero. My guess is because it gets collapsed into the MFT. Is there any way to get NTFS to truly defragment the index file by defragmenting it based on the content of the file? Any API that you're aware of? Contig.exe only defragment the physical file.</p>
<p>I guess this is one way in which NTFS is just like almost every other FS - none of them seem to like shrinking directories.</p> <p>So you should apply a high-tech method that involves using that advanced language, "BAT" :)</p> <p>collapse.bat</p> <pre><code>REM Invoke as "collapse dirname" ren dirname dirname.old mkdir dirname cd dirname.old move * ../dirname/ cd .. rmdir dirname.old </code></pre>
<p>There is <i>slack</i> in the index, but not a <i>gap</i>. I make the distinction to imply that there is technically wasted space, but it's not like NTFS has to parse the 8MB in order to enumerate/query/whatever the index. It knows where the root of its tree is, and it just happens to have a lot of extra allocation leftover. Probably too detailed a response, given how unhelpful it is.</p> <p>Fragmentation is likely a separate issue altogether. </p>
37,154
<p>What kinds of considerations are there for migrating an application from <strong>NHibernate</strong> 1.2 to 2.0? What are breaking changes vs. recommended changes? </p> <p>Are there mapping issues?</p>
<p><a href="http://forum.hibernate.org/viewtopic.php?t=985289" rel="noreferrer">Breaking changes in NHibernate 2.0</a></p> <p><strong>If you have good test coverage it's busywork.</strong></p> <p>Edit: We upgraded this morning. There is nothing major. You have to Flush() the session after you delete. The Expression namespace got renamed to Criterion. All these are covered in the link above. Mappings need no change. It's quite transparent. Oh, and transactions <em>everywhere</em>, but you were probably doing that already.</p> <p>By the way, here's an interesting look at the changes: <a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/08/26/nhibernate-2-0-changes-overview.aspx" rel="noreferrer">http://codebetter.com/blogs/patricksmacchia/archive/2008/08/26/nhibernate-2-0-changes-overview.aspx</a></p>
<p>I found the answer here:</p> <p><a href="http://blog.domaindotnet.com/2008/08/24/nhibernate-20-gold-released-must-wait-for-linq-to-nhibernate/" rel="nofollow noreferrer">http://blog.domaindotnet.com/2008/08/24/nhibernate-20-gold-released-must-wait-for-linq-to-nhibernate/</a></p> <h1>gold release 2.0.0.GA</h1> <h2>BREAKING CHANGES from NH1.2.1GA to NH2.0.0</h2> <ul> <li> <h2>Infrastructure</h2> <ul> <li>.NET 1.1 is no longer supported</li> <li>Nullables.NHibernate is no longer supported (use nullable types of .NET 2.0)</li> <li>Contrib moved. New Location <ul> <li><a href="http://sourceforge.net/projects/nhcontrib" rel="nofollow noreferrer">http://sourceforge.net/projects/nhcontrib</a></li> </ul> </li> </ul> </li> <li> <h2>Compile time</h2> <ul> <li>NHibernate.Expression namespace was renamed to NHibernate.Criterion</li> <li>IInterceptor have additional methods. (IsUnsaved was renamed IsTransient)</li> <li>INamingStrategy</li> <li>IType</li> <li>IEntityPersister</li> <li>IVersionType</li> <li>IBatcher</li> <li>IUserCollectionType</li> <li>IEnhancedUserType</li> <li>IPropertyAccessor</li> <li>ValueTypeType renamed to PrimitiveType</li> </ul> </li> <li> <h2>Possible Breaking Changes for external frameworks</h2> </li> </ul> <ul> <li>Various classes were moved between namespaces</li> <li>Various classes have been renamed (to match Hibernate 3.2 names)</li> <li>ISession interface have additional methods</li> <li>ICacheProvider</li> <li>ICriterion</li> <li>CriteriaQueryTranslator</li> </ul> <p><li></p> <h2>Initialization time</h2> <p></li></p> <ul> <li>&lt;nhibernate&gt; section, in App.config, is no longer supported and will be ignored. Configuration schema for configuration file and App.config is now identical, and the App.config section name is: &lt;hibernate-configuration&gt;</li> <li>&lt;hibernate-configuration&gt; have a different schema and all properties names are cheked</li> <li>configuration properties are no longer prefixed by “hibernate.”, if before you would specify “hibernate.dialect”, now you specify just “dialect”</li> <li>All named queries will be validated at initialization time, an exception will be thrown if any is not valid (can be disabled if needed)</li> <li>Stricter checks for proxying classes (all public methods must be virtual)</li> </ul> <p><li></p> <h2>Run time</h2> <ul> <li>SaveOrUpdateCopy() returns a new instance of the entity without changing the original</li> <li>AutoFlush will not occur outside a transaction - Database transactions are never optional, all communication with the database must occur inside a transaction, whatever you read or write data.</li> <li>NHibernate will return long for count(*) queries on SQL Server</li> <li>&lt;formula&gt; must contain parenthesis when needed</li> <li>These HQL function names may cause conflict in your HQL reserved names are: <ul> <li>substring</li> <li>locate</li> <li>trim</li> <li>length</li> <li>bit_length</li> <li>coalesce</li> <li>nullif</li> <li>abs</li> <li>mod</li> <li>sqrt</li> <li>upper</li> <li>lower</li> <li>cast</li> <li>extract</li> <li>concat</li> <li>current_timestamp</li> <li>sysdate</li> <li>second</li> <li>minute</li> <li>hour</li> <li>day</li> <li>month</li> <li>year</li> <li>str</li> </ul> </li> <li>&lt;any&gt; when meta-type=”class” the persistent type is a string containing the Class.FullName <ul> <li>In order to set a parameter in a query you must use SetParameter(”paraName”, typeof(YourClass).FullName, NHibernateUtil.ClassMetaType)</li> </ul> </li> </ul> <p></li> <li></p> <h2>Mapping</h2> <p></li> <li>&lt;any&gt; : default meta-type is “string” (was “class”)</li></p>
4,688
<p>I have my Wordpress install and MediaWiki <a href="https://stackoverflow.com/questions/33745" title="Thanks ceejayoz">sharing the same login information</a>. Unfortunately, users need to log into both separately, but at least they use the same credentials. </p> <p>What I would like to do is cause a successful login on the Wordpress blog to also cause a login for MediaWiki (ideally both directions). There are two ways this could happen:</p> <ol> <li>Logging in causes a login on the other application (writes the cookie and creates the session in the DB)</li> <li>Accessing an application checks for the cookie of the other and then automatically logs in.</li> </ol> <p>Since the usernames are shared it seems like the latter should be pretty easy to do. Any tips would be great. </p>
<p>The primary problem you are going to run into is that you'll have two login forms, and two logout methods. What you need to do is pick one of the login forms as the default, and redirect the other one over to it.</p> <p>I've been able to <a href="http://www.howtogeek.com" rel="nofollow noreferrer">successfully integrate</a> bbPress + MediaWiki + WordPress + WordPress MU, but I wrote a lot of custom code to do it.</p> <p>I'm using the bbPress login page as the default (and .htaccess rewrite to /login/), and then I created my own MediaWiki authentication plugin (which looks a lot like the one you are using), except my plugin checks the WordPress/bbPress cookie for the login information and automatically logs the user in.</p> <p>I created a customized /logout/ link that runs the bbPress logout, and also kills the MediaWiki cookies at the same time.</p> <p>Then the last step was to redirect all of the other logout / login links for bbpress, mediawiki, etc, over to my consolidated one. I used .htaccess rewrites for this rather than mess with core code.</p> <p>Still a work in progress, but it works fairly well.</p>
<p>You could consider some kind of single-sign-on software. I am unaware of any that are free and I've only ever used <a href="http://ca.com/us/internet-access-control.aspx" rel="nofollow noreferrer">SiteMinder</a> which is neither free nor good. <a href="http://www.atlassian.com/software/crowd/default.jsp" rel="nofollow noreferrer">Crowd</a> may be better (but is again not <a href="http://www.atlassian.com/software/crowd/pricing.jsp" rel="nofollow noreferrer">free</a>).</p>
5,800
<p>I'm using a table adapter in Visual Studio to make a query to a stored procedure in my SQL Server 2005 database. When I make the call via my website application it returns nothing. When I make the same call via SQL Server Manager it returns the expected data.</p> <p>I put a breakpoint on the call to the adapter's <code>getData</code> method and looked at all the parameters and their values and matched them in a query from server management to make sure. I'm sending the following query:</p> <pre><code>getData(string, date, date, int, int?, int?, string, int?, string) </code></pre> <p>further</p> <pre><code>getData('0000-rtg', '1/1/2007', '3/12/2008', 0, null, null, null, null, null) </code></pre> <p>I guess I'm wondering if Visual Studio does something with the <code>null</code>'s before it tries to send the query to the SQL server. If not, how do I fix this problem?</p> <p>EDIT: All these values are passed by variables, I just typed what was in those variables at that break point. </p>
<p>Use Sql Profiler to see how the sql sent to sql server actually looks like. This has helped me many times.</p>
<p>Visual Studio can be funny with query parameters. Make sure each variable has the correct length and type. For example, I use several date parameters in a query. Everytime I edit the query, Visual Studio automatically detects the date parameters and limits the variable to a length of 7. I pass the date in as "9/12/2009", which gets cut off to "9/12/20", so I need to manually change my date paramters to a length of 10.</p>
43,758
<p>Is there a risk of legal trouble if you include GPL or LGPL licensed icons in a closed source software? </p> <p>Would it force it to become open source just to include the icon?</p> <p>Does it matter if the icon is compiled as a resource?</p> <p>Are the creative common licensed icons safe to use if you follow the attribution rules specified by the license?</p>
<p>For GPL, yes. Any GPL Code/Content that's compiled into your Application or the Package will make it GPL. (Edit: What could be safe is if the Icon is a separate file and is used. That could be a grey area, as you are not using GPL Code to access it. But any attempt to embed it will force your program to GPL, it's one of the most restrictive licenses out there)</p> <p>LGPL is fine: Any modification to LGPL Content has to be released under LGPL, but using the Code/Content is safe.</p> <p>Addition: Like LGPL, CreativeCommons usually only affects the Content you're using. So if you're using a CC Icon and modify it, you will have to give out the modified item under CreativeCommons, but your Application is not affected. Just mind the "Non-Commercial" Clause if it exists.</p>
<p>It's a tricky area, at a minimum you should probably arrange for the icons to be loaded at run time so that they can be replaced with other versions, this is at least the spirit of the GPL. </p> <p>An article discusses this at <a href="http://www.linux.com/feature/119212" rel="nofollow noreferrer">http://www.linux.com/feature/119212</a></p>
7,035
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
<p>For a file <code>module.py</code>, the unit test should normally be called <code>test_module.py</code>, following Pythonic naming conventions.</p> <p>There are several commonly accepted places to put <code>test_module.py</code>:</p> <ol> <li>In the same directory as <code>module.py</code>.</li> <li>In <code>../tests/test_module.py</code> (at the same level as the code directory).</li> <li>In <code>tests/test_module.py</code> (one level under the code directory).</li> </ol> <p>I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with <code>test_</code>. Actually, the <a href="https://docs.python.org/library/unittest.html#test-discovery" rel="noreferrer">default <code>unittest</code> pattern used for test discovery is <code>test*.py</code></a>.</p>
<p>I've recently started to program in Python, so I've not really had chance to find out best practice yet. But, I've written a module that goes and finds all the tests and runs them.</p> <p>So, I have:</p> <pre> app/ appfile.py test/ appfileTest.py </pre> <p>I'll have to see how it goes as I progress to larger projects.</p>
8,627
<p>I'm looking for a tool that will be able to build a parser (in C#) if I give it a BNF grammar (eg. <a href="http://savage.net.au/SQL/sql-2003-2.bnf" rel="noreferrer">http://savage.net.au/SQL/sql-2003-2.bnf</a>)</p> <p>Does such a generator exist?</p>
<p>Normally BNF grammars are too ambiguous. ANTLR will be probably good for what you are looking for.</p>
<p>Also take a look at Irony:</p> <p><a href="http://irony.codeplex.com/" rel="nofollow">http://irony.codeplex.com/</a></p> <p>seems very promising</p>
18,539
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
<p>Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive).</p> <ul> <li><p>Python dictionaries are implemented as <strong>hash tables</strong>.</p> </li> <li><p>Hash tables must allow for <strong>hash collisions</strong> i.e. even if two distinct keys have the same hash value, the table's implementation must have a strategy to insert and retrieve the key and value pairs unambiguously.</p> </li> <li><p>Python <code>dict</code> uses <strong>open addressing</strong> to resolve hash collisions (explained below) (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l296" rel="noreferrer">dictobject.c:296-297</a>).</p> </li> <li><p>Python hash table is just a contiguous block of memory (sort of like an array, so you can do an <code>O(1)</code> lookup by index).</p> </li> <li><p><strong>Each slot in the table can store one and only one entry.</strong> This is important.</p> </li> <li><p>Each <strong>entry</strong> in the table is actually a combination of the three values: <strong>&lt; hash, key, value &gt;</strong>. This is implemented as a C struct (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l51" rel="noreferrer">dictobject.h:51-56</a>).</p> </li> <li><p>The figure below is a logical representation of a Python hash table. In the figure below, <code>0, 1, ..., i, ...</code> on the left are indices of the <strong>slots</strong> in the hash table (they are just for illustrative purposes and are not stored along with the table obviously!).</p> <pre><code> # Logical model of Python Hash table -+-----------------+ 0| &lt;hash|key|value&gt;| -+-----------------+ 1| ... | -+-----------------+ .| ... | -+-----------------+ i| ... | -+-----------------+ .| ... | -+-----------------+ n| ... | -+-----------------+ </code></pre> </li> <li><p>When a new dict is initialized it starts with 8 <em>slots</em>. (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l49" rel="noreferrer">dictobject.h:49</a>)</p> </li> <li><p>When adding entries to the table, we start with some slot, <code>i</code>, that is based on the hash of the key. CPython initially uses <code>i = hash(key) &amp; mask</code> (where <code>mask = PyDictMINSIZE - 1</code>, but that's not really important). Just note that the initial slot, <code>i</code>, that is checked depends on the <em>hash</em> of the key.</p> </li> <li><p>If that slot is empty, the entry is added to the slot (by entry, I mean, <code>&lt;hash|key|value&gt;</code>). But what if that slot is occupied!? Most likely because another entry has the same hash (hash collision!)</p> </li> <li><p>If the slot is occupied, CPython (and even PyPy) compares <strong>the hash AND the key</strong> (by compare I mean <code>==</code> comparison not the <code>is</code> comparison) of the entry in the slot against the hash and key of the current entry to be inserted (<a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l337" rel="noreferrer">dictobject.c:337,344-345</a>) respectively. If <em>both</em> match, then it thinks the entry already exists, gives up and moves on to the next entry to be inserted. If either hash or the key don't match, it starts <strong>probing</strong>.</p> </li> <li><p>Probing just means it searches the slots by slot to find an empty slot. Technically we could just go one by one, <code>i+1, i+2, ...</code> and use the first available one (that's linear probing). But for reasons explained beautifully in the comments (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l33" rel="noreferrer">dictobject.c:33-126</a>), CPython uses <strong>random probing</strong>. In random probing, the next slot is picked in a pseudo random order. The entry is added to the first empty slot. For this discussion, the actual algorithm used to pick the next slot is not really important (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l33" rel="noreferrer">dictobject.c:33-126</a> for the algorithm for probing). What is important is that the slots are probed until first empty slot is found.</p> </li> <li><p>The same thing happens for lookups, just starts with the initial slot i (where i depends on the hash of the key). If the hash and the key both don't match the entry in the slot, it starts probing, until it finds a slot with a match. If all slots are exhausted, it reports a fail.</p> </li> <li><p>BTW, the <code>dict</code> will be resized if it is two-thirds full. This avoids slowing down lookups. (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l64" rel="noreferrer">dictobject.h:64-65</a>)</p> </li> </ul> <p>NOTE: I did the research on Python Dict implementation in response to my own <a href="https://stackoverflow.com/questions/9010222/">question</a> about how multiple entries in a dict can have same hash values. I posted a slightly edited version of the response here because all the research is very relevant for this question as well.</p>
<p>Python Dictionaries use <a href="http://en.wikipedia.org/wiki/Hash_table#Open_addressing" rel="noreferrer">Open addressing</a> (<a href="http://books.google.co.in/books?id=gJrmszNHQV4C&amp;lpg=PP1&amp;hl=sv&amp;pg=PA298#v=onepage&amp;q&amp;f=false" rel="noreferrer">reference inside Beautiful code</a>)</p> <p><strong>NB!</strong> <em>Open addressing</em>, a.k.a <em>closed hashing</em> should, as noted in Wikipedia, not be confused with its opposite <em>open hashing!</em></p> <p>Open addressing means that the dict uses array slots, and when an object's primary position is taken in the dict, the object's spot is sought at a different index in the same array, using a "perturbation" scheme, where the object's hash value plays part.</p>
42,409
<p>A problem I ran into a while back I never found a good solution for...</p> <p>Say you have a working copy checked out from subversion at revision 7500, and the disk holding the current repository dies. You've got a backup of the repository at, say, revision 7450. It's easy to restore the repository backup, but any attempt to use the working copy against it gives an error saying that revision 7500 doesn't exist in the repository.</p> <p>What is the best way to check in one gigantic revision to bring the content of the repository up to match the content of the working copy and get he working copy back to a functional state?</p> <p>(Ideally I'd like something easier than having to check out a brand new working copy and then copying over all the files manually - I think at the time the working copies were used to configuration manage servers, so it was a real pain to have to check out clean working copies)</p>
<p>You could check out a rev.7450 copy somewhere, then export your 7500 copy (to remove the .svn folders). Drag the exported copy (which is the latest copy) over the 7450 copy. All the new files should simply overwrite the older ones, leaving the .svn folders the same. </p> <p>Subversion will assume you just made a bunch of changes to 7450, and the next checkin will set it as 7451.</p>
<p>If you are positive you've got the latest version in your directory, then do this:</p> <ol> <li>Delete the item from the repository</li> <li>Delete the SVN references from your copy</li> <li>Check your code in as a new copy.</li> <li>Check out the code you just checked in</li> </ol>
8,047
<p>I have had a few problems with log files growing too big on my SQL Servers (2000). Microsoft doesn't recommend using auto shrink for log files, but since it is a feature it must be useful in some scenarios. Does anyone know when is proper to use the auto shrink property?</p>
<p>Your problem is not that you need to autoshrink periodically but that you need to backup the log files periodically. (We back ours up every 15 minutes.) Backing up the database itself is not sufficient, you must do the log as well. If you do not back up the transaction log, it will grow until it takes up all the space on the drive. If you back it up, it frees the space to be reused (you will still probably need to shrink after the first backup to get the log down to a more reasonable size). If you don't need to be able torecover from transactions (which you should need to be able to do unless your entire database consists of tables that are loaded from another source and can easily be re-loaded.), then set your log to simlpe recovery mode. </p> <p>One reason why autoshrinking isn't so good an idea is that you will be growing the transaction log frequently which slows down performance. IF you back up the log, one you get to a relatively stable size (the amount of space normally used by the transaction log in the time period between backups), then the log will only need to grow occasionally if there are an unusually heavy amount fo transactions.</p>
<p>I used to use it when we had a demo version of a huge database that took up a lot of space on the laptop, so we used it to keep the size down.</p> <p>The key is to use it only when the data is basically throw away.</p> <p>You should truncate the logs periodically as a part of your backup strategy.</p>
49,435
<p>I'd like to have a custom object attached to the application so I can preserve state in it between different html pages in adobe air. Is this possible?</p> <hr> <p>I was asking for a fullblown solution to store a custom js object in memory and persist it between pages loaded from the application sandbox, but this cannot be done unless I use iframes which is not very pleasant, since I have to add a lot of stuff to the bridge. Anoter way may be to do partial rendering of the page filled with html read from files, but this exposes a lot of unpleasant bugs + you cant write script tags in the dom dynamically. It's a crippled platform.</p>
<p>Perhaps you could try attaching the object on the user's machine. There is a tutorial online that seems like it could help:</p> <p><a href="http://corlan.org/2008/09/02/storing-data-locally-in-air/" rel="nofollow noreferrer">http://corlan.org/2008/09/02/storing-data-locally-in-air/</a></p> <p>Example from the site:</p> <pre><code>//write an Object to a file private function writeObject():void { var object:Object = new Object();//create an object to store object.value = asObject.text; //set the text field value to the value property //create a file under the application storage folder var file:File = File.applicationStorageDirectory.resolvePath("myobject.file"); if (file.exists) file.deleteFile(); var fileStream:FileStream = new FileStream(); //create a file stream fileStream.open(file, FileMode.WRITE);// and open the file for write fileStream.writeObject(object);//write the object to the file fileStream.close(); } </code></pre>
<p>What sort of object ?-)</p> <p>If it only holds values that are meaningful in a string, you could store it as a cookie or perhaps in a serverside session ...</p>
23,476
<p>I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., <code>a = 5</code>, <code>b = 6</code>, <code>c = 7</code>) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate <code>S = a + b + c</code>. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.</p>
<p>This is typically not good practice in MATLAB. The file containing the input variables would, in your example, be a script. As would your main file. MATLAB does not error when running one script from another, as suggested by ScottieT812, but under certain circumstances strange errors can arise. (Run time compiling has difficulty, variable name collisions across scripts)</p> <p>A better option is to turn the inputs script into a function which returns the variables of interest</p> <pre><code>function [a,b c] = inputs a = 5; b = 6; c = 7; </code></pre> <p>Then this function can be called in the main.m script.</p> <pre><code>% main.m [a,b,c] = inputs; s = a+b+c; </code></pre>
<p>I ran into the exact problem <a href="https://stackoverflow.com/questions/185461/reading-input-m-file-in-a-main-m-file#185660">KennyMorton</a> mentioned when trying to create runtime compiled versions of MATLAB software for my work. The software uses m-files extensively for passing arguments between functions. Additionally, we create these m-files dynamically which the deployed version of MATLAB does not play nice with. Our workaround was:</p> <ul> <li>save the parameters to a file without the .m extension </li> <li>read and eval the contents of the file</li> </ul> <p>So, to follow the OPs example, in a function we would create a text file, INP, containing our parameters. We create this file in the directory returned by the <strong>ctfroot</strong> function. Then, in MAIN, we would use the following to retrieve these parameters:</p> <pre><code>eval(char(textread(fullfile(ctfroot, INP), '%s', 'whitespace', ''); </code></pre>
22,429
<p>Does anyone know if dbunit has the power to export specific data from multiple tables at once based on a sql statement, as can be done by using dbunit's QueryDataSet class to export data from a single table based on a sql statement, <a href="http://www.dbunit.org/faq.html#extract" rel="nofollow noreferrer">as can been seen here</a>.</p> <p>James</p>
<p><a href="http://jailer.sourceforge.net/" rel="noreferrer">http://jailer.sourceforge.net/</a></p>
<p>Yes it can. All you need is to call addTable(...) method to collect data to QueryDataSet and just export it by FlatXmlDataSet.write(...)</p> <pre><code>QueryDataSet partialDataSet = new QueryDataSet(connection); partialDataSet.addTable(tableName1, "select * from " + tableName1); partialDataSet.addTable(tableName2, "select * from " + tableName2); partialDataSet.addTable(tableName3, "select * from " + tableName3); FileOutputStream fos = new FileOutputStream("Noname.dataset"); FlatXmlDataSet.write(ratingDataSet, fos); </code></pre>
23,163
<p>I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:</p> <pre><code>class Enum&lt;E extends Enum&lt;E&gt;&gt; </code></pre> <p>Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.</p>
<p>It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:</p> <pre><code>public class StatusCode extends Enum&lt;StatusCode&gt; </code></pre> <p>Now if you check the constraints, we've got <code>Enum&lt;StatusCode&gt;</code> - so <code>E=StatusCode</code>. Let's check: does <code>E</code> extend <code>Enum&lt;StatusCode&gt;</code>? Yes! We're okay.</p> <p>You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that <code>Enum&lt;E&gt;</code> implements <code>Comparable&lt;E&gt;</code>. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)</p> <p>I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:</p> <pre><code>public interface IBuilder&lt;TMessage, TBuilder&gt; where TMessage : IMessage&lt;TMessage, TBuilder&gt; where TBuilder : IBuilder&lt;TMessage, TBuilder&gt; public interface IMessage&lt;TMessage, TBuilder&gt; where TMessage : IMessage&lt;TMessage, TBuilder&gt; where TBuilder : IBuilder&lt;TMessage, TBuilder&gt; </code></pre> <p>This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.</p> <p>EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the <em>right</em> case rather than protect you from the <em>wrong</em> case.</p> <p>So if <code>Enum</code> weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types:</p> <pre><code>public class First extends Enum&lt;First&gt; {} public class Second extends Enum&lt;First&gt; {} </code></pre> <p><code>Second</code> would implement <code>Comparable&lt;First&gt;</code> rather than <code>Comparable&lt;Second&gt;</code>... but <code>First</code> itself would be fine.</p>
<p>According to wikipedia, this pattern is called <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">Curiously recurring template pattern</a>. Basically, by using the CRTP pattern, we can easily refer to subclass type without type casting, which means by using the pattern, we can imitate virtual function. </p>
25,934
<p>There's a <a href="http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/8e0235d58c8635c2" rel="noreferrer" title="assertions: does it matter that they are disabled in production?">discussion</a> going on over at comp.lang.c++.moderated about whether or not assertions, which in C++ only exist in debug builds by default, should be kept in production code or not.</p> <p>Obviously, each project is unique, so my question here is <strong>not</strong> so much <strong>whether</strong> assertions should be kept, <strong>but in which cases</strong> this is recommendable/not a good idea.</p> <p>By assertion, I mean:</p> <ul> <li>A run-time check that tests a condition which, when false, reveals a bug in the software.</li> <li>A mechanism by which the program is halted (maybe after really minimal clean-up work).</li> </ul> <p>I'm not necessarily talking about C or C++.</p> <p>My own opinion is that if you're the programmer, but don't own the data (which is the case with most commercial desktop applications), you should keep them on, because a failing asssertion shows a bug, and you should not go on with a bug, with the risk of corrupting the user's data. This forces you to test strongly before you ship, and makes bugs more visible, thus easier to spot and fix.</p> <p>What's your opinion/experience?</p> <p>Cheers,</p> <p>Carl</p> <p>See related question <a href="https://stackoverflow.com/questions/419406/are-assertions-good">here</a></p> <hr> <p><strong>Responses and Updates</strong></p> <p>Hey Graham,</p> <blockquote> <p>An assertion is error, pure and simple and therefore should be handled like one. Since an error should be handled in release mode then you don't really need assertions.</p> </blockquote> <p>That's why I prefer the word "bug" when talking about assertions. It makes things much clearer. To me, the word "error" is too vague. A missing file is an error, not a bug, and the program should deal with it. Trying to dereference a null pointer is a bug, and the program should acknowledge that something smells like bad cheese.</p> <p>Hence, you should test the pointer with an assertion, but the presence of the file with normal error-handling code.</p> <hr> <p>Slight off-topic, but an important point in the discussion.</p> <p>As a heads-up, if your assertions break into the debugger when they fail, why not. But there are plenty of reasons a file could not exist that are completely outside of the control of your code: read/write rights, disk full, USB device unplugged, etc. Since you don't have control over it, I feel assertions are not the right way to deal with that.</p> <p>Carl</p> <hr> <p>Thomas,</p> <p>Yes, I have Code Complete, and must say I strongly disagree with that particular advice.</p> <p>Say your custom memory allocator screws up, and zeroes a chunk of memory that is still used by some other object. I happens to zero a pointer that this object dereferences regularly, and one of the invariants is that this pointer is never null, and you have a couple of assertions to make sure it stays that way. What do you do if the pointer suddenly is null. You just if() around it, hoping that it works?</p> <p>Remember, we're talking about product code here, so there's no breaking into the debugger and inspecting the local state. This is a real bug on the user's machine.</p> <p>Carl</p>
<p>Assertions are comments that do not become outdated. They document which theoretical states are intended, and which states should not occur. If code is changed so states allowed change, the developer is soon informed and needs to update the assertion.</p>
<p>An assertion is error, pure and simple and therefore should be handled like one.</p> <p>Since an error should be handled in release mode then you don't really need assertions.</p> <p>The main benefit I see for assertions is a conditional break - they are much easier to setup than drilling through VC's windows to setup something that takes 1 line of code.</p>
3,832
<p>My main application for my 3D printer (Zortrax M200 Plus) is making 28 mm scale miniatures for role-playing games. Basically people and animals at 1:60 scale, which means that things like arms, legs, or weapons are only a few millimeters thick. If I use the automatically generated supports of the Z-Suite software, the supports end up being thicker than the model parts, and are impossible to remove.</p> <p>I had a bit more luck creating support structures with Meshmixer, but am not totally happy with those. So I am looking for other software to edit .STL files to add supports automatically, preferably with an option to edit those support structures easily afterwards. Any ideas?</p> <p>Note that Zortrax printers only work with proprietary Z-Suite software, so the software that adds the support also needs to be able to export the model with the supports into an STL file, not just gcode.</p>
<p>I see that you've already tried <a href="http://www.meshmixer.com/download.html" rel="nofollow noreferrer" title="Meshmixer - Free Download">Meshmixer</a> and didn't find it helpful, but I wanted to call out <a href="https://www.prusaprinters.org/how-to-create-custom-overhang-supports-in-meshmixer/" rel="nofollow noreferrer" title="How to Create Custom Overhang Supports in Meshmixer - Prusa Blog">an article and accompanying video</a> that I recently found which helped me understand Meshmixer's support generation feature a bit better. It isn't magic, but it is pretty flexible and you can customize them. Plus, you can export them either as a separate file (to be imported via Slic3r's Load Part for example), or as part of the primary object STL file (though you loose the ability to set different print settings for the supports). Much of my printer's time is also devoted to 28mm figurines and I've had varied success with them. There are some models whose detail is too fine and which require too much support to be worth it considering the cleanup - I have a bucket-of-shame that's full of them. I just ordered an upgrade for my printer to allow me to print with multiple filament and I'll be seeing if <a href="https://www.prusaprinters.org/printing-soluble-interface-supports-prusa-i3-mk2-multi-material/" rel="nofollow noreferrer" title="Printing Soluble Interface Supports with Prusa i3 MK2 Multi Material - Prusa Blog">soluble support material</a> is helpful for those small details. Barring that, I've found that some prints do better with Meshmixer's supports while others do better with simplify3d supports, while others still do better with slic3r supports. </p> <p>Summarizing the <a href="https://www.prusaprinters.org/how-to-create-custom-overhang-supports-in-meshmixer/" rel="nofollow noreferrer" title="How to Create Custom Overhang Supports in Meshmixer - Prusa Blog">article</a> on custom Meshmixer supports:</p> <blockquote> <ol> <li>Open your model in Meshmixer</li> <li>From the top menu select View – Show Printer Bed</li> <li>Select Edit – Transform and move the model to the middle of the print bed <ul> <li>This step is important because Meshmixer won’t generate any supports outside of the print area</li> </ul></li> <li>If you want to print the model on a different scale, scale the model now, again by using the Edit – Transform. It’s better to scale the model now, because an additional change of scale later in slicer would also affect the generated supports, resulting in either too thin and weak supports or too thick and hard to remove supports. <ul> <li>Change the Scale X (Scale Y and Scale Z) to the desired value (1 = 100%, 1.5 = 150% etc.)</li> </ul></li> <li>Select Analysis – Overhangs <ul> <li>You can now adjust the Angle Thresh and see a live preview of areas of the model that should be supported</li> </ul></li> <li>Click on Generate Support to see a preview of the support structure <ul> <li>Every time you make changes to the support settings you’ll have to click on Remove Support and Generate Support to refresh the view</li> </ul></li> </ol> </blockquote> <p>(The <a href="https://www.youtube.com/watch?v=OXFKVmMwXCQ&amp;feature=youtu.be" rel="nofollow noreferrer" title="How to create custom supports in Meshmixer - YouTube">video</a> in the article goes into greater detail on the settings available in step 6.)</p> <blockquote> <ol start="7"> <li>Adding and removing supports manually <ul> <li>You can create a new support by left-clicking and dragging from an overhang to the ground or from an existing support to the ground</li> <li>Hold down the Shift key to ignore intersections of the support strut or any other warning and force Meshmixer to generate the new support (use wisely)</li> <li>You can also click on an existing support to generate a new strut going down to the build plate</li> <li>CTRL + Left click on an existing support to remove it</li> </ul></li> <li>When you’re happy with the support structure you can export the model and the support structure together as STL by simply clicking Done and clicking on the Export button in the left menu</li> <li>Alternatively, you can select Convert to Solid to create a separate mesh from the support structure. This will let you set different settings in Slic3r for the supports and for the model itself <ol> <li>After choosing Convert to Solid choose Edit – Separate shells</li> <li>Export both the model and the supports as individual STL files</li> <li>In Slic3r first load the STL with the model</li> <li>Double-click on the model and choose Load part…, select the supports STL file</li> <li>When the STL loads, you can overwrite some of the settings by clicking on the green plus icon</li> </ol></li> </ol> </blockquote>
<p>I had good experience with the support interfaces from CURA. But reduce the thickness of the support interface to be just enough, that a smooth support interface top can be printed and set the top distance so that the model itself can be printed smooth and you can remove the interface easy enough. (I got good results with a thickness of 2-4 layers and a distance of 1-2 layers. Important: the real filament thickness should be set in CURA very precisely, else it could lead to hard to remove interface or a not smooth bottom of the model. </p>
897
<p>I have built a 3D printer from parts. It is using a standard 12V power supply, an Arduino Mega 2560 replica and a RAMPS 1.4 board. The hotend cooling fan is connected to the 12V-AUX pin (the one right next to the x axis stepper driver) on the RAMPS board so that it continuously receives power as long as the machine is turned on. The printer is controlled by the Marlin firmware.</p> <p>When I give power to the board, the cooling fan starts spinning with a lot of noise. It sounds like it is receiving a higher amount of current than it should. Moreover, the noise is not steady, but fluctuates slightly. After about 30 seconds, it gets slightly quieter; after about 40-50 seconds, there is a sudden break. From then on, the fan spins quietly and regularly.</p> <p>According to measurements with a multimeter, the power supply is keeping a constant and correct voltage of slightly over 12V right from the beginning. Hence, I suspect the issue is somewhere on the RAMPS board.</p> <p>I am worried about this being more than a problem of unpleasant noisiness. What could be the cause and is there more to worry about?</p> <p>You can listen to a recording of the sound: <a href="https://soundcloud.com/user-769347820/3d-printer-hotend-cooling-fan-noise/s-OizCr" rel="nofollow noreferrer">3D printer hotend cooling fan noise</a></p> <p>Note that I am not talking about a fan for cooling the extruded plastic, but the one sitting on the extruder heatsink.</p> <hr> <p>Shutting down the printer (even literally unplugging the power supply) and plugging it back in does not lead to the startup noise appearing again. Only when waiting for multiple minutes before reconnecting does it happen again.</p> <p>The voltage to the fan is measured to be constant. The current, on the other hand, correlates with the sounds heard. It starts at 110 - 115 mA. When the fan is quiet, it is at about 90 mA.</p>
<p>Now that you have done some measurements, you could make some conclusions.</p> <blockquote> <p>The voltage over the fan is reported to be constant, but the current starts at 110-115 mA and reduces to 90 mA over time.</p> </blockquote> <p>With limited knowledge of electronics you can conclude that the resistance of the fan is not constant as the resistance determines the amount of current through the fan. So the fan resistance increases over time. This could just be a manufacturing problem or characteristics of the fan. You could try to replace the fan with another fan to see if this fixes your problem.</p>
<p>I propose examining the current voltage of the motor and the arm. The fluctuation of voltage causes the noise.</p>
962
<p>Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?</p> <p>The same question applies to VB6, C++ and other native Windows applications.</p>
<p>Personally, I build my own mechanism to kick off self update process when my application timestamp is out of sync with the server. Not too difficult, but it's not a simple task.</p> <p>By the way, for Delphi you can use some thirdparty help:</p> <p><a href="http://www.tmssoftware.com/site/wupdate.asp" rel="nofollow noreferrer">http://www.tmssoftware.com/site/wupdate.asp</a></p> <p>UPDATED:</p> <p>For my implementation:</p> <p>MyApp.EXE will run in 3 different modes</p> <ol> <li><p>MyApp.EXE without any argument. This will start the application typically.</p> <p>1.1 The very first thing it does is to validate its own file-time with the server.</p> <p>1.2 If update is required then it will download the updated file to the file named "MyApp-YYYY-MM-DD-HH-MM-SS.exe"</p> <p>1.3 Then it invoke "MyApp-YYYY-MM-DD-HH-MM-SS.exe" with command argument </p> <pre><code>MyApp-YYYY-MM-DD-HH-MM-SS.exe --update MyApp.EXE </code></pre> <p>1.4 Terminate this application.</p> <p>1.5 If there is no update required then the application will start normally from 1.1</p></li> <li><p>MyApp.EXE --update "FILENAME".</p> <p>2.1 Try copying itself to "FILENAME" every 100ms until success.</p> <p>2.2 Invoke "FILENAME" when it success</p> <p>2.3 Invoke "FILNAME --delete MyApp-YYYY-MM-DD-HH-MM-SS.exe" to delete itself.</p> <p>2.4 Terminate</p></li> <li><p>MyApp.EXE --delete "FILENAME"</p> <p>3.1 Try deleting the file "FILENAME" every 500ms until success.</p> <p>3.2 Terminate</p></li> </ol> <p>I've already been using this scheme for my application for 7 years and it works well. It could be quite painful to debug when things goes wrong since the steps involve many processes. I suggest you make a lot of trace logging to allow simpler trouble-shooting.</p> <p>Good Luck</p>
<p>I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:</p> <p><a href="http://blogs.msdn.com/g/archive/2008/06/06/sample-demonstrating-clickonce-deployment-of-com-component-implemented-in-managed-assembly-without-using-gac-or-registry-and-without-requiring-admin-rights.aspx" rel="nofollow noreferrer">How To: ClickOnce deployment for unmanaged app with COM component in managed assembly </a></p>
7,489
<p>I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive.</p> <p>Any ideas?</p>
<p>Well, the brute force solution is to attempt to initiate a connection with the database on each server. That will tell you whether it's running, though you could have timeout issues.</p> <p>The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and find out if the SQL server process is running.</p>
<p>I would certainly go with Vincent's answer. Just make absolutely certain you are closing and disposing the tcp connections properly etc. WMI seems a bit of overkill to me if that is all you're after.</p>
4,297
<p>If I am storing the Subversion user names and passwords for repository access in a text file in the <code>conf</code> folder, what is the maximum length of the passwords I can use? That is to say, how long can the secrets in the following file be?</p> <pre><code>[users] harry = harryssecret sally = sallyssecret </code></pre>
<p>If you are using <code>svnserve</code>, it seems to be no limit defined (at least I couldn't find any mention of it). From <a href="http://svnbook.red-bean.com/" rel="nofollow noreferrer">svn book</a>:</p> <blockquote> <p>The svnserve server, by default, knows only how to send a CRAM-MD5 authentication challenge. In essence, the server sends a small amount of data to the client. The client uses the MD5 hash algorithm to create a fingerprint of the data and password combined, and then sends the fingerprint as a response. The server performs the same computation with the stored password to verify that the result is identical. At no point does the actual password travel over the network.</p> </blockquote> <p>IMHO, if MD5 is used then you can use any manageable length for the password.</p>
<p>There's no limit in the config file (aside from memory constraints, of course!).</p> <p>Whether the client limits the input or not will depend on which client you're using, of course, but I'd hope that all of them would allow fairly long passwords.</p>
44,652
<p>I need to edit an xml file using javascript. Now I'm involved in a project of online testing. </p> <p>The question.xml file is already in the project folder.</p> <p>In that i want to add or edit the questions(only using javascript). I'm able to bring the particular content through ajax, but I am not able to edit the file.</p>
<p>Javascript can't write to a file. The best you'll be able to do is get Javascript to read and edit the XML then post that data to a server-side script to write to file.</p>
<p>Nickf is correct. The reason Javascript can't write to a file is because it is a <a href="http://en.wikipedia.org/wiki/Client-side_scripting" rel="nofollow noreferrer">Client-Side</a> language. Javascript will never have permission to write a file because it has to operate inside the browser sandbox. </p> <p>You will need to use a server-side script (.NET, PHP, ColdFusion, etc) to write the file.</p>
44,116
<p>A Y-combinator is a computer science concept from the &ldquo;functional&rdquo; side of things. Most programmers don't know much at all about combinators, if they've even heard about them.</p> <ul> <li>What is a Y-combinator?</li> <li>How do combinators work?</li> <li>What are they good for?</li> <li>Are they useful in procedural languages?</li> </ul>
<p>If you're ready for a long read, <a href="http://mvanier.livejournal.com/2897.html" rel="noreferrer">Mike Vanier has a <em>great</em> explanation</a>. Long story short, it allows you to implement recursion in a language that doesn't necessarily support it natively.</p>
<p>I think the best way to answer this is to pick a language, like JavaScript:</p> <pre><code>function factorial(num) { // If the number is less than 0, reject it. if (num &lt; 0) { return -1; } // If the number is 0, its factorial is 1. else if (num == 0) { return 1; } // Otherwise, call this recursive procedure again. else { return (num * factorial(num - 1)); } } </code></pre> <p>Now rewrite it so that it doesn't use the name of the function inside the function, but still calls it recursively.</p> <p>The only place the function name <code>factorial</code> should be seen is at the call site.</p> <p>Hint: you can't use names of functions, but you can use names of parameters.</p> <p>Work the problem. Don't look it up. Once you solve it, you will understand what problem the y-combinator solves.</p>
11,904
<p>I'm getting ready to implement a source control system (subversion) but I'm facing some doubts on how to structure my folders.</p> <p>I use Delphi for all my development and compile the projects from within the IDE.</p> <p>My current projects folder structure is as follows:</p> <pre> -E:\Work\1. Shared --Forms (shared forms across all projects) --Units (shared units/classes across all projects including 3rd party like JCL) -E:\Work\2. Company Name --Admin (stuff related with admin work like a license keys generator, Windows CGI to handle order processing automatically, all developed in Delphi) --Projects ----ProjectA -----5.x (version 5.x) ------BIN (where all the binaries for this project go) ------Build Manager (where the FinalBuilder project lives) -------Install (NSIS file that create the setup.exe) -------Protection (Project files to protect the compiled exe) -------Update (inf files related with the auto-update) ------Docs (where the readme.txt, license.txt and history.txt that are included in the setup file are) -------Defects (docs for any testing done by me or others) -------HTMLHelp (html help for the project) ------R&D (where screenshots, design ideas and other R&D stuff goes to) ------Releases (when building a release with FinalBuilder the setup file created by nsis is placed here) ------Resources (Images and other resources used by this project) ------Source (if a sub-project exists it will compile to BIN since they are all related) -------SubprojectA -------SubprojectB -------SubprojectC --Sites --- companywebsite.com (the only one at the moment but if we decide to have individual web sites for products they would all be placed on the Sites folder) </pre> <p>The sign "-" marks directories.</p> <p>Anyone cares to comment about the current structure or has any suggestions to improve it?</p> <p>Thanks!</p>
<p>Having setup literally hundreds of projects over the years, and having specialized in software configuration management and release engineering, I would recommend that you first focus on how you want to build/release your project(s).</p> <p>If you only use an IDE to build (compile and package) your project(s), then you might as well just follow the conventions typical for that IDE, plus any "best practices" you may find.</p> <p>However, I would strongly recommend that you do not build only with an IDE, or even at all. Instead, create an automated build/release script using one or more of the many wonderful open-source tools available. Since you appear to be targeting Windows, I recommend starting with a look at Ant, Ivy, and the appropriate xUnit (jUnit for Java, nUnit for .NET, etc.) for testing.</p> <p>Once you start down that path, you will find lots of advice regarding project structure, designing your build scripts, testing, etc. Rather than overwhelm you with detailed advice now, I will simply leave you with that suggestion--you will readily find answers to your question there, as well as find a whole lot more questions worth investigating.</p> <p>Enjoy!</p> <p>Based on comments, it seems that some detail is needed.</p> <p>A particular recommendation that I would make is that you separate your codebase into individual subprojects that each produce a single deliverable. The main application (.EXE) should be one, any supporting binaries would each be separate projects, the installer would be a separate project, etc.</p> <p>Each project produces a single primary deliverable: an .EXE, a .DLL, a .HLP, etc. That deliverable is "published" to a single, shared, local, output directory.</p> <p>Make a directory tree where the subprojects are peers (no depth or hierarchy, because it does not help), and do NOT let projects "reach" into each other's subtree--each project should be completely independent, with dependencies ONLY on the primary deliverables of the other subprojects, referenced in the shared output directory.</p> <p>Do NOT create a hierarchy of build scripts that invoke each other, I did and found that it does not add value but does exponentially increase the maintenance effort. Instead, make a continuous integration script that invokes your stand-alone build script, but first does a clean checkout into a temporary directory.</p> <p>Do NOT commit any deliverables or dependencies into source control--not your build output, not the libraries that you use, etc. Use Ivy against a Maven-like binary repository that you deploy separate from source control, and publish your own deliverables to it for sharing within your organization.</p> <p>Oh, and don't use Maven--it is too complicated, obfuscates the build process, and therefore is not cost-effective to customize.</p> <p>I am moving towards SCons, BuildBot, Ant, Ivy, nAnt, etc. based on my target platform.</p> <p>I have been composing a whitepaper on this topic, which I see may have an audience.</p> <p>EDIT: Please see my detailed answer to <a href="https://stackoverflow.com/questions/222827/how-do-you-organize-your-version-control-repository#304036">How do you organize your version control repository?</a></p>
<p>why the 5.x? (under projectA)</p> <p>I don't think it is useful to introduce the versions in the tree - that is what subversion, etc is for. </p>
37,931
<p>I'm using Grails to send a large number of HTML emails. I use the SimpleTemplateEngine to create my email bodies in this fashion:</p> <pre><code>def ccIdToEmailMap = [:] def emailTemplateFile = Utilities.retrieveFile("email${File.separator}emailTemplate.gtpl") def engine = new SimpleTemplateEngine() def clientContacts = ClientContact.list() for(ClientContact cc in clientContactList) { def binding = [clientContact : cc] //STOPS (FREEZES) EITHER HERE OR.... def template = template = engine.createTemplate(emailTemplateFile).make(binding) //OR STOPS (FREEZES) HERE def body = template.toString() def email = [text: body, to: cc.emailAddress] ccIdToEmailMap.put(cc.id, email) println "added to map" } return ccIdToEmailMap </code></pre> <p>Here is the template I'm trying to render for each email body:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Happy Holidays from google Partners&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table width="492" cellpadding="0" cellspacing="0" style="border:2px solid #acacac;margin:8px auto;" align="center"&gt; &lt;tr&gt; &lt;td colspan="5" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/cardbg.gif" width="492" height="10" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgl.gif" width="6" height="453" border="0"&gt;&lt;/td&gt; &lt;td style="background:#fff;border:1px solid #acacac;padding:2px;" width="228"&gt; &lt;div style="width:208px;margin:4px 8px 0px 8px; color:#515151;"&gt; &lt;font face="Times New Roman" size="2"&gt; &lt;span style="font:14px 'Times New Roman',times,serif;"&gt;Static text that is the same for each email &lt;br&gt;&amp;nbsp;&lt;br&gt; More text &lt;br&gt;&amp;nbsp;&lt;br&gt; We wish you health and happiness during the holidays and a year of growth in 2009. &lt;/span&gt; &lt;/font&gt; &lt;/div&gt; &lt;/td&gt; &lt;td style="background:#c9f4fe;border-top:1px solid #acacac;border-bottom:1px solid #acacac;" width="5"&gt;&lt;img src="http://www.google.com/holiday2008/vertbg.gif" border="0" height="453" width="5"&gt;&lt;/td&gt; &lt;td width="247" style="background:#fff;border:1px solid #acacac;"&gt;&lt;img src="http://www.google.com/holiday2008/snowing.gif" width="247" height="453" border="0"&gt;&lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="453" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="38" border="0"&gt;&lt;/td&gt; &lt;td colspan="3" style="border:1px solid #acacac;" align="center"&gt;&lt;img src="http://www.google.com/holiday2008/happyholidays.gif" width="480" height="38" alt="Happy Holidays" border="0"&gt;&lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="38" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="120" border="0"&gt;&lt;/td&gt; &lt;td colspan="3" style="background-color#fff;border:1px solid #acacac;padding:2px;" valign="top"&gt; &lt;img src="http://www.google.com/holiday2008/gogl_logo_card.gif" width="140" height="40" alt="google partners" border="0" align="right" hspace="4" vspace="4" /&gt; &lt;font face="Times New Roman" size="2"&gt; &lt;div style="padding:4px;font:12pt 'Times New Roman',serif;color:#515151;"&gt; &lt;span style="font-size:10pt"&gt;&lt;i&gt;from:&lt;/i&gt;&lt;/span&gt; &lt;div style="padding:2px 4px;"&gt; &lt;% clientContact.owners.eachWithIndex { it, i -&gt; %&gt; &lt;% if(i &lt; (clientContact.owners.size() - 1)) { %&gt; ${it.toString()}, &lt;% }else { %&gt; ${it.toString()} &lt;% } %&gt; &lt;% } %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/font&gt; &lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="120" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="5" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/cardbg.gif" width="492" height="10" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Once this methods returns the ccIdToEmail map, I send out all of my emails. For some reason, preparing this map of clientContactIds and email bodies causes my application to freeze at either of the two lines listed above. I can successfully prepare/send ~140 emails before it freezes. This happens very consistently.</p> <p>Does anyone know why this would work but then stop working after a ~140 email bodies are created from a template? I haven't been able to find anything online about other peope having trouble with this.</p> <p>Andrew</p>
<p>Sounds like a synchronization issue. As a first step, you should create the template outside of the loop. Since there is no need to recreate the template every time.</p> <pre><code> def ccIdToEmailMap = [:] def emailTemplateFile = Utilities.retrieveFile("email${File.separator}emailTemplate.gtpl") def engine = new SimpleTemplateEngine() def template = engine.createTemplate(emailTemplateFile) def clientContacts = ClientContact.list() for(ClientContact cc in clientContactList) { def binding = [clientContact : cc] def body = template.make(binding).toString() def email = [text: body, to: cc.emailAddress] ccIdToEmailMap.put(cc.id, email) println "added to map" } return ccIdToEmailMap </code></pre> <p>If it doesn't help, it might help if you'd post the template content and/or the source of ClientContact.</p> <p>hth, Sigi</p>
<p>Sounds like a synchronization issue. As a first step, you should create the template outside of the loop. Since there is no need to recreate the template every time.</p> <pre><code> def ccIdToEmailMap = [:] def emailTemplateFile = Utilities.retrieveFile("email${File.separator}emailTemplate.gtpl") def engine = new SimpleTemplateEngine() def template = engine.createTemplate(emailTemplateFile) def clientContacts = ClientContact.list() for(ClientContact cc in clientContactList) { def binding = [clientContact : cc] def body = template.make(binding).toString() def email = [text: body, to: cc.emailAddress] ccIdToEmailMap.put(cc.id, email) println "added to map" } return ccIdToEmailMap </code></pre> <p>If it doesn't help, it might help if you'd post the template content and/or the source of ClientContact.</p> <p>hth, Sigi</p>
48,356
<p>We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files. </p> <p>This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.</p> <p>What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?</p>
<p>In my main project (a RAD framework using PHP with gettext for translations) we're doing already alot of prepare operations on javascript files like merging and minifying them. Within this preperations we parse for gettext-markers and replace them with the language specific text.</p> <p>The result get save as javascript file and normal included into the html.</p> <pre><code>&lt;script scr="var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js"&gt;&lt;/script&gt; </code></pre> <p>The filename contains Locale and a hash value for caching.</p> <p>Date and money values get always converted from system format to Locale format on output and visa versa for input.</p>
<p>To deal with il8n in our applications we dynamically create a JavaScript file (based on the locale we are interested in), that contains keys and translations, e.g.</p> <pre><code>LOCALISATIONS = { 'util.date.day.long': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 'util.date.day.short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ... }; </code></pre> <p>and other JavaScript code will use this object to get translated text.</p>
23,227
<p>In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs. My question is: how do I fix this in the smallest possible manner?</p>
<p>You could use generics:</p> <pre><code>DAO&lt;SpecificDTO&gt; dao = new SpecificDAO(); dao.save(new SpecificDTO()); etc. </code></pre> <p>Your DAO class would look like:</p> <pre><code>interface DAO&lt;T extends DTO&gt; { void save(T); } class SpecificDAO implements DAO&lt;SpecificDTO&gt; { void save(SpecificDTO) { // implementation. } // etc. } </code></pre> <p>SpecificDTO would extend or implement DTO.</p>
<p>Refactoring to generics is no small amount of pain (even though it's most likely worth it).</p> <p>This will be especially horrendous if code uses your DTO interface like so:</p> <pre><code>DTO user = userDAO.getById(45); ((UserDTO)user).setEmail(newEmail) userDAO.update(user); </code></pre> <p>I've seen this done (in much more subtle ways).</p> <p>You could do this:</p> <pre><code>public DeprecatedDAO implements DAO { public void save(DTO dto) { logger.warn("Use type-specific calls from now on", new Exception()); } } public UserDAO extends DeprecatedDAO { @Deprecated public void save(DTO dto) { super.save(dto); save((UserDTO)dto); } public void save(UserDTO dto) { // do whatever you do to save the object } } </code></pre> <p>This is not a <em>great</em> solution, but might be easier to implement; your legacy code should still work, but it will produce warnings and stack traces to help you hunt them down, and you have a type-safe implementation as well.</p>
25,807
<p>I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine. </p> <p>Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing. </p> <p>Is there any way to see debug output from GraphBuilder when it assembles a graph?</p> <p>Is there a way to dump a working graph to see how it was put together?</p> <p>Any other ideas for unraveling the mystery that lives in the DirectShow box?</p> <p>Thanks! -Z</p>
<p>You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...</p> <p>In order to find your graph in the list, you have to register it in the running object table:</p> <pre><code>void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister ) { IMoniker* pMoniker; IRunningObjectTable* pROT; GetRunningObjectTable( 0, &amp;pROT ); WCHAR wsz[256]; swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() ); CreateItemMoniker( L"!", wsz, &amp;pMoniker ); pROT-&gt;Register( 0, pUnkGraph, pMoniker, pdwRegister ); // Clean up any COM stuff here ... } </code></pre> <p>After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke</p>
<p>Older versions of DirectX, I belive 9a, but not 9b had a "debug mode" for dshow. It would output logs of debug info into the debug console. </p> <p>So download an older version, set it to debug. then open up debugview or load graphedt.exe in visual studio to see the debug info.</p>
4,748
<p>Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.</p> <p>What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?</p> <p>Does LINQ simplify the solution?</p>
<p>On MS SQL Server 2005 and above, <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="noreferrer">ROW_NUMBER()</a> seems to work:</p> <p><a href="http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx" rel="noreferrer">T-SQL: Paging with ROW_NUMBER()</a></p> <pre><code>DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; </code></pre>
<p>There is a discussion about this <a href="https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml" rel="nofollow noreferrer">Here</a></p> <p>The technique gets page number 100,000 from a 150,000 line database in 78ms</p> <blockquote> <p>Using optimizer knowledge and SET ROWCOUNT, the first EmployeeID in the page that is requested is stored in a local variable for a starting point. Next, SET ROWCOUNT to the maximum number of records that is requested in @maximumRows. This allows paging the result set in a much more efficient manner. Using this method also takes advantage of pre-existing indexes on the table as it goes directly to the base table and not to a locally created table. </p> </blockquote> <p>I am afraid I am not able to judge if it is better than the current accepted answer.</p>
3,141
<p>Lately I'm having some issues with white PLA.</p> <p>It sticks nicely to the print bed, but the very last layer of the print comes out really ugly.</p> <p>I'm not a native english speaker, I don't know what is the proper term to describe what I see, so I'm attaching two pictures instead:</p> <p><a href="https://i.stack.imgur.com/4A8Gn.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/4A8Gn.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/76KNF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/76KNF.jpg" alt="enter image description here"></a></p> <p>As you can see, the surface has wrinkles. If you touch it, it feels like a <a href="https://i.stack.imgur.com/ab7vc.jpg" rel="noreferrer">jaggled surface</a>. What is causing this? I've never had this kind of issue before with the same PLA roll, what can be the issue?</p> <p>I have a prusa-style printer, 45°C printbed, 225°C hotend, 10% hexagonal infill, 30mm/s print speed. The object stays on the surface without warping, I can tell for sure that it isn't detaching from the bed and coming up towards the extruder.</p> <p>It happens only for infill, perimeters are just perfect.</p> <p>What can be the issue here?</p>
<p>This appears to be the result of your hot end (nozzle) temperature being slightly too high. </p> <p>I'd recommend lowering your nozzle temperature by a few degrees and retrying the print. If the quality improves you're good. If it doesn't improve significantly try lowering a few degrees more. </p> <p>If you lower the nozzle temperature to the point that you start having other adverse effects, try going back to the lowest temperature that works and check your infill and shell settings. The top shell of your part may be too thin given the span (top surface, maximum travel length). i.e. the strands being printed on the top of your part are sagging between your infil hex's, by thickening this part in the slicer settings the next layer on the roof won't sag as much as the previous.</p> <p>By increasing your number of shells or shell thickness (or roof thickness, i'm not sure on the exact terminology) you could effectively hide the effect you're seeing by thickening this section of your part. </p> <p>Best guess though is nozzle is a bit too hot.</p>
<p>This looks like the air trapped inside the print is expanding, causing wavy surfaces. This can be solved by lowering nozzle temperatures, and turning on the fan.</p>
559
<p>Would it suppose any difference regarding overhead to write an import loading all the types within one package (<code>import java.*</code>); than just a specific type (i.e. <code>import java.lang.ClassLoader</code>)? Would the second one be a more advisable way to use than the other one?</p>
<p>There is not a performance or overhead cost to doing import .* vs importing specific types. However, I consider it to be a best practice to never use import .* My primary reason for this is I just like to keep things straightward, clean and with as little ambiguity as possible, and I think with a .* import you lose that.</p>
<p>It's more of a good coding practice as anyone reading your code will immediately know what classes are used by a particular class by just looking at the import block at the top of the file whereas one would have to dig to find out if you used wildcards.</p>
22,698
<p>I want to show first element that is hidden by jquery. my html code is:</p> <pre><code>&lt;ol&gt; &lt;li&gt;1&lt;/li&gt; &lt;li style="display:none"&gt;2&lt;/li&gt; &lt;li style="display:none"&gt;3&lt;/li&gt; &lt;li style="display:none"&gt;4&lt;/li&gt; &lt;li style="display:none"&gt;5&lt;/li&gt; &lt;li&gt;&lt;a class="add"&gt;Add More ...&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I want to show first hidden LI, each time that "a" element was clicked. My solution is below. but I think better way exists.</p> <pre><code>$("a.add").click(function(){ var hiddens=$(":hidden",$(this).parent().parent()); if (hiddens.length&gt;0) { hiddens.each(function(index,el){ if(index==0) { $(this).slideToggle("fast"); } }); } if (hiddens.length==1) { $(this).parent().hide(); } </code></pre> <p>Tanx</p>
<p>Just add a :first selector after you get :hidden set so you get the first element from set found by :hidden selector</p> <pre><code>$("a.add").click(function(){ $(":hidden:first").slideToggle("fast"); }); </code></pre>
<p>Thank You "aether": I found below solutions after your answer:</p> <pre><code>$(":hidden:eq(0)",$(this).parent().parent()) </code></pre> <p>OR</p> <pre><code>$(":hidden:lt(1)",$(this).parent().parent()) </code></pre>
47,825
<p>I'm trying to setup Spring using Hibernate and JPA, but when trying to persist an object, nothing seems to be added to the database.</p> <p>Am using the following:</p> <pre><code>&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="url" value="${jdbc.url}"/&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}"/&gt; &lt;property name="username" value="${jdbc.username}"/&gt; &lt;property name="password" value="${jdbc.password}"/&gt; &lt;/bean&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="BankingWeb" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="databasePlatform" value="${hibernate.dialect}" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;tx:annotation-driven/&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt; &lt;/bean&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/&gt; &lt;bean name="accountManager" class="ssel.banking.dao.jpa.AccountManager" /&gt; &lt;bean name="userManager" class="ssel.banking.dao.jpa.UserManager" /&gt; </code></pre> <p>And in AccountManager, I'm doing:</p> <pre><code>@Repository public class AccountManager implements IAccountManager { @PersistenceContext private EntityManager em; /* -- 8&lt; -- Query methods omitted -- 8&lt; -- */ public Account storeAccount(Account ac) { ac = em.merge(ac); em.persist(ac); return ac; } } </code></pre> <p>Where ac comes from:</p> <pre><code> Account ac = new Account(); ac.setId(mostRecent.getId()+1); ac.setUser(user); ac.setName(accName); ac.setDate(new Date()); ac.setValue(0); ac = accountManager.storeAccount(ac); return ac; </code></pre> <p>Is there anyone who can point out what I'm doing wrong? The persist call returns without throwing exceptions. If afterwards I do <code>em.contains(ac)</code>, this returns true.</p> <p>In case anyone needed, here's how Account is defined:</p> <pre><code>@SuppressWarnings("serial") @Entity @NamedQueries({ @NamedQuery(name = "Account.AllAccounts", query = "SELECT a FROM Account a"), @NamedQuery(name = "Account.Accounts4User", query = "SELECT a FROM Account a WHERE user=:user"), @NamedQuery(name = "Account.Account4Name", query = "SELECT a FROM Account a WHERE name=:name"), @NamedQuery(name = "Account.MaxId", query = "SELECT MAX(a.id) FROM Account a"), @NamedQuery(name = "Account.Account4Id", query = "SELECT a FROM Account a WHERE id=:id"), }) public class Account extends AbstractNamedDomain { @Temporal(TemporalType.DATE) @Column(name = "xdate") private Date date; private double value; @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name="userid") private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) @OrderBy("date") private List&lt;AccountActivity&gt; accountActivity = new ArrayList&lt;AccountActivity&gt;(); public List&lt;AccountActivity&gt; getAccountActivity() { return accountActivity; } public void setAccountActivity(List&lt;AccountActivity&gt; accountActivity) { this.accountActivity = accountActivity; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public void addAccountActivity(AccountActivity activity) { // Make sure ordering is maintained, JPA only does this on loading int i = 0; while (i &lt; getAccountActivity().size()) { if (getAccountActivity().get(i).getDate().compareTo(activity.getDate()) &lt;= 0) break; i++; } getAccountActivity().add(i, activity); } } @MappedSuperclass public abstract class AbstractNamedDomain extends AbstractDomain { private String name; public AbstractNamedDomain() { } public AbstractNamedDomain(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @MappedSuperclass public abstract class AbstractDomain implements Serializable { @Id @GeneratedValue private long id = NEW_ID; public static long NEW_ID = -1; public long getId() { return id; } public void setId(long id) { this.id = id; } public boolean isNew() { return id==NEW_ID; } } </code></pre>
<p>Thanks to eric and Juan Manuel's answers, I was able to figure out that the transaction wasn't committed.</p> <p>Adding @Transactional to the storeAccount method did the trick!</p>
<p>Probably you're keeping the transaction active and it is not calling "commit" until other methods running supporting the active transaction end (all "voting" for commit and none for rollback.)</p> <p>If you're sure that the entity you're going to persist is ok you could probably do this:</p> <pre><code>@TransactionManagement(TransactionManagementType.BEAN) public class AccountManager implements IAccountManager { ..} </code></pre> <p>and manage your entity persistance adding:</p> <pre><code>@Resource private SessionContext sessionContext; public Account storeAccount(Account ac) { sessionContext.getUserTransaction().begin(); ac = em.merge(ac); em.persist(ac); sessionContext.getUserTransaction().commit(); return ac; } </code></pre>
49,042
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.ietf.org/rfc/rfc3339.txt" rel="noreferrer">RFC 3339</a> formatted string representation and/or parse this string representation back to a <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> structure? The RFC-3339 date-time format is used in a number of specifications such as the <a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs" rel="noreferrer">Atom Syndication Format</a>.</p>
<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).</p> <pre><code>using System; using System.Globalization; namespace DateTimeConsoleApplication { /// &lt;summary&gt; /// Provides methods for converting &lt;see cref="DateTime"/&gt; structures to and from the equivalent RFC 3339 string representation. /// &lt;/summary&gt; public static class Rfc3339DateTime { //============================================================ // Private members //============================================================ #region Private Members /// &lt;summary&gt; /// Private member to hold array of formats that RFC 3339 date-time representations conform to. /// &lt;/summary&gt; private static string[] formats = new string[0]; /// &lt;summary&gt; /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format. /// &lt;/summary&gt; private const string format = "yyyy-MM-dd'T'HH:mm:ss.fffK"; #endregion //============================================================ // Public Properties //============================================================ #region Rfc3339DateTimeFormat /// &lt;summary&gt; /// Gets the custom format specifier that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 3339 format. /// &lt;/summary&gt; /// &lt;value&gt;A &lt;i&gt;DateTime format string&lt;/i&gt; that may be used to represent a &lt;see cref="DateTime"/&gt; in the RFC 3339 format.&lt;/value&gt; /// &lt;remarks&gt; /// &lt;para&gt; /// This method returns a string representation of a &lt;see cref="DateTime"/&gt; that /// is precise to the three most significant digits of the seconds fraction; that is, it represents /// the milliseconds in a date and time value. The &lt;see cref="Rfc3339DateTimeFormat"/&gt; is a valid /// date-time format string for use in the &lt;see cref="DateTime.ToString(String, IFormatProvider)"/&gt; method. /// &lt;/para&gt; /// &lt;/remarks&gt; public static string Rfc3339DateTimeFormat { get { return format; } } #endregion #region Rfc3339DateTimePatterns /// &lt;summary&gt; /// Gets an array of the expected formats for RFC 3339 date-time string representations. /// &lt;/summary&gt; /// &lt;value&gt; /// An array of the expected formats for RFC 3339 date-time string representations /// that may used in the &lt;see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/&gt; method. /// &lt;/value&gt; public static string[] Rfc3339DateTimePatterns { get { if (formats.Length &gt; 0) { return formats; } else { formats = new string[11]; // Rfc3339DateTimePatterns formats[0] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; formats[1] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK"; formats[2] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK"; formats[3] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK"; formats[4] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"; formats[5] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK"; formats[6] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK"; formats[7] = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"; // Fall back patterns formats[8] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern; formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern; return formats; } } } #endregion //============================================================ // Public Methods //============================================================ #region Parse(string s) /// &lt;summary&gt; /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent. /// &lt;/summary&gt; /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt; /// &lt;returns&gt;A &lt;see cref="DateTime"/&gt; equivalent to the date and time contained in &lt;paramref name="s"/&gt;.&lt;/returns&gt; /// &lt;remarks&gt; /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object. /// &lt;/remarks&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="s"/&gt; is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic).&lt;/exception&gt; /// &lt;exception cref="FormatException"&gt;&lt;paramref name="s"/&gt; does not contain a valid RFC 3339 string representation of a date and time.&lt;/exception&gt; public static DateTime Parse(string s) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ if(s == null) { throw new ArgumentNullException("s"); } DateTime result; if (Rfc3339DateTime.TryParse(s, out result)) { return result; } else { throw new FormatException(String.Format(null, "{0} is not a valid RFC 3339 string representation of a date and time.", s)); } } #endregion #region ToString(DateTime utcDateTime) /// &lt;summary&gt; /// Converts the value of the specified &lt;see cref="DateTime"/&gt; object to its equivalent string representation. /// &lt;/summary&gt; /// &lt;param name="utcDateTime"&gt;The Coordinated Universal Time (UTC) &lt;see cref="DateTime"/&gt; to convert.&lt;/param&gt; /// &lt;returns&gt;A RFC 3339 string representation of the value of the &lt;paramref name="utcDateTime"/&gt;.&lt;/returns&gt; /// &lt;remarks&gt; /// &lt;para&gt; /// This method returns a string representation of the &lt;paramref name="utcDateTime"/&gt; that /// is precise to the three most significant digits of the seconds fraction; that is, it represents /// the milliseconds in a date and time value. /// &lt;/para&gt; /// &lt;para&gt; /// While it is possible to display higher precision fractions of a second component of a time value, /// that value may not be meaningful. The precision of date and time values depends on the resolution /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's /// resolution is approximately 10-15 milliseconds. /// &lt;/para&gt; /// &lt;/remarks&gt; /// &lt;exception cref="ArgumentException"&gt;The specified &lt;paramref name="utcDateTime"/&gt; object does not represent a &lt;see cref="DateTimeKind.Utc"&gt;Coordinated Universal Time (UTC)&lt;/see&gt; value.&lt;/exception&gt; public static string ToString(DateTime utcDateTime) { if (utcDateTime.Kind != DateTimeKind.Utc) { throw new ArgumentException("utcDateTime"); } return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo); } #endregion #region TryParse(string s, out DateTime result) /// &lt;summary&gt; /// Converts the specified string representation of a date and time to its &lt;see cref="DateTime"/&gt; equivalent. /// &lt;/summary&gt; /// &lt;param name="s"&gt;A string containing a date and time to convert.&lt;/param&gt; /// &lt;param name="result"&gt; /// When this method returns, contains the &lt;see cref="DateTime"/&gt; value equivalent to the date and time /// contained in &lt;paramref name="s"/&gt;, if the conversion succeeded, /// or &lt;see cref="DateTime.MinValue"&gt;MinValue&lt;/see&gt; if the conversion failed. /// The conversion fails if the s parameter is a &lt;b&gt;null&lt;/b&gt; reference (Nothing in Visual Basic), /// or does not contain a valid string representation of a date and time. /// This parameter is passed uninitialized. /// &lt;/param&gt; /// &lt;returns&gt;&lt;b&gt;true&lt;/b&gt; if the &lt;paramref name="s"/&gt; parameter was converted successfully; otherwise, &lt;b&gt;false&lt;/b&gt;.&lt;/returns&gt; /// &lt;remarks&gt; /// The string &lt;paramref name="s"/&gt; is parsed using formatting information in the &lt;see cref="DateTimeFormatInfo.InvariantInfo"/&gt; object. /// &lt;/remarks&gt; public static bool TryParse(string s, out DateTime result) { //------------------------------------------------------------ // Attempt to convert string representation //------------------------------------------------------------ bool wasConverted = false; result = DateTime.MinValue; if (!String.IsNullOrEmpty(s)) { DateTime parseResult; if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult)) { result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc); wasConverted = true; } } return wasConverted; } #endregion } } </code></pre>
<p>In .NET (assuming UTC):</p> <pre><code> datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ") </code></pre> <p><code>DateTime.Parse()</code> can be used to convert back into a <code>DateTime</code> structure.</p>
3,772
<p>I have a code igniter project, and I wanted to try debugging it using Zend Studio. WHen I start debugging, I immediately run ino</p> <p>"The URI you submitted has disallowed characters."</p> <p>Does anyone have any idea?</p>
<p>(Assuming you are using the latest version of CodeIgniter (CI) which is 1.7.0)</p> <p>CI is pretty strict about what characters it allows in URLs. You can modify the regex that is used to filter URLs.</p> <p>In system/config/config.php on line 126 is </p> <pre><code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; </code></pre> <p>The comment above this line pretty much explains it all, and what sentinel value to use to over-ride this filter and permit all characters (i.e. turn off filtering completely).</p> <p>On a side note, I found CI to be way too restrictive (for one it doesnt allow for GET requests and wants all interactions to happen via POST. I find this absolutely crazy and is akin to throwing the baby out with the bath water. Apparently, I am not the only one who thinks that CI is overly restrictive, the Kohana Project is a fork of CI + optimizations, namely pure php5 support (all OO), (CI is still PHP4 compatible at the expense of not being able to take advantage of PHP5 OO capabilities).</p> <p>I prefer Kohana over CI, YMMV</p> <p><a href="http://kohanaphp.com/home" rel="noreferrer">http://kohanaphp.com/home</a></p>
<p>in Expression engine you'll find this in /admin/expressionengine/config/config.php</p> <pre><code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\-'; </code></pre> <p>change to </p> <pre><code>$config['permitted_uri_chars'] = ''; </code></pre> <p>but read the line comment before you do this.</p> <p>Or don't use anything CI based.</p>
45,342
<p>I'm currently working on an asp.net-mvc content management system. It would be incredibly useful to be able to deploy nested applications e.g. /shop to have a separate app inside. Or even another instance of the cms.</p> <p>I've found some information around talking about limiting the inheritance of the web.config but I've no idea how this maps to an MVC application. I'm hoping as its essentially the same stack it will just run. Nothing is ever that easy though.</p> <p>If anyone has any experience doing this I would be really grateful. The idea of one big application to rule them all is not at all nice.</p> <p>Si.</p>
<p>To be honest you biggest hurdle is going to be creating the routes and making sure they don't interfere with routes already in the system. After you get that working the rest is easy as pie.</p> <p>The first thing you will need is an HttpModule that will be inserted in to the web.config under the . This module will be used to register and custom ViewEngines or Routes that you want to register. You do this in the same way that you do in the Global.asax but instead of putting them in the Application_Start you put them in the static constructor of the HttpModule. This is so they are only loaded once like Application_Start.</p> <p>By do the above you will have created a module that is easily transportable and doesn't require the implimentor to modify their Global.asax code to get your stuff to work.</p> <p>The second thing you probably want to do is create a custom configuration in the web.config to set stuff like the root path of your application. This will be prepended on to the route when you are setting it up in the HttpModule. Also you can use this to store customization information that is not appropriate for the database.</p> <p>Last but not necessary is that you may want to create a custom ViewEngine that knowns and understands your folder structure. This is only necessary if you want to store the views in a different path than the default views, in order to minimize conflicts.</p>
<p>I've gone down this road before (with /blog), but found it to be doable but complicated and difficult to maintain. Instead I ended up using subdomains:</p> <ul> <li>www.example.com </li> <li>shop.example.com</li> <li>blog.example.com</li> </ul> <p>These are much easier to maintain because you can just have them work as separate websites in IIS. And, of course, you can always redirect www.example.com/shop to shop.example.com.</p>
35,524
<p>I have a subversion repository with the standard layout, i.e. trunk/ and branches/ (and tags/). When working on a bigger change, a feature branch is used, regularly synced with trunk, and later reintegrated back into trunk (using 1.5 now). Pretty standard stuff.</p> <p>What I am wondering is whether such a feature branch, once finished and merged should be kept around, or deleted. The subversion book occasionally seems to suggest that it is common to delete them, but I've also seen a bunch of Open Source projects which do keep the branches.</p> <p>I am also somewhat concerned about how deleting a branch will make it harder to keep track of which branches existed, especially when potentially duplicate names enter the scenario (say we search-refactor twice), their commit histories disappearing somewhere in the depth of the repository etc. </p> <p>On the other hand, branches are used quite a lot, especially with 1.5 now, and I do like the thought of not having to poke through a large list of inactive branches to find the ones I am currently working on.</p> <p>What are the pros and cons that I am missing? What are people doing?</p>
<p>If you are really worried about deleting them, lest they be forgotten, then simply create a folder under branches called 'inactive' and <code>svn move</code> your older, inactive branches into that folder. This might be the best of both worlds for you.</p>
<p>My team deletes them to keep the clutter down. It's not like the go away after all; they can be retrieved if desired. You are right that it can be difficult to find them again: you need to know a revision number where the branch existed so you tell your client to look at that revision in order to see your files.</p> <p>We use FogBugz for our project management which keeps track of when things were committed to our SVN repository by revision number. We can use this to determine what revision we need to revert to in order to see our files: we find the feature history in FogBugz, look to determine what revisions the branch existed in, and use that information to jump backwards.</p>
19,661
<p>I have a C linux application (A) that spawns another process (P) when it is started. When I want to debug P I start A as usual and I connect with ddd/gdb to P.</p> <p>Problems appear when I want to debug the entry-point (start of main) of P. If I follow the usual approach when I connect the debugger to P is already to late. The solution I've found was to insert a sleep at the begining of the main of P so I have time to connect with gdb but this is not a very elegant solution.</p> <p>I've also tried using <code>asm("int $3")</code> but it doesn't seems to work.</p> <p>Do you have any idea how I could solve this problem? (preferably without altering the code of A or P)</p>
<p>You should use this option:</p> <pre><code>set follow-fork-mode</code> <i>mode</i></pre> <p>Where <em>mode</em> is one of <code>parent</code>, <code>child</code> or <code>ask</code>.</p> <p>To follow the parent (this is the default) use:</p> <pre><code>set follow-fork-mode parent </code></pre> <p>To follow the child:</p> <pre><code>set follow-fork-mode child </code></pre> <p>To have the debugger ask you each time:</p> <pre><code>set follow-fork-mode ask </code></pre> <p>So basically you'd start out connecting gdb to A, then set gdb to follow the child, and then when A spawns P, gdb will connect to P and detach from A.</p>
<p>You should be able to do this by making use of gdb's remote debugging features, specifically <code>gdbserver</code>. In effect, launch (P) using <code>gdbserver</code>. These links have more detailed info:</p> <ul> <li><a href="http://davis.lbl.gov/Manuals/GDB/gdb_17.html" rel="nofollow noreferrer">Using gdbserver</a></li> <li><a href="http://sources.redhat.com/gdb/onlinedocs/gdb_18.html" rel="nofollow noreferrer">GDB Remote Debugging</a></li> </ul>
49,390
<p>i'm using the <a href="http://msdn.microsoft.com/en-us/library/bb775248(VS.85).aspx" rel="nofollow noreferrer">Win32 progress dialog</a>. The damnest thing is that when i call:</p> <pre><code>progressDialog.StopProgressDialog(); </code></pre> <p>it doesn't disappear. It stays on screen until the user moves her mouse over it - <em>then</em> it suddenly disappers. </p> <p>The call to <code>StopProgressDialog</code> returns right away (i.e. it's not a synchronous call). i can prove this by doing things after the call has returned:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { //Force red background to prove we've started this.BackColor = Color.Red; this.Refresh(); //Start a progress dialog IProgressDialog pd = (IProgressDialog)new ProgressDialog(); pd.StartProgressDialog(this.Handle, null, PROGDLG.Normal, IntPtr.Zero); //The long running operation System.Threading.Thread.Sleep(10000); //Stop the progress dialog pd.SetLine(1, "Stopping Progress Dialog", false, IntPtr.Zero); pd.StopProgressDialog(); pd = null; //Return form to normal color to prove we've stopped. this.BackColor = SystemColors.Control; this.Refresh(); } </code></pre> <p>The form:</p> <ul> <li>starts gray</li> <li>turns red to show we've stared</li> <li>turns back to gray color to show we've called <strong>stop</strong></li> </ul> <p>So the call to <code>StopProgressDialog</code> has returned, except the progress dialog is still sitting there, mocking me, showing the message:</p> <blockquote> <p>Stopping Progress Dialog</p> </blockquote> <p><a href="https://i.stack.imgur.com/5YXHR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5YXHR.png" alt="alt text"></a> </p> <hr> <h2>Doesn't Appear for 10 seconds</h2> <p>Additionally, the progress dialog does not appear on screen until the</p> <pre><code>System.Threading.Thread.Sleep(10000); </code></pre> <p>ten second sleep is over.</p> <hr> <h2>Not limited to .NET WinForms</h2> <p>The same code also fails in Delphi, which is also an object wrapper around Window's windows:</p> <pre><code>procedure TForm1.Button1Click(Sender: TObject); var pd: IProgressDialog; begin Self.Color := clRed; Self.Repaint; pd := CoProgressDialog.Create; pd.StartProgressDialog(Self.Handle, nil, PROGDLG_NORMAL, nil); Sleep(10000); pd.SetLine(1, StringToOleStr('Stopping Progress Dialog'), False, nil); pd.StopProgressDialog; pd := nil; Self.Color := clBtnFace; Self.Repaint; end; </code></pre> <hr> <h2>PreserveSig</h2> <p>An exception would be thrown if <code>StopProgressDialog</code> was failing.</p> <p><em>Most</em> of the methods in IProgressDialog, when translated into C# (or into Delphi), use the compiler's automatic mechanism of converting failed COM HRESULTS into a native language exception. </p> <p>In other words the following two signatures will throw an exception if the COM call returned an error HRESULT (i.e. a value less than zero):</p> <pre><code>//C# void StopProgressDialog(); //Delphi procedure StopProgressDialog; safecall; </code></pre> <p>Whereas the following lets you see the HRESULT's and react yourself:</p> <pre><code>//C# [PreserveSig] int StopProgressDialog(); //Delphi function StopProgressDialog: HRESULT; stdcall; </code></pre> <p>HRESULT is a 32-bit value. If the high-bit is set (or the value is negative) it is an error.</p> <p>i am using the former syntax. So if <code>StopProgressDialog</code> is returning an error it will be automatically converted to a language exception. </p> <p><strong>Note:</strong> Just for SaG i used the <code>[PreserveSig]</code> syntax, the returned HRESULT is zero;</p> <hr> <h2>MsgWait?</h2> <p>The symptom is similar to what <a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/17/375307.aspx" rel="nofollow noreferrer">Raymond Chen described once</a>, which has to do with the incorrect use of PeekMessage followed by MsgWaitForMultipleObjects:</p> <blockquote> <p>"Sometimes my program gets stuck and reports one fewer record than it should. I have to jiggle the mouse to get the value to update. After a while longer, it falls two behind, then three..."</p> </blockquote> <p>But that would mean that the failure is in IProgressDialog, since it fails equally well on CLR .NET WinForms and native Win32 code.</p>
<p>To really hide the dialog, I've added the following to my C++ wrapper class:</p> <pre><code>void CProgressDlg::Stop() { if ((m_isVisible)&amp;&amp;(m_bValid)) { HWND hDlgWnd = NULL; //Sometimes the progress dialog sticks around after stopping it, //until the mouse pointer is moved over it or some other triggers. //This process finds the hwnd of the progress dialog and hides it //immediately. IOleWindow *pOleWindow; HRESULT hr=m_pIDlg-&gt;QueryInterface(IID_IOleWindow,(LPVOID *)&amp;pOleWindow); if(SUCCEEDED(hr)) { hr=pOleWindow-&gt;GetWindow(&amp;hDlgWnd); if(FAILED(hr)) { hDlgWnd = NULL; } pOleWindow-&gt;Release(); } m_pIDlg-&gt;StopProgressDialog(); if (hDlgWnd) ShowWindow(hDlgWnd, SW_HIDE); m_isVisible = false; m_pIDlg-&gt;Release(); m_bValid = false; } } </code></pre> <p>This is in C++, but you should be able to adapt this to C# without much problems.</p>
<p>Check the return value of the StopProgressDialog Method, maybe that will give you more information about what is going on:</p> <blockquote> <p>HRESULT StopProgressDialog(VOID);</p> <p><em>Returns S_OK if successful, or an error value otherwise.</em></p> </blockquote>
49,542
<pre><code>File fil = new File("Tall.txt"); FileReader inputFil = new FileReader(fil); BufferedReader in = new BufferedReader(inputFil); int [] tall = new int [100]; String s =in.readLine(); while(s!=null) { int i = 0; tall[i] = Integer.parseInt(s); //this is line 19 System.out.println(tall[i]); s = in.readLine(); } in.close(); </code></pre> <p>I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:</p> <pre><code>Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at BinarySok.main(BinarySok.java:19) </code></pre> <p>Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.</p>
<p>You might want to do something like this (if you're in java 5 &amp; up)</p> <pre><code>Scanner scanner = new Scanner(new File("tall.txt")); int [] tall = new int [100]; int i = 0; while(scanner.hasNextInt()){ tall[i++] = scanner.nextInt(); } </code></pre>
<pre><code>File file = new File("E:/Responsibility.txt"); Scanner scanner = new Scanner(file); List&lt;Integer&gt; integers = new ArrayList&lt;&gt;(); while (scanner.hasNext()) { if (scanner.hasNextInt()) { integers.add(scanner.nextInt()); } else { scanner.next(); } } System.out.println(integers); </code></pre>
39,049
<p>I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg:</p> <p><code>Welcome to Clozure Common Lisp Version 1.2-r9226-RC1 (DarwinX8664)!<br> ? (^[[D</code></p> <p>Here I've pressed the <code>(</code> key, and then the <code>left cursor</code> key.</p> <p>When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left.</p> <p>I guess this is some sort of terminal configuration option?</p>
<p>If Clozure CL doesn't provide native readline/editline/whatever support or is configured not to use it, you can run it with rlwrap, for example:</p> <pre><code>rlwrap openmcl </code></pre> <p>rlwrap can be obtained via <a href="http://www.macports.org/" rel="nofollow noreferrer">MacPorts</a> or directly from <a href="http://utopia.knoware.nl/~hlub/rlwrap/" rel="nofollow noreferrer">http://utopia.knoware.nl/~hlub/rlwrap/</a>.</p>
<p>i know that i'm not answering the question with this, but you should not spend much time directly using a lisp repl.</p> <p>using emacs and <a href="http://common-lisp.net/project/slime/" rel="nofollow noreferrer">slime</a> is a much more convenient way of interacting with a lisp. you have an inspector and a debugger at hand, you can jump to the source code of the functions, etc.</p>
22,672
<p>I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. </p> <p>Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?</p>
<p>I'm working with C# and Postgres using <b>Npgsql2</b> component, and they work fast, I recommend you.</p> <p>You can download from <a href="https://github.com/npgsql/Npgsql/releases" rel="noreferrer">https://github.com/npgsql/Npgsql/releases</a></p> <p><b>Note:</b> If you want an application that works with any database you can use the <b>DbProviderFactory</b> class and make your queries using <b>IDbConnection</b>, <b>IDbCommand</b>, <b>IDataReader</b> and/or <b>IDbTransaction</b> interfaces.</p>
<p>Npgsql is excellent driver, but only issue Ive found so far is that Numeric value does not fit in a System.Decimal, so only option is correct each query or DB schema </p> <p><a href="https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/438#issuecomment-486586272" rel="nofollow noreferrer">https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/438#issuecomment-486586272</a></p>
6,918
<p>If I have a string with a valid math expression such as:</p> <pre><code>String s = "1 + 2 * 7"; </code></pre> <p>Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.</p>
<p>You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)</p> <pre><code>Dim sc As New MSScriptControl.ScriptControl() sc.Language = "VBScript" Dim expression As String = "1 + 2 * 7" Dim result As Double = sc.Eval(expression) </code></pre> <p><strong>Edit</strong> - C# version.</p> <pre><code>MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl(); sc.Language = "VBScript"; string expression = "1 + 2 * 7"; object result = sc.Eval(expression); MessageBox.Show(result.ToString()); </code></pre> <p><strong>Edit</strong> - The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.</p>
<p>Flee Fast Lightweight Expression Evaluator</p> <p><a href="https://flee.codeplex.com" rel="nofollow">https://flee.codeplex.com</a></p> <p>Language Reference</p> <ul> <li>ArithmeticOperators Example: a*2 + b ^ 2 - 100 % 5</li> <li>ComparisonOperators Example: a &lt;> 100</li> <li>AndOrXorNotOperators Example (logical): a > 100 And Not b = 100</li> <li>ShiftOperators Example: 100 >> 2</li> <li>Concatenation Example: "abc" + "def"</li> <li>Indexing Example: arr[i + 1] + 100</li> <li>Literals</li> <li>Casting Example: 100 + cast(obj, int)</li> <li>ConditionalOperator Example: If(a > 100 and b > 10, "both greater", "less")</li> <li>InOperator Example (List): If(100 in (100, 200, 300, -1), "in", "not in")</li> <li>Overloaded Operators On Types</li> </ul> <p>Example :</p> <pre><code>Imports Ciloci.Flee Imports Ciloci.Flee.CalcEngine Imports System.Math </code></pre> <hr> <pre><code> Dim ec As New Ciloci.Flee.ExpressionContext Dim ex As IDynamicExpression ec.Imports.AddType(GetType(Math)) ec.Variables("a") = 10 ec.Variables("b") = 40 ex = ec.CompileDynamic("a+b") Dim evalData evalData = ex.Evaluate() Console.WriteLine(evalData) </code></pre> <p>The output : 50</p>
46,273
<p>Some systems such as Symbian insist people to use heap instead of stack when allocating<br> big objects(such as pathnames, which may be more than 512 bytes). Is there any specific reason for this?</p>
<p>Embedded devices often have a fixed-sized stack. Since a subroutine call in C only needs to push a few words onto the stack, a few hundred byte may suffice (if you avoid recursive function calls).</p>
<p>The stack for embedded devices usually resides in a very small amount of high-speed memory. If you allocate large objects on the stack on such a device, you might be facing a <strong>stack overflow</strong>.</p>
47,410
<p>I'm trying out PHPTAL and I want to render a table with zebra stripes. I'm looping through a simple php assoc array ($_SERVER).</p> <p>Note that I don't want to use jQuery or anything like that, I'm trying to learn PHPTAL usage!</p> <p>Currently I have it working like this (too verbose for my liking):</p> <pre><code>&lt;tr tal:repeat="item server"&gt; &lt;td tal:condition="repeat/item/odd" tal:content="repeat/item/key" class="odd"&gt;item key&lt;/td&gt; &lt;td tal:condition="repeat/item/even" tal:content="repeat/item/key" class="even"&gt;item key&lt;/td&gt; &lt;td tal:condition="repeat/item/odd" tal:content="item" class="odd"&gt;item value&lt;/td&gt; &lt;td tal:condition="repeat/item/even" tal:content="item" class="even"&gt;item value&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Basically I want some kind of conditional assignment on the fly, but I'm unsure of the syntax.</p>
<p>You could create expression modifier by writing <code>phptal_tales_evenodd()</code> function (see <code>phptal_tales()</code> in manual):</p> <pre><code>&lt;td tal:attributes="class evenodd:repeat/item/odd"&gt; </code></pre>
<p>Well, it seems like I have my own answer, though I still think this is rather ugly:</p> <pre><code>&lt;tr tal:repeat="item server"&gt; &lt;td tal:content="repeat/item/key" tal:attributes="class php: repeat.item.odd ? 'odd' : 'even'"&gt;item key&lt;/td&gt; &lt;td tal:content="item" tal:attributes="class php: repeat.item.odd ? 'odd' : 'even'"&gt;item value&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Anyone got anything more graceful looking for PHPTAL?</p>
40,853
<p>More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?</p>
<p>Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a file. Then add that function to the list <code>kill-buffer-query-functions</code>.</p> <p>Looking at the documentation for <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html" rel="nofollow noreferrer">Buffer File Name</a> you understand:</p> <ul> <li>a buffer is not visiting a file if and only if the variable <code>buffer-file-name</code> is nil</li> </ul> <p>Use that insight to write the function:</p> <pre class="lang-lisp prettyprint-override"><code>(defun maybe-kill-buffer () (if (and (not buffer-file-name) (buffer-modified-p)) ;; buffer is not visiting a file (y-or-n-p "This buffer is not visiting a file but has been edited. Kill it anyway? ") t)) </code></pre> <p>And then add the function to the hook like so:</p> <pre><code>(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer) </code></pre>
<pre><code>(defun maybe-kill-buffer () (if (and (not buffer-file-name) (buffer-modified-p)) ;; buffer is not visiting a file (y-or-n-p (format "Buffer %s has been edited. Kill it anyway? " (buffer-name))) t)) (add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer) </code></pre>
11,248
<p>I have a model and two views set up like this:</p> <pre><code>Model ---&gt; OSortFilterProxyModel ---&gt; OListView Model ------------------------------&gt; OTableView </code></pre> <p>When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?</p>
<p>What is probably happening is that the views do have two different models. One is your original model, the other is the sort filter model.</p> <p>I'm not sure if this would work, and it depends on what Qt considers "activated", but you could connect a function to each of the view's activated slots. These will pass you a model index. You'll have to send the model index through the proxy model in the appropriate direction (mapFromSource and mapToSource). Then, call the setCurrentIndex on the other view.</p> <p>The documentation for the activated signal states that what is considered "activated" varies by platform. There might be other signals you could latch onto, such as the selection model's selection changed signal. You might have to do a different call to change the selection as seen by the user. And finally, it might be possible or even easier to do in a derived QSelectionModel, as long as you remember about mapping to/from the source model.</p>
<p>Not quite sure how your model subclass is implemented - but the selection depends on persistent model indexes being correct. Can you provide some source code? Are you using the same selection model on both?</p>
16,533
<p>How to invoke the default browser with an URL from C#?</p>
<pre><code>System.Diagnostics.Process.Start("http://www.google.com"); </code></pre> <p>More details here - <a href="http://msdn.microsoft.com/en-us/library/aa326951.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa326951.aspx</a></p>
<p>I used System.Diagnostics.Process.Start in the past, but if Firefox or another browser is set as the default this method always throws a terrible exception to users. At last, I come across System.Windows.Forms.Help.ShowHelp</p> <p><code> Help.ShowHelp(null, "<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>"); </code></p> <p>Please notice that Help is a class only available for WinForms, while Process can be used for other cases (WebForms, WPF and so on).</p>
28,788
<p>I'm looking for a cross-browser way of wrapping long portions of text that have no breaking spaces (e.g. long URLs) inside of divs with pre-determined widths.</p> <p>Here are some solutions I've found around the web and why they <strong>don't</strong> work for me:</p> <ul> <li><strong>overflow : hidden / auto / scroll</strong> - I need the entire text to be visible without scrolling. The div can grow vertically, but not horizontally.</li> <li><strong>Injecting &amp;shy; into the string</strong> via js / server-side - &amp;shy; is supported by FF3 now, but copying and pasting a URL with a &amp;shy; in the middle will not work in Safari. Also, to my knowledge, there isn't a clean method of measuring text width to find out the best string offsets to add these characters to (there's one hacky way, see next item). Another problem is that zooming in Firefox and Opera can easily break this.</li> <li><strong>dumping text into a hidden element and measuring offsetWidth</strong> - related to the item above, it requires adding extra characters into the string. Also, measuring the amount of breaks required in a long body of text could easily require thousands of expensive DOM insertions (one for every substring length), which could effectively freeze the site.</li> <li><strong>using a monospace font</strong> - again, zooming can mess up width calculations, and the text can't be styled freely.</li> </ul> <p>Things that look promising but are not quite there:</p> <ul> <li><strong>word-wrap : break-word</strong> - it's now <a href="http://www.w3.org/TR/css3-text/#word-wrap" rel="noreferrer">part of CSS3 working draft</a>, but it's not supported by either Firefox, Opera or Safari yet. This would be the ideal solution if it worked across all browsers today :(</li> <li><strong>injecting &lt;wbr&gt; tags into the string</strong> via js/ server-side - copying and pasting URLs works in all browsers, but I still don't have a good way of measuring where to put the breaks. Also, this tag invalidates HTML.</li> <li><strong>adding breaks after every character</strong> - it's better than thousands of DOM insertions, but still not ideal (adding DOM elements to a document eats memory and slows downs selector queries, among other things).</li> </ul> <p>Does anyone have more ideas on how to tackle this problem?</p>
<p>I've typically handled this using a combination of <code>word-wrap</code> and the <code>&lt;wbr&gt;</code> idea. note there are a few <a href="http://www.quirksmode.org/oddsandends/wbr.html" rel="nofollow noreferrer">variants</a>. as you can see, <code>&amp;#8203;</code> is probably your best bet for compatibility.</p> <p><code>word-wrap</code> browser support isn't <em>terrible</em>, all things considered, Safari, Internet Explorer, and Firefox 3.1 (Alpha Build) all support it (<a href="http://www.css3.info/preview/word-wrap/" rel="nofollow noreferrer">src</a>), so we may not be all that far off.</p> <p>In regards to the server side breakage, I've used this method pretty successfully (php):</p> <pre><code>function _wordwrap($text) { $split = explode(" ", $text); foreach($split as $key=&gt;$value) { if (strlen($value) &gt; 10) { $split[$key] = chunk_split($value, 5, "&amp;#8203;"); } } return implode(" ", $split); } </code></pre> <p>Basically, for words over 10 characters, I split them at 5 characters each. This seems to work for all use cases I've been handed.</p>
<p>Using a regular expression in PHP should be faster to breakup long words. I have created a function that handles htmlspecialchars and breaks up words with &amp;shy; Here is the function for anyone who is interested. Just pass the string, and the max word length (leave as 0 if you dont want to break up words with &amp;shy;) and it will return a string with html special chars converted and the words broken up with &amp;shy;</p> <pre><code>function htmlspecialchars2($string = "", $maxWordLength = 0) { if($maxWordLength &gt; 0) { $pattern = '/(\S{'.$maxWordLength.',}?)/'; $replacement = '$1&amp;shy;'; $string = preg_replace($pattern, $replacement, $string); } //now encode special chars but dont encode &amp;shy; $string = preg_replace(array('/\&amp;(?!shy\;)/','/\"/',"/\'/",'/\&lt;/','/\&gt;/'), array('&amp;amp;','&amp;quot;','&amp;#039;','&amp;lt;','&amp;gt;'), $string); return $string; } </code></pre>
41,794
<p>Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.</p> <p>For example:</p> <pre><code>Dim myLabel As New Label myLabel.Text = "This is &lt;b&gt;bold&lt;/b&gt; text. This is &lt;i&gt;italicized&lt;/i&gt; text." </code></pre> <p>Which would produce the text in the label as:</p> <blockquote> <p>This is <strong>bold</strong> text. This is <em>italicized</em> text.</p> </blockquote>
<p>That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:</p> <ol> <li>Use separate labels</li> <li>Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text</li> <li>Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2.</li> </ol>
<p>Yeah. You can implements, using HTML Render. For you see, click on the link: <a href="https://htmlrenderer.codeplex.com/" rel="nofollow">https://htmlrenderer.codeplex.com/</a> I hope this is useful.</p>
3,246
<p>Can ZK easily be integrated in a struts web application?</p>
<p>maybe you can find it interesting:</p> <p><a href="http://www.zkoss.org/smalltalks/zk-sample/zk-sample.html" rel="nofollow noreferrer">http://www.zkoss.org/smalltalks/zk-sample/zk-sample.html</a></p> <p>moreover, you can browse a bit the zk forum you can find on <a href="http://www.zkoss.org/" rel="nofollow noreferrer">http://www.zkoss.org/</a> itself, it is more than easy to find some discussion about that. hope it can help</p> <p>luca</p>
<p>more concretely: <a href="http://docs.zkoss.org/wiki/ZK/How-Tos/Integrate-Other-Frameworks#Struts_.2B_Tiles_.2B_JSP_.28.2B_Spring.29" rel="nofollow noreferrer">http://docs.zkoss.org/wiki/ZK/How-Tos/Integrate-Other-Frameworks#Struts_.2B_Tiles_.2B_JSP_.28.2B_Spring.29</a></p>
19,091
<p>I'm working with Eclipse Version 3.2.1 Build M20060921-0945 on a MS-Windows 2000 SP4 using a JDK 1.5.0-12.<br> I takes my locale that is es-AR and sets all menu and context in Spanish which I don't like. So I had included in eclipse.ini file one parameter <em>"-nl en"</em>.<br> Since that, <em>"References..."</em> feature in both <em>"Search"</em> and contextual menu stopped working. I removed parameter and ran eclipse with <em>"-clean"</em> but still not working. I don't have any other clue about what is happening. Thank you all in advance.<br> Beto</p>
<p>Delete all the files in you eclipse data, eg:<br> <code>&lt;WORKSPACE&gt;/.metadata/.plugins/org.eclipse.jdt.core</code><br> This should force eclipse to rebuild its index</p>
<p>Trash your install. </p> <p>Then reinstall it.</p>
33,222
<p>Is there a good tutorial on working with (programming) threads in Visual Studio 2005? Not <a href="http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library" rel="nofollow noreferrer">MFC</a> related, just native C++ (no .NET).</p>
<p>Instead of using Win32 threads directly, I'd consider using a thread wrapper such as <a href="http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html" rel="noreferrer">Boost threads</a>. These are cross platform so porting your application later will be easier. </p>
<p>Try one of these articles on <a href="http://en.wikipedia.org/wiki/The_Code_Project" rel="nofollow noreferrer">The Code Project</a>:</p> <ul> <li><p><em><a href="http://www.codeproject.com/KB/threads/threadobject.aspx" rel="nofollow noreferrer">Creating a C++ Thread Class</a></em></p></li> <li><p><em><a href="http://www.codeproject.com/KB/winsdk/Win32_Event_Handling.aspx" rel="nofollow noreferrer">How to use WIN32 Event Kernel Object</a></em></p></li> </ul>
35,236
<p>I've committed changes in numerous files to a SVN repository from Eclipse.</p> <p>I then go to website directory on the linux box where I want to update these changes from the repository to the directory there.</p> <p>I want to say "svn update project100" which will update the directories under "project100" with all my added and changed files, etc.</p> <p>HOWEVER, I don't want to necessarily update changes that I didn't make. So I thought I could say "svn status project100" but when I do this I get a totally different list of changes that will be made, none of mine are in the list, which is odd.</p> <p>Hence to be sure that only my changes are updated to the web directory, I am forced to navigate to every directory where I know there is a change that I made and explicitly update only those files, e.g. "svn update newfile1.php" etc. which is tedious.</p> <p>Can anyone shed any light on the standard working procedure here, namely how do I get an accurate list of all the changes that are about to be made before I execute the "svn update" command? I thought it was the "status" command.</p>
<p>Try:</p> <pre><code>svn status --show-updates </code></pre> <p>or (the same but shorter):</p> <pre><code>svn status -u </code></pre>
<p>You can use 'svn diff' to see the difference between your working copy and the repository.</p>
22,105
<p>I like Nant very much. I do a lot of scripting with NAnt. It is a great little tool.</p> <p>Since NAnt is pre 1.0, when problems occur, I often think if that it is a problem with NAnt itself, but this is not always the case.</p> <p>One funny example: After running the oracle scripts I parsed the log output to make sure there was no problem. I was testing this with a small log file and it was fine.</p> <p>I used the task to load the file contents to a string property and used a regex to search for errors.</p> <p>When I used this script for a large log file, I stopped getting the "build failed" message at the bottom, because I was printing the error messages.</p> <p>Because the "build failed" was hiding at the top, I thought NAnt crashed, but it worked fine. </p> <p>It would be better for NAnt to have a 1.0 release. Any reasons why not?</p>
<p>NAnt is an open source project that has been around a long while and is quite stable. While they have their reasons for not calling it version "1", does the version number really matter that much in this case? It's just a label.</p> <p>I'd contact the team and find out what needs to be done before they label it as such and perhaps you can contribute some bug fixes etc...</p> <p>The nice thing about the source being open is if you find a bug, you can fix it yourself. Hence the risk of it not being 1.0 is mitigated slightly if you're willing to invest a bit of time.</p>
<p>Open Source projects tend to use more "modest" versions than commercial products which tend to be more marketing driven. A good example of the difference is the Java versioning scheme which went from 1.0 to 1.4 and then by the time it got to version 1.5 it flipped to using version 5 (though 1.5 is the internal name).</p>
34,796
<p>My app uses a WebRequest at certain points to get pages from itself.</p> <p>This shouldn't be a problem. It actually works fine on the server, which is a "shared" hosting package with Medium trust. Locally, I use a custom security policy based on Medium trust, which includes the following &#8212; copied straight from the default Medium trust policy:</p> <pre> &lt;IPermission class="WebPermission" version="1"&gt; &lt;ConnectAccess&gt; &lt;URI uri="$OriginHost$"/&gt; &lt;/ConnectAccess&gt; &lt;/IPermission&gt; </pre> <p>The offending line is in a custom XmlRelativeUrlResolver:</p> <pre><code>public override object GetEntity( System.Uri puriAbsolute, string psRole, System.Type pReturnType ) { return _baseResolver.GetEntity( puriAbsolute, psRole, pReturnType ); } </code></pre> <p>The url being requested is on localhost, in the same application as the requester. Here's the top of the stack trace.</p> <pre> at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint) at System.Net.HttpRequestCreator.Create(Uri Uri) at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase) at System.Net.WebRequest.Create(Uri requestUri) at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at flow.controls.XmlRelativeUrlResolver.GetEntity(Uri puriAbsolute, String psRole, Type pReturnType) in c:\flow\source\controls\DataTransform.cs:line 105 at System.Xml.Xsl.Xslt.XsltLoader.CreateReader(Uri uri, XmlResolver xmlResolver)</pre> <p>Anyone see the problem here?</p> <p>@Sijin: Thanks for the suggestion. The url that gets sent to the resolver is based on the request URL, and I confirmed in the debugger that accessing the site at 127.0.0.1 yields the same result.</p>
<p>Does it work if you put 127.0.0.1 instead of localhost?</p>
<p>This might not be the solution but when I saw your post I remembered this issue that I ran into about a year ago:</p> <blockquote> <p><a href="http://support.microsoft.com/default.aspx/kb/896861" rel="nofollow noreferrer">http://support.microsoft.com/default.aspx/kb/896861</a></p> <p>You receive error 401.1 when you browse a Web site that uses Integrated Authentication and is hosted on IIS 5.1 or IIS 6</p> </blockquote> <p>We were creating a WebRequest to screen scrape a page and it worked in our production environment because we were not using a loopback host name but on development machines we ended up with access denied (after applying Windows Server 2003 SP2). The one difference here is that this was under integrated authentication which caused it to fail... it worked when the request was anonymous (so that is why I am not sure this is the answer for you).</p>
19,133
<p>What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.</p>
<p>Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...</p> <pre><code>String str = "Hello, there, everyone?"; StringBuffer result = new StringBuffer(str.length()); String strl = str.toLowerCase(); boolean bMustCapitalize = false; for (int i = 0; i &lt; strl.length(); i++) { char c = strl.charAt(i); if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') { if (bMustCapitalize) { result.append(strl.substring(i, i+1).toUpperCase()); bMustCapitalize = false; } else { result.append(c); } } else { bMustCapitalize = true; } } System.out.println(result); </code></pre> <p>You can replace the convoluted uppercase append with:</p> <pre><code>result.append((char) (c - 0x20)); </code></pre> <p>although it might seem more hackish.</p>
<p>I would do it like this: </p> <pre><code>private String toCamelCase(String s) { StringBuffer sb = new StringBuffer(); String[] x = s.replaceAll("[^A-Za-z]", " ").replaceAll("\\s+", " ") .trim().split(" "); for (int i = 0; i &lt; x.length; i++) { if (i == 0) { x[i] = x[i].toLowerCase(); } else { String r = x[i].substring(1); x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r; } sb.append(x[i]); } return sb.toString(); } </code></pre>
31,018
<p>Are you aware of any serious performance problems with checking if a file exists before you open it and send it? The context for this is a web application that serves up files dynamically via an ASP page. I was told that there is no check for whether or not the file exists because the database stores this information and shouldn't be wrong. It is of course sometimes wrong for any number of reasons so we end up sending back nothing leaving the user unhappy.</p> <p>My instinct is that checking for a file's existence is so cheap that you shouldn't worry about it but I was told otherwise. Our storage solution is a pretty high powered one (not just an IDE drive on the web server) if that helps. My question is basically: Is my instinct correct?</p> <p>Thanks!</p> <p>Note: These files are never just deleted. Something has to go wrong for them to be missing but this happens a few times a week. Also, the reason I want to check for a file's existence is because I can return an alternate asset that is on disk so I'd like to be able to have that logic all in one spot rather than deal with catching an exception and dealing with that in that context.</p>
<p>Even if you check it exists just before you try to serve it, it could be deleted between the check and you serving it.</p> <p>The problem here is that you send back nothing if you can't serve the file. Trying to serve a non-existent file should throw an exception (or whatever the equivalent is on your platform) - you should handle that exception by returning an appropriate "Sorry, we couldn't find your file" error page.</p>
<p>I really don't know if it is a cheap or expensive task, but, considering that not checking for the existence of the file could result in an unpleasant response to the client I would say it's not expensive.</p> <p>I do have some web apps where I check for file existence and is working just fine.</p>
25,122
<p>I've been using a local git repository interacting with my group's CVS repository for several months, now. I've made an almost neurotic number of branches, most of which have thankfully merged back into my trunk. But naming is starting to become an issue. If I have a task easily named with a simple label, but I accomplish it in three stages which each include their own branch and merge situation, then I can repeat the branch name each time, but that makes the history a little confusing. If I get more specific in the names, with a separate description for each stage, then the branch names start to get long and unwieldy.</p> <p>I did learn looking through old threads here that I could start naming branches with a / in the name, i.e., topic/task, or something like that. I may start doing that and seeing if it helps keep things better organized.</p> <p>What are some best practices for naming git branches?</p> <p>Edit: Nobody has actually suggested any naming conventions. I do delete branches when I'm done with them. I just happen to have several around due to management constantly adjusting my priorities. :) As an example of why I might need more than one branch on a task, suppose I need to commit the first discrete milestone in the task to the group's CVS repository. At that point, due to my imperfect interaction with CVS, I would perform that commit and then kill that branch. (I've seen too much weirdness interacting with CVS if I try to continue to use the same branch at that point.)</p>
<p>Here are some branch naming conventions that I use and the reasons for them</p> <p><strong>Branch naming conventions</strong></p> <ol> <li>Use grouping tokens (words) at the beginning of your branch names.</li> <li>Define and use short lead tokens to differentiate branches in a way that is meaningful to your workflow.</li> <li>Use slashes to separate parts of your branch names.</li> <li>Do not use bare numbers as leading parts.</li> <li>Avoid long descriptive names for long-lived branches.</li> </ol> <p><strong>Group tokens</strong></p> <p>Use "grouping" tokens in front of your branch names. </p> <pre><code>group1/foo group2/foo group1/bar group2/bar group3/bar group1/baz </code></pre> <p>The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity.</p> <p><strong>Short well-defined tokens</strong></p> <p>Choose short tokens so they do not add too much noise to every one of your branch names. I use these:</p> <pre><code>wip Works in progress; stuff I know won't be finished soon feat Feature I'm adding or expanding bug Bug fix or experiment junk Throwaway branch created to experiment </code></pre> <p>Each of these tokens can be used to tell you to which part of your workflow each branch belongs.</p> <p>It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in.</p> <pre><code>new/frabnotz new/foo new/bar test/foo test/frabnotz ver/foo </code></pre> <p>You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options.</p> <pre><code>$ git branch --list "test/*" test/foo test/frabnotz $ git branch --list "*/foo" new/foo test/foo ver/foo $ gitk --branches="*/foo" </code></pre> <p><strong>Use slashes to separate parts</strong></p> <p>You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote.</p> <pre><code>$ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*' $ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*' </code></pre> <p>For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones.</p> <pre><code>$ git checkout new&lt;TAB&gt; Menu: new/frabnotz new/foo new/bar $ git checkout foo&lt;TAB&gt; Menu: new/foo test/foo ver/foo </code></pre> <p>(Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.)</p> <p>It also lets you search for branches in many git commands, like this:</p> <pre><code>git branch --list "feature/*" git log --graph --oneline --decorate --branches="feature/*" gitk --branches="feature/*" </code></pre> <p>Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named "foo" and another branch named "foo/bar". This can be confusing for new users.</p> <p><strong>Do not use bare numbers</strong></p> <p>Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion. </p> <pre><code>$ git checkout CR15032&lt;TAB&gt; Menu: fix/CR15032 test/CR15032 </code></pre> <p>If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited.</p> <p><strong>Avoid long descriptive names</strong></p> <p>Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log.</p> <p>On the other hand long branch names can be more helpful in "merge commits" if you do not habitually rewrite them by hand. The default merge commit message is <code>Merge branch 'branch-name'</code>. You may find it more helpful to have merge messages show up as <code>Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted'</code> instead of just <code>Merge branch 'fix/CR15032'</code>.</p>
<p>Following up on <a href="https://stackoverflow.com/a/280157/5411817">farktronix's suggestion</a>, we have been using Jira ticket numbers for similar in mercurial, and I'm planning to continue using them for git branches. But I think the ticket number itself is probably unique enough. While it might be helpful to have a descriptive word in the branch name as farktronix noted, if you are switching between branches often enough, you probably want less to type. Then if you need to know the branch name, look in Jira for the associated keywords in the ticket if you don't know it. In addition, you should include the ticket number in each comment.</p> <p>If your branch represents a version, it appears that the common convention is to use x.x.x (example: &quot;1.0.0&quot;) format for branch names and vx.x.x (example &quot;v1.0.0&quot;) for tag names (to avoid conflict). See also: <a href="https://stackoverflow.com/questions/2006265/is-there-an-standard-naming-convention-for-git-tags">is-there-an-standard-naming-convention-for-git-tags</a></p>
34,487
<p>I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.</p> <p>Does anyone know any faster ways of doing this or tips to speed up the methods?</p> <pre><code>castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms </code></pre> <p>Code:</p> <pre><code>private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 &amp;&amp; month == 0 &amp;&amp; day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } </code></pre> <p>-</p> <pre><code>private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00") != -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } </code></pre> <p>-</p> <pre><code>private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } </code></pre> <hr> <p>No, Date.parse will not handle dashes by default. And I need to return null for date time strings like <code>"0000-00-00"</code>.</p>
<p>I've been using the following snipplet to parse UTC date strings:</p> <pre><code>private function parseUTCDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0); return d; } </code></pre> <p>Just remove the time part and it should work fine for your needs:</p> <pre><code>private function parseDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); return d; } </code></pre> <p><strike>No idea about the speed, I haven't been worried about that in my applications.</strike> 50K iterations in significantly less than a second on my machine.</p>
<p>Here is my implementation. Give this a try.</p> <pre><code>public static function dateToUtcTime(date:Date):String { var tmp:Array = new Array(); var char:String; var output:String = ''; // create format YYMMDDhhmmssZ // ensure 2 digits are used for each format entry, so 0x00 suffuxed at each byte tmp.push(date.secondsUTC); tmp.push(date.minutesUTC); tmp.push(date.hoursUTC); tmp.push(date.getUTCDate()); tmp.push(date.getUTCMonth() + 1); // months 0-11 tmp.push(date.getUTCFullYear() % 100); for(var i:int=0; i &lt; 6/* 7 items pushed*/; ++i) { char = String(tmp.pop()); trace("char: " + char); if(char.length &lt; 2) output += "0"; output += char; } output += 'Z'; return output; } </code></pre>
2,534
<p>When viewing a webpage, I would like to copy a selection of text with its html formatting in one piece. Meaning if some text is in bold and blue, I want the tool to create a style or class in the html which makes the text blue. Everything is contained in the produced html.</p> <p>I have downloaded a similar plugin but the classes definitions are still external which means I have to get them separately. A non technical user would be at a loss here. I want the user to be able to copy and paste to a new webpage and that page just just works properly because the html copied contains everything.</p> <p>This doesn't have to be a FF plugin. It could be IE or a Windows app.</p>
<p>I think you may be able to accomplish this by using the Firebug for Firefox extension. I often use it to export the content of a web page for use rebuilding a similar object. Is this still too technical? Firebug is a powerful, viable option that it is worth learning, I think.</p>
<p>I think the copy operation does this already. If I copy this page and paste it in a WYSIWYG editor such as TinyMCE (included in Wordpress), I get the formatting. For example the text of this page is (as pasted):</p> <pre><code>&lt;h2&gt;&lt;a href="http://stackoverflow.com/questions/365603/firefox-plugin-to-copy-text-with-its-formatting-intelligently"&gt;Firefox plugin to copy text with its formatting Intelligently?&lt;/a&gt;&lt;/h2&gt; </code></pre> <p>The HTML markup is copied, but not external CSS. I suspect creating a piece of CSS that would apply to your standalone snippet of code the style it had within the DOM hierarchy would be horribly difficult if at all possible. </p>
47,732
<p>I'm trying to print with Laybrick and for the most part it is going. The problem lies with the top layer and gaps appearing. I've tried increasing the number of top layers but the gaps still appear. Any ideas what else I can try? </p> <p>I'm using Simplify3d. <a href="https://i.stack.imgur.com/Y05dR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Y05dR.jpg" alt="Image"></a></p>
<p>When using Simplify3D, you may try referring to their awesome troubleshooting guide: <a href="https://www.simplify3d.com/support/print-quality-troubleshooting/#holes-and-gaps-in-the-top-layers" rel="nofollow">https://www.simplify3d.com/support/print-quality-troubleshooting/#holes-and-gaps-in-the-top-layers</a> 3 reasons (from the guide) for gaps in the top layers:</p> <ol> <li><p>under-extrusion: you may try to increase extrusion multiplier to see if this helps</p></li> <li><p>low infill percentage: not likely in your case if increasing number of top layers did not help</p></li> <li><p>not enough top layers: you already tried increasing number of top layers.</p></li> </ol> <p>In addition to that, you may change certain parameters (such as extrusion multiplier) for a given number of layers by using Simplify3D features. It can be helpful to avoid problems to for the rest of the model.</p>
<p>When using Simplify3D, you may try referring to their awesome troubleshooting guide: <a href="https://www.simplify3d.com/support/print-quality-troubleshooting/#holes-and-gaps-in-the-top-layers" rel="nofollow">https://www.simplify3d.com/support/print-quality-troubleshooting/#holes-and-gaps-in-the-top-layers</a> 3 reasons (from the guide) for gaps in the top layers:</p> <ol> <li><p>under-extrusion: you may try to increase extrusion multiplier to see if this helps</p></li> <li><p>low infill percentage: not likely in your case if increasing number of top layers did not help</p></li> <li><p>not enough top layers: you already tried increasing number of top layers.</p></li> </ol> <p>In addition to that, you may change certain parameters (such as extrusion multiplier) for a given number of layers by using Simplify3D features. It can be helpful to avoid problems to for the rest of the model.</p>
393
<p>I have an SSRS report where the date should be grouped by project category the project code in the category is repeating in side the group how do I suppress the value</p> <p>Please help me to get an idea.</p> <p>Thanks,brijit</p>
<p>You can also hide fields by putting an expression in the Hidden property like this:</p> <pre><code>=Fields!ProductCode.Value = Previous(Fields!ProductCode.Value) </code></pre> <p>So if the value in the previous record is the same as this one, it will hide the field. You must sort the dataset correctly for this to work. In your case I think the sorting would be Date, ProductCategory, ProductCode.</p> <p>In the past I used this often together with expressions for field borders to group the output visually.</p>
<p>I think it may be an issue concerning the way you are grouping the dates. Do you have the grouped with time on them as well but suppressing the hours in your output?</p> <p>For example:</p> <p>12-5-2010 12:00:00</p> <p>12-5-2010 13:00:00</p> <p>if you strip the times off in how you see them but not how you group them, they would show up duped.</p>
44,466
<p>I want to prevent the user from maximizing the Windows Form to full screen so I have disabled the Maximize button. However, I want to be able to have the user 'restore' the Form. When they click the Restore button I want it to show a different, smaller, minified, form, which will show them a maximize button which will return the use to the original form.</p> <p>Is there a way to do this?</p> <p>Thanks.</p> <p>edit: You don't understand, I'm not preventing the user from resizing the form. Whats happening is when the click the restore button, it will hide the form and open a new one with less controls on it. When they click maximize on the smaller form, it will return to the original form.</p>
<p>I looked at a similar problem to this at work and the only solutions I could find involved setting undocumented window styles, which I was not inclined to do. </p> <p>Therefore the best solution to your problem I would think would be to hide the current minimize/maximize/restore buttons and add your own using some ownerdraw or other commands.</p> <p>Looking at this from a user interaction perspective I would want the minimize/maximize/restore buttons to do exactly the same thing for your application as they do for all others. Overriding that functionality would create confusion for your users, hence why I would recommend creating different buttons either on the title bar or somewhere else on your interface that perform this function.</p>
<p>I had a similar situation recently, and from a UI design perspective, found a good example in Windows Media Player. It leaves the Minimise, Maximise and Restore buttons as they are, and has a separate button on the bottom right for "Switch to Compact Mode". And in the mini/compact mode, the same button toggles to "Switch to Full Mode". Another alternative example is Skype, which has an additional system icon button just left of the standard minimise button, that toggles between Compact and Standard modes.</p> <p>(If I had the privilege, I would've preferred to put this as a comment to add to Daemin's accepted answer, still relatively new to StackOverflow)</p>
48,725
<p>I am using <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx" rel="nofollow noreferrer">NetworkInterface.GetAllNetworkInterfaces()</a> to get all the interfaces on a PC. However, this appears to only return "active" interfaces. How can I find "inactive" network interfaces, such as unconnected VPNs, disabled NICs, etc. in .NET. </p> <p>I would like to find them by their name in "Control Panel" -> "Network Connections". So, for example, if I have a VPN called "My Work" I would like to be able to find it using the name "My Work".</p> <p>Using Win32_NetworkAdapterConfiguration does not seem to be an option as it does not return the name shown in "Network Connections" (as far as I can see).</p> <p>Many thanks,</p> <p>RB.</p>
<p>Ok, this is a hacky solution I got to detect named VPNs. It will throw an error if it cannot connect to the VPN for whatever reason (including the network connection is down, the VPN does not exist, etc.). </p> <p>Specific error codes to test for include :</p> <blockquote> <p>Remote Access error 800 - Unable to establish the VPN connection.<br> The VPN server may be unreachable, or security parameters may not be configured properly for this connection.</p> <p>Remote Access error 623 - The system could not find the phone book entry for this connection.</p> </blockquote> <p>It doesn't really answer my question as posed (although it works well enough for the real-life problem).</p> <pre><code>Dim p As New Process p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = "rasdial.exe" p.StartInfo.Arguments = """Company HQ""" p.Start() If Not p.WaitForExit(My.Settings.VpnTimeout) Then Throw New Exception( _ String.Format("Connecting to ""{0}"" VPN failed after {1}ms", sVpn, My.Settings.VpnTimeout)) End If If p.ExitCode &lt;&gt; 0 Then Throw New Exception( _ String.Format("Failed connecting to ""{0}"" with exit code {1}. Errors {2}", sVpn, p.ExitCode, p.StandardOutput.ReadToEnd.Replace(vbCrLf, ""))) End If </code></pre>
<p>OK - Last ditch effort :)</p> <p>How about the <a href="http://msdn.microsoft.com/en-us/library/aa394220(VS.85).aspx" rel="nofollow noreferrer">Win32_NetworkConnection</a> class - I'm pretty sure this will handle VPN connections</p>
45,502
<p>Does anyone know if anyone makes a watermarked textbox control for the compact framework?</p> <p>I already loked at the following and didn't see one.</p> <p><a href="http://www.componentone.com/SuperProducts/StudioMobile/" rel="nofollow noreferrer">Component One Mobile</a></p> <p><a href="http://www.pocketpccontrols.com/" rel="nofollow noreferrer">Pocket PC Controls</a></p> <p><a href="http://www.resco.net/developer/mobileformstoolkit/overview.aspx" rel="nofollow noreferrer">Resco Mobile Forms Toolkit</a></p>
<p>Daniel Moth has a pretty good blog post about how to do this here: </p> <p><a href="http://www.danielmoth.com/Blog/2006/07/textbox-with-cue-banner-support-for.html" rel="noreferrer">TextBox with cue banner support for Windows Mobile</a></p> <p>Best of all it is simple and free!</p>
<p>I've never seen one. <a href="http://www.codeproject.com/KB/miscctrl/WaterMark.aspx" rel="nofollow noreferrer">This project</a> shows how to do it yourself - not sure if it would work on CF, but I didn't see any obvious non-CF supported stuff in the example.</p>
21,073
<p>I'm currently working on a WebSphere 6.1 Web Project.</p> <p>In my java code, how can i get the current running application port?</p>
<p>The servlet API gives you the local port in HttpServletRequest.</p> <pre><code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); writer.write("" + request.getLocalPort()); writer.close(); } </code></pre> <p>The ports are defined in the node's <em>serverindex.xml</em> (e.g. [WAS]/profiles/AppSrv01/config/cells/localhostNode01Cell/nodes/localhostNode01/serverindex.xml).</p> <pre><code>&lt;specialEndpoints xmi:id="NamedEndPoint_1214751102556" endPointName="WC_defaulthost"&gt; &lt;endPoint xmi:id="EndPoint_1214751102556" host="*" port="9080"/&gt; </code></pre> <p>I'm not sure if the WAS JMX support exposes this information - you'd have to check the doc.</p>
<p>If you use RAD you can run administrative console from IDE and then discover all the ports used by WAS </p> <p><a href="http://pic.dhe.ibm.com/infocenter/radhelp/v9/index.jsp?topic=%2Fcom.ibm.sca.tools.doc%2Fsamples%2Ftopics%2Fwas_ports.html" rel="nofollow noreferrer">http://pic.dhe.ibm.com/infocenter/radhelp/v9/index.jsp?topic=%2Fcom.ibm.sca.tools.doc%2Fsamples%2Ftopics%2Fwas_ports.html</a> <img src="https://i.stack.imgur.com/097kP.png" alt="enter image description here"></p>
33,175
<p>I am trying to implement the following functionality:</p> <pre><code>class WeightResolver { WeightMonitor _source; bool _cancelled; Weight _threshold; public Cancel() { _cancelled = true; } public Weight Resolve(){ _cancelled = false; while(_source.CurrentWeight &lt; threshold ) { if(_cancelled) throw new CancelledOperationException(); // Wait until one of the above conditions is met } return _source.CurrentWeight } } </code></pre> <p>However I am running into trouble managing my threads. For example, the Cancel method is registered via an event and Resolve invoked as follows:</p> <pre><code> _activity_timeout_manager.TimeoutHandler += new Action(_weight_resolver.Cancel())l try { var weight = _weight_resolver.Resolve(); } catch(CancelledOperationException) { .... } </code></pre> <p>where the activity manager is running a timer on tick of which it invokes events using TimeoutHandler.Invoke();</p> <p>The problem is that even though it is properly registered with the event, Cancel() never gets called. I believe this is because the thread it is calling to is currently spinning and therefore it never gets a chance at the CPU.</p> <p>What can I do to remedy the situation short of making the call to Resolve() asynchronous? It is extremely preferable for WeightResolver.Resolve() to stay synchronous because the code calling it should spin unless some return is provided anyways.</p> <p><strong>EDIT:</strong> To clarify what I'm asking for. This seems like a fairly common set-up and I would be surprised if there isn't a simple standard way to handle it. I simply have never run across the situation before and don't know what exactly it could be.</p>
<p>This might not work for you, but based on the information you've provided, I'd suggest looking at thread.Join(XXX) where XXX is the number of milliseconds to wait. It'll greatly simplify your code.</p> <p><a href="http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx</a></p> <p>you can block the calling thread to the new thread for a specified amount of time, after which you can abort the Resolve thread.</p> <pre><code>resolveThread.Start(); resolveThread.Join(2000); //this will block the main thread, thus making resolve synchronous resolveThread.Abort(); //timeout has expired </code></pre>
<p>Is this while loop ever giving up the CPU?</p> <pre><code>while(_source.CurrentWeight &lt; threshold ) </code></pre> <p>If not, then your inactivity timer won't get a chance to run. You might want to use ManualResetEvents (instead of the loop... have whatever sets _source.CurrentWeight set the event) or throw in a Thread.yield() every once in a while.</p>
28,547
<p>I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders.</p> <p>It works, but its not specific enough. </p> <p>Hopefully this makes sense...</p> <pre><code>$('div.toggle').hide();//hide all divs that are part of the expand/collapse $('ul.product-info li a').toggle(function(event){ event.preventDefault(); $(this).next('div').slideToggle(200);//find the next div and sliiiide it $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!! },function(event) { // opposite here event.preventDefault(); $(this).next('div').slideToggle(200); $('img.expander').attr('src','img/content/info-open.gif'); }); &lt;ul class="product-info"&gt; &lt;li&gt; &lt;a class="img-link" href="#"&gt;&lt;img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /&gt; &lt;span&gt;How it compares to the other options&lt;/span&gt; &lt;/a&gt; &lt;div class="toggle"&gt;&lt;p&gt;Content viewable when expanded!&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>There are loads of <code>$('img.expander')</code> tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks.</p> <p>EDIT, updated code as per Douglas' solution:</p> <pre><code>$('div.toggle').hide(); $('ul.product-info li a').toggle(function(event){ //$('#faq-copy .answer').hide(); event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-close.gif'); //alert('on'); },function(event) { // same here event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-open.gif'); }); </code></pre>
<pre><code>$(this).contents('img.expander') </code></pre> <p>This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.</p>
<p>Have you tried the .siblings() method?</p> <pre><code>$(this).siblings('img.expander').attr('src','img/content/info-close.gif'); </code></pre>
34,322
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p> <p>Here's some example code:</p> <pre><code>#!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() </code></pre> <p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
<p>When I tried to write Python web service last year, I ended up using <a href="http://pywebsvcs.sourceforge.net/" rel="noreferrer">ZSI-2.0</a> (which is something like heir of SOAPpy) and a <a href="http://pywebsvcs.sourceforge.net/holger.pdf" rel="noreferrer">paper available on its web</a>.</p> <p>Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.</p>
<blockquote> <p>I want to generate a WSDL that I can give to the web folks, ....</p> </blockquote> <p>You can try <a href="http://soaplib.github.com/soaplib/2_0/" rel="nofollow noreferrer">soaplib</a>. It has on-demand WSDL generation.</p>
34,380