instruction
stringlengths
0
30k
I disagree with [Yaakov Ellis' answer.][1] The Common Language Specification guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, and so your Instance property is thread-safe. Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. After your static constructor completes the Instance property will be non-null. [1]: http://stackoverflow.com/questions/7095/is-the-c-static-constructor-thread-safe#7100
I disagree with [Yaakov Ellis' answer.][1] The [Common Language Infrastructure specification][2] guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe. Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. After your static constructor completes the Instance property will be non-null. As [Zoomba's answer][3] points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance. [1]: http://stackoverflow.com/questions/7095/is-the-c-static-constructor-thread-safe#7100 [2]: http://www.ecma-international.org/publications/standards/Ecma-335.htm [3]: http://stackoverflow.com/questions/7095#7105
http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html asm {trap} ; Halts a program running on PPC32 or PPC64. __asm {int 3} ; Halts a program running on IA-32.
> [@Jorge](#37302) wrote: If you want to process your code in a different way the use a preprocessor directive but if you just want a code snippet then find another way because the preprocessor wasn't meant to do that. Interesting. I don't really consider a preprocessor to necessarily work this way. In the example provided, I am doing a simple text substitution, which is in-line with the definition of a preprocessor on [Wikipedia][1]. If this isn't the proper use of a preprocessor, what should we call a simple text replacement, which generally needs to occur before a compilation? [1]: http://en.wikipedia.org/wiki/Preprocessor
I assume that you followed the [dijit.Tree and dojo.data in Dojo 1.1][1] tutorial which directed you to pass the data to the tree control using a data store. That had me banging my head of a brick wall for a while. Its not really a great approach and the alternative is not really well documented. You need to create a use model instead. I have included an example below of a tree model that I created for displaying the structure of an LDAP directory. You will find the default implementation of the model in your dojo distribution at ./dijit/_tree/model.js. The comments should help you understand the functions supported by the model. The IDirectoryService class the code below are stubs for server-side Java POJOs generated by [Direct Web Remoting][2] (DWR). I highly recommend DWR if you going to be doing a lot of client-server interaction. <pre><code lang="javascript"> dojo.declare("LDAPDirectoryTreeModel", [ dijit.tree.model ], { getRoot : function(onItem) { IDirectoryService.getRoots( function(roots) { onItem(roots[0]) }); }, mayHaveChildren : function(item) { return true; }, getChildren : function(parentItem, onComplete) { IDirectoryService.getChildrenImpl(parentItem, onComplete); }, getIdentity : function(item) { return item.dn; }, getLabel : function(item) { return item.rdn; } }); </code></pre> And here is an extract from the my JSP page where I created the model and used it to populate the tree control. <pre><code lang="jsp"> &lt;div dojoType="LDAPDirectoryTreeModel" jsid="treeModel" id="treeModel"&gt; &lt;/div&gt; &lt;div jsid="tree" id="tree" dojoType="dijit.Tree" model="treeModel" labelAttr="name" label="${directory.host}:${directory.port}"&gt; &lt;/div&gt; </code></pre> [1]: http://dojotoolkit.org/2008/02/12/dijit-tree-and-dojo-data-dojo-1-1 [2]: http://directwebremoting.org
What's the best way to persist data in a Java Desktop Application?
|java|persistence|desktop|oop|
I have a large tree of Java Objects in my Desktop Application and am trying to decide on the best way of persisting them as a file to the file system. Some thoughts I've had were: - **Roll my own serializer using DataOutputStream**: This would give me the greatest control of what was in the file, but at the cost of micromanaging it. - **Straight old Serialization using ObjectOutputStream and its various related classes**: I'm not sold on it though since I find the data brittle. Changing any object's structure breaks the serialized instances of it. So I'm locked in to what seems to be a horrible versioning nightmare. - **XML Serialization**: It's not as brittle, but it's significantly slower that straight out serialization. It can be transformed outside of my program. - **JavaDB**: I'd considered this since I'm comfortable writing JDBC applications. The difference here is that the database instance would only persist while the file was being opened or saved. It's not pretty but... it does lend itself to migrating to a central server architecture if the need arises later and it introduces the possibility of quering the datamodel in a simpler way. I'm curious to see what other people think. And I'm hoping that I've missed some obvious, and simpler approach than the ones above. Thanks in advance, Allain
After installing the DEB that John pointed to, my app crashes... Is this because the deb is for the wrong Ubuntu (8.08 rather than 8.04)? It appears to be the correct version of libgluezilla for the version of Mono (everything is. 1.9.1)... Here is what I get when I try to run the application with <pre> $MONO_LOG_LEVEL=debug mono TestbedCSharp.exe Mono-INFO: Assembly Loader probing location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'. Mono-INFO: Image addref Mono.Mozilla 0x8514cb0 -> /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll 0x8514590: 2 Mono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> mscorlib 0x823ba30: 10 Mono-INFO: Assembly Mono.Mozilla 0x8514cb0 added to domain TestbedCSharp.exe, ref_count=1 Mono-INFO: AOT failed to load AOT module /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: /usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.so: cannot open shared object file: No such file or directory Mono-INFO: Assembly Loader loaded assembly from location: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll'. Mono-INFO: Config attempting to parse: '/usr/lib/mono/gac/Mono.Mozilla/0.2.0.0__0738eb9f132ed756/Mono.Mozilla.dll.config'. Mono-INFO: Config attempting to parse: '/etc/mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'. Mono-INFO: Config attempting to parse: '/home/kris/.mono/assemblies/Mono.Mozilla/Mono.Mozilla.config'. Mono-INFO: Assembly Ref addref System.Windows.Forms 0x82880d8 -> Mono.Mozilla 0x8514cb0: 2 Mono-INFO: Assembly Ref addref Mono.Mozilla 0x8514cb0 -> System 0x8290908: 5 Mono-INFO: DllImport attempting to load: 'gluezilla'. Mono-INFO: DllImport loading location: 'libgluezilla.so'. Mono-INFO: Searching for 'gluezilla_init'. Mono-INFO: Probing 'gluezilla_init'. Mono-INFO: Found as 'gluezilla_init'. ** (TestbedCSharp.exe:22700): WARNING **: Thread (nil) may have been prematurely finalized </pre>
The least painful and indeed Django-recommended way of doing this is through a ForeignKey(User) property. That said, extending django.contrib.auth.models.User also works better now -- ever since the refactoring of Django's inheritance code in the models API. I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.
This is true. It's the way [FogCreek Copilot][1] works Take a look at item 2 on Joel's [Copilot 2.0 post][2]. [1]: https://www.copilot.com/ [2]: http://www.joelonsoftware.com/items/2007/01/26.html
Real-time wmv video encoding in C#
|video|encoding|.net|
How to encode video on the fly and send it trough the network from C#? Can't find a suitable library. I need to encode in WMV and don't mind if the actual encoding is made in C++ as long as the library has a .NET dll available. Thanks
|video|encoding|.net|c#|
|video|encoding|.net|
How to encode video on the fly and send it trough the network from C#? Can't find a suitable library. I need to encode in WMV and don't mind if the actual encoding is made in C++ as long as the library has a .NET assembly available. Thanks
PHP variables are assigned by value, passed to functions by value, and when containing/representing objects are passed by reference. Assigned by value/reference example: $var1 = "test"; $var2 = $var1; $var2 = "new test"; $var3 = &$var2; $var3 = "final test"; print ("var1: $var1, var2: $var2, var3: $var3); would output "var1: test, var2: final test, var3: final test". Passed by value/reference exampe: $var1 = "foo"; $var2 = "bar"; changeThem($var1, $var2); print "var1: $var1, var2: $var2"; function changeThem($var1, &$var2){ $var1 = "FOO"; $var2 = "BAR"; } would output: "var1: foo, var2 BAR". Object passed by reference exampe: class Foo{ public $var1; function __construct(){ $this->var1 = "foo"; } public function printFoo(){ print $this->var1; } } $foo = new Foo(); changeFoo($foo); $foo->printFoo(); function changeFoo($foo){ $foo->var1 = "FOO"; } Would output: "FOO" (that last example could be better probably...)
PHP variables are assigned by value, passed to functions by value, and when containing/representing objects are passed by reference. You can force variables to pass by reference using an & Assigned by value/reference example: $var1 = "test"; $var2 = $var1; $var2 = "new test"; $var3 = &$var2; $var3 = "final test"; print ("var1: $var1, var2: $var2, var3: $var3); would output "var1: test, var2: final test, var3: final test". Passed by value/reference exampe: $var1 = "foo"; $var2 = "bar"; changeThem($var1, $var2); print "var1: $var1, var2: $var2"; function changeThem($var1, &$var2){ $var1 = "FOO"; $var2 = "BAR"; } would output: "var1: foo, var2 BAR". Object passed by reference exampe: class Foo{ public $var1; function __construct(){ $this->var1 = "foo"; } public function printFoo(){ print $this->var1; } } $foo = new Foo(); changeFoo($foo); $foo->printFoo(); function changeFoo($foo){ $foo->var1 = "FOO"; } Would output: "FOO" (that last example could be better probably...)
You can upgrade 6.5 to SQL Server 2000. You may have an easier time getting a hold of SQL Server or the 2000 version of the MSDE. Microsoft has a page on [going from 6.5 to 2000][1]. Once you have the database in 2000 format, SQL Server 2005 will have no trouble upgrading it to the 2005 format. If you don't have SQL Server 2000, you can [download the MSDE 2000][2] version directly from Microsoft. [1]: http://www.microsoft.com/technet/prodtechnol/sql/2000/deploy/sqlugrd.mspx#EQFAC [2]: http://www.microsoft.com/downloads/details.aspx?familyid=413744D1-A0BC-479F-BAFA-E4B278EB9147&displaylang=en
@Goyuix -- that's excellent for something written from memory. tested it here -- found the connection wasn't opened. Otherwise very nice. using System.Data.OleDb; ... using (OleDbConnection conn = new OleDbConnection()) { conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;"; using (OleDbCommand cmd = new OleDbCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = "Select * from yourTable"; using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Console.WriteLine(dr["columnName"]); } } } }
you'll have to split the file by linebreaks, then loop thru each line and apply the following logic $seat = 0; $name = 1; $chips = 2; foreach( $string in $file ) { if (preg_match("Seat ([1-0]): ([A-Za-z_0-9]*) \(([1-0]*) in chips\)", $string, $matches)) { echo "Seat: " . $matches[$seat] . "<br>"; echo "Name: " . $matches[$name] . "<br>"; echo "Chips: " . $matches[$chips] . "<br>"; } } I haven't ran this code, so you may have to fix some errors...
I always use the preg_ set of function for REGEX in PHP because the PERL-compatible expressions have much more capability. That extra capability doesn't necessarily come into play here, but they are also supposed to be faster, so why not use them anyway, right? For an expression, try this: /Seat (\d+): ([^ ]+) \((\d+)/ You can use preg_match() on each line, storing the results in an array. You can then get at those results and manipulate them as you like.
I always use the preg_ set of function for REGEX in PHP because the PERL-compatible expressions have much more capability. That extra capability doesn't necessarily come into play here, but they are also supposed to be faster, so why not use them anyway, right? For an expression, try this: /Seat (\d+): ([^ ]+) \((\d+)/ You can use preg_match() on each line, storing the results in an array. You can then get at those results and manipulate them as you like. EDIT: Btw, you could also run preg`_`match`_`all on the entire block of text (instead of looping through line-by-line) and get the results that way, too.
I think that some of the confusion comes from the difference between the concept of a tag and the implementation in SVN. To SVN a tag is a branch which is a copy. Modifying tags is considered wrong and in fact tools like TortoiseSVN will warn you if you attempt to modify anything with ../tags/.. in the path.
I would highly recommend picking up a copy of Effective Java and reading through item 7 obeying the [equals contract][2]. You need to be careful if you are overriding equals for mutable objects, as many of the collections such as Maps and Sets use equals to determine equivalence, and mutating an object contained in a collection could lead to unexpected results. Brian Goetz also has a pretty good [overview of implementing equals and hashCode][3]. [2]: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object) [3]: http://www.ibm.com/developerworks/java/library/j-jtp05273.html
I would highly recommend picking up a copy of Effective Java and reading through item 7 obeying the [equals contract][1]. You need to be careful if you are overriding equals for mutable objects, as many of the collections such as Maps and Sets use equals to determine equivalence, and mutating an object contained in a collection could lead to unexpected results. Brian Goetz also has a pretty good [overview of implementing equals and hashCode][2]. [1]: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html [2]: http://www.ibm.com/developerworks/java/library/j-jtp05273.html
Here's what I'm currently using: preg_match("/(Seat \d+: [A-Za-z0-9 _-]+) \((\d+) in chips\)/",$line)
|java|desktop|oop|persistence|
I have a large tree of Java Objects in my Desktop Application and am trying to decide on the best way of persisting them as a file to the file system. Some thoughts I've had were: - **Roll my own serializer using DataOutputStream**: This would give me the greatest control of what was in the file, but at the cost of micromanaging it. - **Straight old Serialization using ObjectOutputStream and its various related classes**: I'm not sold on it though since I find the data brittle. Changing any object's structure breaks the serialized instances of it. So I'm locked in to what seems to be a horrible versioning nightmare. - **XML Serialization**: It's not as brittle, but it's significantly slower that straight out serialization. It can be transformed outside of my program. - **JavaDB**: I'd considered this since I'm comfortable writing JDBC applications. The difference here is that the database instance would only persist while the file was being opened or saved. It's not pretty but... it does lend itself to migrating to a central server architecture if the need arises later and it introduces the possibility of quering the datamodel in a simpler way. I'm curious to see what other people think. And I'm hoping that I've missed some obvious, and simpler approach than the ones above. Thanks in advance, Allain Here are some more options culled from the answers below: - **An Object Database** - Has significantly less infrastructure than ORM approaches and performs faster than an XML approach. thanks aku
First of all, you can find out which version of Windows you are using with the [OperatingSystem.Platform][1] property in the System library. Second, it is possible that you may put your font settings in Resource files, and determine which resource file to use depending on certain conditions (e.g., your operating system version). Personally though, I think it would be nice to let your user determine the fonts that *they* prefer as opposed to the font that you want for them to use. Finally, you might want to take a look at [WPF][2] as this is one of the problem spaces that it was designed to solve. [1]: http://msdn.microsoft.com/en-us/library/system.operatingsystem.platform.aspx [2]: http://windowsclient.net/
Not really, at least, not last time I looked. I mean, boost::thread_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think. Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is going to be Win32-specific anyway (due to the use of IOCPs) there doesn't really seem to be much benefit from that.
Your implementation looks good enough -- what I do want to know is why you want to do this in the first place? Won't it be preferrable for the focus to cycle back to the first entry? Is the data in the last text box so malleable that once they click the button it is "remembered"? Or do you have some sort of operation that the button does to that specifici text box data -- in that case shouldn't the focus go to a subsequent control instead? I'm interested in finding out why you want to do this in the first place.
I think what you're doing is fine. The only thing I could think of to improve it would be to store each control into a stack as they are accessed. That would give you a complete time line of what was accessed.
Encoding flash video is actually very easy with ffmpeg. You can use one command to convert from just about any video format, ffmpeg is smart enough to figure the rest out, and it'll use every processor on your machine. Invoking it is easy: ffmpeg -i input.avi output.flv ffmpeg will guess at the bitrate you want, but if you'd like to specify one, you can use the -b option, so `-b 500000` is 500kbps for example. There's a ton of options of course, but I generally get good results without much tinkering. This is a good place to start if you're looking for more options: [video options][1]. You don't need a special web server to show flash video. I've done just fine by simply pushing .flv files up to a standard web server, and linking to them with a good swf player, like [flowplayer][2]. WMVs are fine if you can be sure that all of your users will always use [a recent, up to date version of] Windows only, but even then, Flash is often a better fit for the web. The player is even extremely skinnable and can be controlled with javascript. [1]: http://ffmpeg.mplayerhq.hu/ffmpeg-doc.html#SEC9 [2]: http://flowplayer.org/
The database will do this for you. Look at "select ... for update", which is designed just for this kind of thing. It will give you a write lock on the selected rows, which you can then commit or roll back.
In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the [Zope Wiki][1]: from SomeOtherProduct.SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass.speak = speak That code will overwrite/create a method called speak on the class. In Jeff Atwood's [recent post on monkey patching][2]. He shows an example in C# 3.0 which is the current language I use for work. [1]: http://wiki.zope.org/zope2/MonkeyPatch [2]: http://www.codinghorror.com/blog/archives/001151.html
is this a console app or a winforms app? If it's a .NET 1.1 console app this is, sadly, by design -- it's confirmed by a MSFT dev in the [second blog post you referenced](http://www.codinghorror.com/blog/archives/000216.html): > BTW, on my 1.1 machine the example from MSDN does have the expected output; it's just that the second line doesn't show up until after you've attached a debugger (or not). In v2 we've flipped things around so that the UnhandledException event fires before the debugger attaches, which seems to be what most people expect. Sounds like .NET 2.0 does this better (thank goodness), but honestly, I never had time to go back and check.
It's a WinForms app. The exceptions that are caught by Application.ThreadException work fine, and I don't get the ugly .NET exception box (OK to terminate, cancel to debug? who came up with that??). I was getting some exceptions that weren't being caught by that and ended up going to the AppDomain.UnhandledException event that were causing problems. I think I've caught most of those exceptions and I am displaying them in our nice error box now. So I'll just have to hope there are not some other circumstances that would cause exceptions to not be caught by the Application.ThreadException handler.
get root permissions on a file inside of vi?
|c#|.net|video|encoding|
That's very likely. This was pretty much what we assumed (browser problem, not necessarily Ajax). Our problem is now, with this application being accessed by many people via a Citrix environment, with each page continually creating DOM objects and not releasing them, the Citrix environment starts thrashing after some usage. I've seen similar complaints online (especially where you are dumb enough to access an Ajax website via Citrix), but it doesn't make me feel much better that this is the intended behavior. I'm wondering now if anyone has come up with a clever workaround. We also have a client app where we are using the .NET BrowserControl to access these websites, rather than just straight IE7, so if anyone knows a secret API call (*FreeStaleDomObjectsFTW()*) we can utilize from that end of the stack, that would be useful as well.
I don't have any experience with it, but [SupoSE][1] (open source, written in Java) is a tool designed to do exactly this. [1]: http://supose.soebes.de/
Use the [UNION][1] operator: SELECT ColumnA FROM Table1 UNION SELECT ColumnA FROM Table2 [1]: http://msdn.microsoft.com/en-us/library/ms180026.aspx
Your friend might be referring to VIP's (Virtual IP's). From my understanding a VIP is usually controlled by a piece of hardware like a router and then redirects to one of your 2 private IP's. We use this with a cluster of machines behind a VIP. I'm not a network guy so that's pretty much the extent of my knowledge.
You can use a union select: Select columnA from table1 union select columnA from table2
SELECT Table1.*, Table2.d, Table2.e, Table2.f FROM Table1 JOIN Table2 ON Table1.a = Table2.a Or am I misunderstanding your question? Edit: It appears I did.
I believe it's: SELECT columna FROM table1 UNION SELECT columnb FROM table2;
I have been looking for something similar. The best I have come up with is [OpenGrok][1]. I have not tried to implement it yet, but sounds promising. [1]: http://opensolaris.org/os/project/opengrok/ "OpenGrok"
How do I best generate a CSV (comma-delimited text file) for download with ASP.NET?
|asp.net|vb.net|file-io|csv|
This is what I've got. It works. But, is there a simpler or better way? One an ASPX page, I've got the download link... <asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink> And then I've got the Download.aspx.vb Code Behind... Public Partial Class Download Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set header Response.Clear() Response.ContentType = "text/csv" Dim FileName As String = "books.csv" Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName) 'generate file content Dim db As New bookDevelopmentDataContext Dim Allbooks = From b In db.books _ Order By b.Added _ Select b Dim CsvFile As New StringBuilder CsvFile.AppendLine(CsvHeader()) For Each b As Book In Allbooks CsvFile.AppendLine(bookString(b)) Next 'write the file Response.Write(CsvFile.ToString) Response.End() End Sub Function CsvHeader() As String Dim CsvLine As New StringBuilder CsvLine.Append("Published,") CsvLine.Append("Title,") CsvLine.Append("Author,") CsvLine.Append("Price") Return CsvLine.ToString End Function Function bookString(ByVal b As Book) As String Dim CsvLine As New StringBuilder CsvLine.Append(b.Published.ToShortDateString + ",") CsvLine.Append(b.Title.Replace(",", "") + ",") CsvLine.Append(b.Author.Replace(",", "") + ",") CsvLine.Append(Format(b.Price, "c").Replace(",", "")) Return CsvLine.ToString End Function End Class
You should "never" override equals & getHashCode for mutable objects - this goes for .net and Java both. If you do, and use such an object as the key in f.ex a dictionary and then *change* that object, you'll be in trouble because the dictionary relies on the hashcode to find the object. Here's a good article on the topic: [http://weblogs.asp.net/bleroy/archive/2004/12/15/316601.aspx][1] [1]: http://weblogs.asp.net/bleroy/archive/2004/12/15/316601.aspx
Check out [preg_match][1]. Probably looking for something like... <?php $str = 'Seat 1: fabulous29 (835 in chips)'; preg_match('/Seat (?<seatNo>\d+): (?<name>\w+) \((?<chipCnt>\d+) in chips\)/', $str, $matches); print_r($matches); ?> *It's been a while since I did php, so this *could* be a little or a lot off.* [1]: http://www.php.net/manual/en/function.preg-match.php
I think you need to elaborate on your needs if you want useful answers. Generally speaking, though, I get the impression that NAnt offers more flexibility compared to MSBuild, whereas (with my relatively simple needs) I've been fine with the latter so far.
I think you need to elaborate on your needs if you want useful answers. Generally speaking, though, I get the impression that NAnt offers more flexibility compared to MSBuild, whereas (with my relatively simple needs) I've been fine with the latter so far. **Edit:** Sorry, I wasn't trying to be harsh. I see others have already answered in a more useful manner.
When we used to work in MSSQL 2000, we did what we called the "triple-flip": SELECT * FROM ( SELECT TOP (pagesize) FROM ( SELECT TOP (n * pagesize) FROM X ORDER BY (column) ASC ) AS t1 ORDER BY (column) DESC ) AS t2 ORDER BY (column) ASC It wasn't elegant, and it wasn't fast, but it worked.
I suspect this is wildly inefficient but is quite a simple approach, which worked on a small dataset that I tried it on. select top 1 field from table where field in (select top 1 field from table order by field asc) order by field desc SQL server only (I think) but should work on older versions that do not support ROW_NUMBER().
I suspect this is wildly inefficient but is quite a simple approach, which worked on a small dataset that I tried it on. select top 1 field from table where field in (select top 5 field from table order by field asc) order by field desc This would get the 5th item, change the second top number to get a different nth item SQL server only (I think) but should work on older versions that do not support ROW_NUMBER().
[@cmcculloh](http://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196) Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor.
[@cmcculloh](http://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196) Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor. *EDIT:* *Here's my new model:* *A. Each interface no longer has a constructor method.* *B. All Shippers (UPS, FedEx, etc) now implement iShipper (which extends iVendor) and extend the abstract class Shipper (which has all common non-abstract methods for shippers defined in it, getName(), getZip() etc).* *C. Each Shipper has it's own unique _construct method which overwrites the abstract __construct($vendors_no = null, $shipment = null) method contained in Shipper.* *Thanks for the help!* *I don't remember why I am making those two optional now though...*
> Virtual functions in constructors, why do languages differ? Because there's no one good behaviour. I find the C++ behaviour makes more sense (since base class c-tors are called first, it stands to reason that they should call base class virtual functions--after all, the derived class c-tor hasn't run yet, so it may not have set up the right preconditions for the derived class virtual function). But sometimes, where I want to use the virtual functions to initialize state (so it doesn't matter that they're being called with the state uninitialized) the C#/Java behaviour is nicer.
How do you return the focus to the last used control after clicking a button in a winform app?
|c#|winforms|
I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about: ![Sample App Screen Shot][1] [1]: http://lh6.ggpht.com/joe.r.barone/SLs4KZMBqfI/AAAAAAAABNw/P6xtqhCo8Y4/s800/SampleApp1.jpg The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked. I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now: public partial class Form1 : Form { Control _lastEnteredControl; private void textBox_Enter(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Do something here"); _lastEnteredControl.Focus(); } } So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?
|c#|.net|winforms|
Instead of that macro, might I suggest this one: template<typename T, int N> inline size_t array_size(T(&)[N]) { return N; } #define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1) 1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant. 2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays. So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.
The [Common Language Infrastructure specification][2] guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe. Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null. As [Zoomba's answer][3] points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance. [2]: http://www.ecma-international.org/publications/standards/Ecma-335.htm [3]: http://stackoverflow.com/questions/7095#7105
The C99 standard has a number of standard sized-integer types. If you can use a compiler that supports C99 (gcc does), you'll find these in `<stdint.h>` and you can just use them in your projects. Also, it can be especially important in embedded projects to use types as a sort of "safety net" for things like unit conversions. If you can use C++, I understand that there are some "unit" libraries out there that let you work in physical units that are defined by the C++ type system (via templates) that are compiled as operations on the underlying scalar types. For example, these libraries won't let you add a `distance_t` to a `mass_t` because the units don't line up; you'll actually get a compiler error. Even if you can't work in C++ or another language that lets you write code that way, you can at least use the C type system to help you catch errors like that by eye. (That was actually the original intent of Simonyi's Hungarian notation.) Just because the compiler won't yell at you for adding a `meter_t` to a `gram_t` doesn't mean you shouldn't use types like that. Code reviews will be much more productive at discovering unit errors then.
Debugging Javascript in Internet Explorer and Safari
|javascript|safari|explorer|
Currently, I don't really have a good method of debugging javascript in internet explorer and safari. In Firefox, you can use Firebug's [Logging feature][1] and [Command Line functions][2]. However, this doesn't help me when I move to other browsers. [1]: http://getfirebug.com/logging.html [2]: http://getfirebug.com/commandline.html
*string* is an alias for *System.String*. So technically, there is no difference. It's like *int* vs. *System.UInt32*. As far as guidelines, use *string* any time you would you're referring to an object. Use *String* if you need to refer specifically to the class.
*string* is an alias for *System.String*. So technically, there is no difference. It's like *int* vs. *System.UInt32*. As far as guidelines, I think it's generally recommended to use *string* any time you would you're referring to an object. e.g. string place = "world"; Likewise, I think it's generally recommended to use *String* if you need to refer specifically to the class. e.g. string greet = String.Format("Hello {0}!", place);
|linux|unix|vi|
Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type sudo vi filename Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.
A quick Google seems to give this advice: 1. Don't try to edit if it's read-only. 1. You might be able to change the permissions on the file. (Whether or not it will let you save is up to experimentation.) 1. If you still edited anyway, save to a temporary file and then move it. <http://ubuntuforums.org/showthread.php?t=782136>
Ryan's advice is generally good, however, if following step 3, don't move the temporary file; it'll have the wrong ownership and permissions. Instead, `sudoedit` the correct file and read in the contents (using `:r` or the like) of the temporary file. If following step 2, use `:w!` to force the file to be written.
How to get the value of built, encoded ViewState?
|c#|asp.net|
I need to grab the base64-encoded representation of the ViewState. Obviously this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /> I need a way on the server side to get the value "/wEPDwUJODU0Njc5MD...=="
I need to grab the base64-encoded representation of the ViewState. Obviously this would not be available until fairly late in the request lifecycle, which is OK. For example, if the output of the page includes: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /> I need a way on the server side to get the value "/wEPDwUJODU0Njc5MD...==" To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being *sent* to the client, not the ViewState I'm getting back from them.
Oh, in WinForms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads. I have an old CodeProject article here which should help: <http://www.codeproject.com/KB/exception/ExceptionHandling.aspx>
That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this: MyDB db = new MyDB("Data Source=..."); var q = from db.MyTable select c; foreach (var c in q) Console.WriteLine(c.MyField.ToString());
The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the "bin location" relevant to the working directory that you have specified. <executable>c:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable> <workingDirectory>C:\data\projects\FooSolution\</workingDirectory> <projectFile>FooSolution.sln</projectFile> <buildArgs>/noconsolelogger /p:Configuration=Debug </buildArgs> So in the above example your build output will be put in C:\data\projects\FooSolution\[ProjectName]\bin\Debug. Should you want to output to a different location you may want to look at of the <publishers> tag in CCNET. <publishers> <xmllogger /> <buildpublisher> <sourceDir>C:\data\projects\FooSolution\FooProject\bin\Debug</sourceDir> <publishDir>C:\published\FooSolution\</publishDir> <useLabelSubDirectory>false</useLabelSubDirectory> </buildpublisher> </publishers> This will allow you to publish your output to a different location.
Your approach looks good. If you want to avoid having to add an the event handler to every control you add, you could create a recursive routine to add a [GotFocus][1] listener to every control in your form. This will work for any type of control in your form, however you could adjust it to meet your needs. private void Form_OnLoad(object obj, EventArgs e) { AddGotFocusListener(this); } private void AddGotFocusListener(Control ctrl) { foreach(Control c in ctrl.Controls) { c.GotFocus += new EventHandler(Control_GotFocus); if(c.Controls.Count > 0) { AddGotFocusListener(c); } } } private void Control_GotFocus(object obj, EventArgs e) { // Set focused control here } [1]: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus.aspx
How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size)
|java|jvm|heap|tuning|out-of-memory|
I am writing a client-side Swing application (graphical font designer) on Java 5. Recently, I am running into "java.lang.OutOfMemoryError: Java heap space" error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found [Ergonomics in the 5.0 Java Virtual Machine][1] and others saying on Windows machine the JVM defaults max heap size as 64MB. Given this situation, how should I deal with this constraint? I could increase the max heap size using command line option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some finite max does not ultimately get rid of the issue. I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too. If you could point me to details of above ideas or some alternatives like automatic virtual memory, extending heap size dynamically, that will be great. [1]: http://java.sun.com/docs/hotspot/gc5.0/ergo5.html
For a bit of 'simplicity' maybe try. public Form1() { InitializeComponent(); foreach (Control ctrl in Controls) { if (ctrl is TextBox) { ctrl.Enter += delegate(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; }; } } } then you don't have to worry about decorating each textbox manually (or forgetting about one too).
Wordpress Wiki Integration
|wordpress|php|mysql|wiki|
I am running a WordPress blog right now on my own LAMP hosting. I really want to add some basic Wiki functionality to my site. Ideally just the ability to have some posts or pages that users with certain roles / capabilities could edit. The latest version of WordPress has edit revisions, so it would seem like I could leverage that. I looked at the basic [roles and capabilities][1], and the edit_others_posts capability of the Editor role seems like it would be a good option, but it allows editing of ***ALL*** posts. What I want is the ability for **some** users to edit **some** pages /[ posts that *they don't own*. Maybe a flag on certain pages / posts that allows others to edit them. On the other end of the spectrum I would be happy if I could install a Wiki and share the login credentials between WordPress and the Wiki. I hacked MediaWiki a while ago to share logins with another site (in Classic ASP) via session cookies and it was a pain to do and even worse to maintain. Ideally I would like to find a plug-in or someone who knows a more elegant solution. [1]: http://codex.wordpress.org/Roles_and_Capabilities
[@cmcculloh](http://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196) Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor. *EDIT:* *Here's my new model:* *A. Each interface no longer has a constructor method.* *B. All Shippers (UPS, FedEx, etc) now implement iShipper (which extends iVendor) and extend the abstract class Shipper (which has all common non-abstract methods for shippers defined in it, getName(), getZip() etc).* *C. Each Shipper has it's own unique _construct method which overwrites the abstract __construct($vendors_no = null, $shipment = null) method contained in Shipper (I don't remember why I'm allowing those to be optional now though. I'd have to go back through my documentation...).* So: interface iVendor{ public function getName(); public function getVendors_no(); public function getZip(); public function getCountryCode(); public function setName($name); public function setVendors_no($vendors_no); public function setZip($zip); public function setCountryCode($countryCode); } interface iShipper extends iVendor{ public function getTransitTime($shipment = null); public function getTransitCost($shipment = null); public function getCurrentShipment(); public function setCurrentShipment($shipment); public function getStatus($shipment = null); } abstract class Shipper implements iShipper{ abstract public function __construct($vendors_no = null, $shipment = null); //a bunch of non-abstract common methods... } class FedEx extends Shipper implements iShipper{ public function __construct($vendors_no = null, $shipment = null){ //a bunch of setup code... } //all my FedEx specific methods... } *Thanks for the help!* *ps. since I have now added this to "your" answer, if there is something about it you don't like/think should be different, feel free to change it...*
Validation Patterns for Custom XML Documents
|c#|visual-studio|xml|schema|
I have a web application that generates a medium sized XML dataset to be consumed by a third party. I thought it would be a good idea to provide some form of schema document for the XML that I generate so I pasted the XML into Visual Studio and got it to generate an XSD. The annoying thing is that my XML doesn't validate to the XSD that was generated! Is it better to roll your own XSD? What about different schema docs like DTDs, Relax NG, or Schematron? The key is that I would like to be able to validate my document using C#. What are your xml validation strategies?
Overriding the equals method is necessary if you want to test equivalence in standard library classes (for example, ensuring a java.util.Set contains unique elements or using objects as keys in java.util.Map objects). Note, if you override equals, ensure you honour the API contract as described in the documentation. For example, ensure you also override [Object.hashCode][1]: > If two objects are equal according to > the equals(Object) method, then > calling the hashCode method on each of > the two objects must produce the same > integer result. [1]: http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html
Do you care if you get dups or not? UNION will be slower than UNION ALL because UNION will filter out dups
In Oracle (at least) there is UNION and UNION ALL, UNION ALL will return all results from both sets even if there are duplicates, where as UNION will return the distinct results from both sets.