Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
### ANSWER: If you ever see these lines and are mistified like I was, here's what they mean. `Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))` `EventDispatchTread.run() line: not available [local variables unavailable]` It's not that the variables are unavailable because they are lurking behin...
Welcome to the complexity of writing GUI code. When you run a Swing program, a background thread called the Event Dispatch Thread is created. When the user clicks on a JButton, for example, JButton creates and fires an event using this Event Dispatch Thread. Hence the name: it's the thread that dispatches events! You...
Any method call on a null object will raise a null pointer exception. In your code, *rules, name or display* could be null and cause an exception.
What is this java.awt.event error?
[ "", "java", "events", "awt", "" ]
I have the following Linq to SQL query, in which I'm trying to do a multi-column GROUP BY: ``` return from revision in dataContext.Revisions where revision.BranchID == sourceBranch.BranchID-1 && !revision.HasBeenMerged group revision by new Task(revision.TaskSourceCode.ToUpper(), ...
Looks like you already have your solution, but just FYI LINQ to SQL does support `.ToUpper()`. For instance: ``` NorthwindDataContext dc = new NorthwindDataContext(); Product product = dc.Products.Single(p => p.ProductName.ToUpper() == "CHAI"); ``` Is translated into: ``` exec sp_executesql N'SELECT [t0].[ProductID...
OK, I figured this out. I had two problems; first of all, ToUpper() doesn't translate into SQL, and secondly, I don't think Linq to SQL supports orderby on objects; at least not non-entities. By decomposing the orderby into its constituent columns, everything started to work as planned. ``` return from revision in dat...
Linq to SQL: How can I Order By a composite object?
[ "", "c#", "linq-to-sql", "sql-order-by", "" ]
This is probably not possible, but I have this class: ``` public class Metadata<DataType> where DataType : struct { private DataType mDataType; } ``` There's more to it, but let's keep it simple. The generic type (DataType) is limited to value types by the where statement. What I want to do is have a list of thes...
``` public abstract class Metadata { } // extend abstract Metadata class public class Metadata<DataType> : Metadata where DataType : struct { private DataType mDataType; } ```
Following leppie's answer, why not make `MetaData` an interface: ``` public interface IMetaData { } public class Metadata<DataType> : IMetaData where DataType : struct { private DataType mDataType; } ```
C# - Multiple generic types in one list
[ "", "c#", "generics", "" ]
this seems so silly - i must be missing something obvious. I have the following code (just as a test): ``` <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void page_load(object o, EventArgs...
I put my 2 cents on that when you access the public site, you are running through a web proxy, and that is where the content is being cached.
Try this in Page\_Load: ``` Response.BufferOutput = false; ``` Also get a copy of [Fiddler](http://www.fiddlertool.com/fiddler/) and watch your HTTP conversation to make sure your page is not cached.
How to disable Response.Buffer
[ "", "c#", "asp.net", "buffer", "" ]
Is there any performance penalty for the following code snippet? ``` for (int i=0; i<someValue; i++) { Object o = someList.get(i); o.doSomething; } ``` Or does this code actually make more sense? ``` Object o; for (int i=0; i<someValue; i++) { o = someList.get(i); o.doSomething; } ``` If in byte cod...
In today's compilers, no. I declare objects in the smallest scope I can, because it's a lot more readable for the next guy.
[To quote Knuth, who may be quoting Hoare](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize): > **Premature optimization is the root of all evil.** Whether the compiler will produce marginally faster code by defining the variable outside the loop is debatable, and I imagine it won't. I wo...
Declare an object inside or outside a loop?
[ "", "java", "performance", "" ]
I've been working with Swing for a while now but the whole model/structure of `JFrame`s, `paint()`, `super`, etc is all murky in my mind. I need a clear explanation or link that will explain how the whole GUI system is organized.
The same happened to me. Actually to this day I don't quite get 100% how all it works. Swing is a very flexible framework - perhaps too flexible. With flexibility comes a lot of abstraction and with abstraction comes confusion. :) I've found the following articles worth reading. They helped me to better understand th...
Have you looked at the Java Swing Tutorial (click [here](http://java.sun.com/docs/books/tutorial/uiswing/))? It does a pretty good job of covering the basics of developing Swing applications.
Java GUI Swing Model Explanation
[ "", "java", "swing", "user-interface", "jframe", "" ]
This may seem like a stupid question, so here goes: Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo?
``` FileInfo f = new FileInfo(path); string drive = Path.GetPathRoot(f.FullName); ``` This will return "C:\". That's really the only other way.
Well, there's also this: ``` FileInfo file = new FileInfo(path); DriveInfo drive = new DriveInfo(file.Directory.Root.FullName); ``` And hey, why not an extension method? ``` public static DriveInfo GetDriveInfo(this FileInfo file) { return new DriveInfo(file.Directory.Root.FullName); } ``` Then you could just d...
Get the drive letter from a path string or FileInfo
[ "", "c#", "file-io", "" ]
Is this ``` ... T1 join T2 using(ID) where T2.VALUE=42 ... ``` the same as ``` ... T1 join T2 on(T1.ID=T2.ID) where T2.VALUE=42 ... ``` for all types of joins? My understanding of `using(ID)` is that it's just shorthand for `on(T1.ID=T2.ID)`. Is this true? Now for another question: Is the above the same as ``` ...
I don't use the USING syntax, since 1. most of my joins aren't suited to it (not the same fieldname that is being matched, and/or multiple matches in the join) and 2. it isn't immediately obvious what it translates to in the case with more than two tables ie assuming 3 tables with 'id' and 'id\_2' columns, does ``` ...
The `USING` clause is shorthand for an equi-join of columns, assuming the columns exist in both tables by the same name: ``` A JOIN B USING (column1) A JOIN B ON A.column1=B.column1 ``` You can also name multiple columns, which makes joins on compound keys pretty straightforward. The following joins should be equiva...
What's the difference between "using" and "on" in table joins in MySQL?
[ "", "mysql", "sql", "join", "" ]
I've found this piece of code on [Koders](http://www.koders.com/csharp/fidACD7502AA845419FF59B7DA804D3C8FCA0E40138.aspx?s=basecodegeneratorwithsite#L76): ``` private ServiceProvider SiteServiceProvider { get { if (serviceProvider == null) { serviceProvider = new ServiceProvider(site...
It's possible that the ServiceProvider overrides the !=/== operator, so that for an *invalid* state the comparison to null returns true. Looks strange anyway.
I would expect that "test for null" pattern more if it was a factory method - i.e. ``` SomeType provider = SomeFactory.CreateProvider(); if(provider == null) // damn!! no factory implementation loaded... { etc } ``` There is one other case worth knowing about, but which doesn't apply here (since we know the type we a...
Checking C# new() initialisation for null?
[ "", "c#", "exception", "new-operator", "" ]
I know how to do this using for loops. Is it possible to do something like this using LINQ or lambdas? ``` int[] a = { 10, 20, 30 }; int[] b = { 2, 4, 10 }; int[] c = a * b; //resulting array should be { 20, 80, 300 } ```
EDIT: The code below will work, but it's not as readable as using an explicit method. LINQ is great where it definitely *adds* to readability... but this isn't one of those cases. This is a briefer version of CMS's answer - the extra `let` isn't required, and when you're just doing a projection it's simpler to just us...
Using the Zip function (new to .NET 4.0) details [here](http://bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx): ``` int[] a = { 10, 20, 30 }; int[] b = { 2, 4, 10 }; int[] c = a.Zip(b, (a1, b1) => a1 * b1).ToArray(); ``` Until .NET 4 comes out you can ...
Can you use LINQ or lambdas to perform matrix operations?
[ "", "c#", "linq", "lambda", "" ]
I noticed C++ will not compile the following: ``` class No_Good { static double const d = 1.0; }; ``` However it will happily allow a variation where the double is changed to an int, unsigned, or any integral type: ``` class Happy_Times { static unsigned const u = 1; }; ``` My solution was to alter it to read: ...
The problem is that with an integer, the compiler *usually* doesn't have to ever create a memory address for the constant. It doesn't exist at runtime, and every use of it gets inlined into the surrounding code. It can still decide to give it a memory location - if its address is ever taken (or if it's passed by const ...
I see no technical reason why ``` struct type { static const double value = 3.14; }; ``` is forbidden. Any occasion you find where it works is due to non-portable implementation defined features. They also seem to be of only limited use. For integral constants initialized in class definitions, you can use them an...
Why can't I have a non-integral static const member in a class?
[ "", "c++", "" ]
--Edit with more bgnd information-- A (black box) COM object returns me a string. A 2nd COM object expects this same string as byte[] as input and returns a byte[] with the processed data. This will be fed to a browser as downloadable, non-human-readable file that will be loaded in a client side stand-alone applicatio...
Okay, with your updated information: your 2nd COM object expects binary data, but you want to create that binary data from a string. Does it treat it as plain binary data? My guess is that something is going to reverse this process on the client side. If it's eventually going to want to reconstruct the data as a strin...
BinaryFormatter is almost certainly not what you want to use. If you just need to convert a string to bytes, use [Encoding.GetBytes](http://msdn.microsoft.com/en-us/library/system.text.encoding.getbytes.aspx) for a suitable encoding, of course. UTF-8 is usually correct, but check whether the document specifies an enco...
Converting string from memorystream to binary[] contains leading crap
[ "", "c#", "stream", "" ]
Using C#, when a user types a text in a normal textbox, how can you see the Hebrew equivalent of that text? I want to use this feature on a data entry form, when the secretary puts in the customer name using English characters to have it converted automatically in another textbox to the hebrew representation. Maybe s...
I didn't even know there was such a thing as [Hebraization](http://en.wikipedia.org/wiki/Hebraization_of_English) — thanks for asking this question :-) This functionality is not provided by the .NET Framework, so I'm afraid you'd have to build it yourself. You'd have to know how the English is pronounced to provide th...
I'll guess that's next to impossible, I don't know hebrew, but I do know from other languages that the pronounciation (and thus the transliteration) peoples names often (actually more often than not) differs a lot from the general pronounciation of the letters. This is because names change slower than the writing syste...
Convert text from English characters to Hebrew characters
[ "", "c#", "cultureinfo", "hebrew", "" ]
If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.
You mean something like this? ``` import os for path, dirs, files in os.walk( root ): for f in files: print path, f, os.path.getsize( os.path.join( path, f ) ) ```
There is no other way to compute the size than recursively invoking stat. This is independent of Python; the operating system just provides no other way. The algorithm doesn't have to be recursive; you can use os.walk. There might be two exceptions to make it more efficient: 1. If all the files you want to measure f...
What's the best way to get the size of a folder and all the files inside from python?
[ "", "python", "" ]
Rails introduced some core extensions to Ruby like `3.days.from_now` which returns, as you'd expect a date three days in the future. With extension methods in C# we can now do something similar: ``` static class Extensions { public static TimeSpan Days(this int i) { return new TimeSpan(i, 0, 0, 0, 0); ...
I like extension methods a lot but I do feel that when they are used outside of LINQ that they improve readability at the expense of maintainability. Take `3.Days().FromNow()` as an example. This is wonderfully expressive and anyone could read this code and tell you exactly what it does. That is a truly beautiful thin...
First, my gut feeling: `3.Minutes.from_now` looks totally cool, but does not demonstrate why extension methods are good. This also reflects my general view: cool, but I've never really missed them. --- **Question: Is `3.Minutes` a timespan, or an angle?** Namespaces referenced through a using statement "normally" on...
C# Extension Methods - How far is too far?
[ "", "c#", "ruby-on-rails", "extension-methods", "" ]
I am using CODBCRecordset (a class found on CodeProject) to find a single record in a table with 39 columns. If no record is found then the call to CRecordset::Open is fine. If a record matches the conditions then I get an Out of Memory exception when CRecordset::Open is called. I am selecting all the columns in the qu...
Read Pax's response. It gives a you a great understanding about why the problem happens. Work Around: This error will only happen if the field defined as (TEXT, LONGTEXT, etc) is NULL (and maybe empty). If there is data in the field then it will only allocate for the size the data in the field and not the max size (t...
Can we assume you mean you're calling C**ODBC**Recordset::Open(), yes? Or more precisely, something like: ``` CDatabase db; db.Open (NULL,FALSE,FALSE,"ODBC;",TRUE); CODBCRecordSet rs (&db); rs.Open ("select blah, blah, blah from ..."); ``` **EDIT after response:** There are some known bugs with various ODBC drivers ...
"out of memory" exception in CRecordset when selecting a LONGTEXT column from MySQL
[ "", "c++", "mysql", "database", "mfc", "recordset", "" ]
sorry but I do not have the actual code with me, but I will try to explain: I have a servlet mapped to the following: ``` /admin/* ``` So, this goes to a servlet: ``` public class AdminController extends MainController { public void doPost(HttpServletRequest request, HttpServletResponse response) { // D...
The [HttpServlet.service](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpServlet.html#service(javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse)) method gets called for all request types and what you are seeing is a HEAD request and then a GET or POST request. Inst...
Though it is old thread but my answer may help someone. Today I faced the same issue. My particular servlet is working fine earlier and suddenly it has started calling doGet method twice. On investigation, I found that my chrome browser has html validator extension which is calling the servlet again with same request t...
Servlet being called twice!
[ "", "java", "servlets", "" ]
I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. <http://api.reddit.com>. This returns a valid json object. If I call a local file (which is what is returned from the website saved to my local disk) things work fine. ``` $(document).ready(function() { $.getJSON("js/re...
The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the [docs](http://docs.jquery.com/Ajax/jQuery.getJSON): ``` $(document).ready(function() { $.getJSON("http://api.flickr.com/services/feeds/phot...
JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable. What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function yo...
jsonp request not working in firefox
[ "", "javascript", "jquery", "json", "" ]
When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable? ``` public void someMethod(someType someObject){ /* * code that modifies the someObject's state * */ } ``` Al...
No, I don't think this is possible. The normal approach is to create an adapter for SomeType where all the methods changing state throws UnsupportedOperationException. This is used by for instance java.util.Collections.unmodifiable\*-functions. There are several approaches to this: * you can let SomeType be an interf...
In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example). However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it".
How to get a c++ constant pointer equivalent in Java?
[ "", "java", "immutability", "final", "constants", "" ]
I'm using SQL Server 2005. I have a field that must either contain a unique value or a NULL value. I think I should be enforcing this with either a `CHECK CONSTRAINT` or a `TRIGGER for INSERT, UPDATE`. Is there an advantage to using a constraint here over a trigger (or vice-versa)? What might such a constraint/trigge...
Here is an alternative way to do it with a constraint. In order to enforce this constraint you'll need a function that counts the number of occurrences of the field value. In your constraint, simply make sure this maximum is 1. Constraint: ``` field is null or dbo.fn_count_maximum_of_field(field) < 2 ``` **EDIT I...
I create a view with the an index that ignores the nulls through the where clause...i.e. if you insert null into the table the view doesn't care but if you insert a non null value the view will enforce the constraint. ``` create view dbo.UniqueAssetTag with schemabinding as select asset_tag from dbo.equipment where as...
Field value must be unique unless it is NULL
[ "", "sql", "sql-server", "sql-server-2005", "null", "" ]
I've always been one to simply use: ``` List<String> names = new ArrayList<>(); ``` I use the interface as the type name for *portability*, so that when I ask questions such as this, I can rework my code. When should [`LinkedList`](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html) be used over [`A...
**Summary** `ArrayList` with `ArrayDeque` are preferable in *many* more use-cases than `LinkedList`. If you're not sure — just start with `ArrayList`. --- TLDR, in `ArrayList` accessing an element takes constant time [O(1)] and adding an element takes O(n) time [worst case]. In `LinkedList` inserting an element takes...
Thus far, nobody seems to have addressed the memory footprint of each of these lists besides the general consensus that a `LinkedList` is "lots more" than an `ArrayList` so I did some number crunching to demonstrate exactly how much both lists take up for N null references. Since references are either 32 or 64 bits (e...
When to use LinkedList over ArrayList in Java?
[ "", "java", "arraylist", "collections", "linked-list", "" ]
I am modifying a SQL table through C# code and I need to drop a NOT NULL constraint if it exists. How do I check to see if it exists first?
``` select is_nullable from sys.columns where object_id = OBJECT_ID('tablename') and name = 'columnname'; ```
Well, you could check `syscolumns.isnullable` flag? Or more recently: ``` COLUMNPROPERTY(@tableId, 'ColumnName', 'AllowsNull') ``` Where @tableId is OBJECT\_ID('TableName')
How to check if NOT NULL constraint exists
[ "", "c#", "sql-server", "" ]
``` public class doublePrecision { public static void main(String[] args) { double total = 0; total += 5.6; total += 5.8; System.out.println(total); } } ``` The above code prints: ``` 11.399999999999 ``` How would I get this to just print (or be able to use it as) 11.4?
As others have mentioned, you'll probably want to use the [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) class, if you want to have an exact representation of 11.4. Now, a little explanation into why this is happening: The `float` and `double` primitive types in Java are [floating...
When you input a double number, for example, `33.33333333333333`, the value you get is actually the closest representable double-precision value, which is exactly: ``` 33.3333333333333285963817615993320941925048828125 ``` Dividing that by 100 gives: ``` 0.333333333333333285963817615993320941925048828125 ``` which a...
Retain precision with double in Java
[ "", "java", "floating-point", "double", "precision", "" ]
Is it worth changing my code to be "more portable" and able to deal with the horror of magic quotes, or should I just make sure that it's always off via a .htaccess file? ``` if (get_magic_quotes_gpc()) { $var = stripslashes($_POST['var']); } else { $var = $_POST['var']; } ``` Versus ``` php_flag magic_quote...
Don't accommodate both situations. Two code paths = twice the headaches, plus there's a good chance you'll slip up and forget to handle both situations somewhere. I used to check if magic quotes were on or off, and if they were on, undo their magic (as others in the thread have suggested). The problem with this is, yo...
I would check the setting using `get_magic_quotes_gpc()` and do a big noisy exit with error. In the error inform the administrator of the proper setting.
Work around magic quotes, or just make sure they're off?
[ "", "php", "magic-quotes-gpc", "" ]
I've been working on a program to read a dbf file, mess around with the data, and save it back to dbf. The problem that I am having is specifically to do with the writing portion. ``` private const string constring = "Driver={Microsoft dBASE Driver (*.dbf)};" + "SourceType=DBF;" ...
For people coming here in the future: I wrote this today and it works well. The filename is without the extension (.dbf). The path (used for connection) is the directory path only (no file). You can add your datatable to a dataset and pass it in. Also, some of my datatypes are foxpro data types and may not be compatibl...
What kind of dbf file are you working with? (There are several, e.g. dBase, FoxPro etc that are not 100% compatible.) I have gotten this to work with the Microsoft Visual FoxPro OleDB Provider from C#, you might give that a shot instead of using the dBase ODBC driver.
How can I save a DataTable to a .DBF?
[ "", "c#", "odbc", "dbf", "" ]
Let's say I have a class like this: ``` class ApplicationDefs{ public static final String configOption1 = "some option"; public static final String configOption2 = "some other option"; public static final String configOption3 = "yet another option"; } ``` Many of the other classes in my application are using these op...
You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e. ``` public static final String configOption1 = "some option".intern(); ``` This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will...
No, it's part of the JLS, I'm afraid. This is touched upon, briefly, in Java Puzzlers but I don't have my copy to hand. I guess you might consider having these constants defined in a properties file, and have the class that loads them periodically. Reference: <http://java.sun.com/docs/books/jls/third_edition/html/exp...
Are all compile-time constants inlined?
[ "", "java", "inlining", "compile-time-constant", "" ]
How to query to get count of matching words in a field, specifically in MySQL. simply i need to get how many times a "search terms"appear in the field value. for example, the value is "one two one onetwo" so when i search for word "one" it should give me 3 is it possible? because currently i just extract the value ou...
You could create a function to be used directly within SQL, in order to do it all in one step. Here is [a function which I found on the MySQL website](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html) : ``` delimiter || DROP FUNCTION IF EXISTS substrCount|| CREATE FUNCTION substrCount(s VARCHAR(255), ss V...
Are you looking to find a query that, given a list of words, returns the number of matching words in a database field? eg: Database table has ``` ID Terms 1 cat, dog, bird, horse ``` then running a check on the words "cat, horse" returns 2? If so, I suggest you do your checking *outside* of SQL, in whatever...
MySQL count matching words
[ "", "sql", "mysql", "database", "" ]
OK, this is an odd request, and it might not even be fully true... but I'm upgrading someone's system ... and they are using OSCommerce (from a long time ago). It appears their variables are referrenced without a dollar sign in front of them (which is new to me). I haven't done PHP in about 7 years, and I've always us...
I believe OSCommerce actually DEFINES these values, so the usage is correct (without the $). Look for ``` define("DB_SERVER", "localhost"); ``` or something similar. In other words, do *not* go through and update these with a $ before if they're actually defined constants.
If i remember correctly a big difference is the lack of 'register\_globals' being default to 'ON'. You might need to change a lot of instances here $var should be $\_REQUEST['var'] or the appropriate $\_GET/$\_POST super globals. And as far as constants are concerned you should access them as such: ``` constant('MY_C...
PHP 3 to PHP 5 Upgrade... Variables in 3 didn't have $ in front... is there a setting for back compat?
[ "", "php", "variables", "" ]
One of the core fields present on several of my app's major database tables needs to be changed from varchar(5) to varchar(8). The list of stored procedures that depend on these tables is extremely long, not to mention the changes that would have to be made in my Data Access Layer (ASP.NET 2.0 DataSet with TableAdapter...
You might be interested in this [essay](http://www.agiledata.org/essays/databaseRefactoring.html) by Scott Ambler on Database Refactoring. I think he also has a book on it. The basic idea, I believe, will be to introduce a new column with the proper width, copy existing data to the new column, implement a trigger to sy...
While it doesn't help you much now you could (in the future) look to use a code generation tool that generates data access layers and any necessary (non-custom) stored procedures for you. I use .netTiers and changing something like a field name, data type or column size (like your situation) is very simple. If you're ...
What's the best way to update my asp.net application / database after changing the schema?
[ "", "c#", "asp.net", "sql-server-2005", "" ]
My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for this?
Ugh, I hate it when people try to guess at which characters are valid. Besides being completely non-portable (always thinking about Mono), both of the earlier comments missed more 25 invalid characters. ``` foreach (var c in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, '-'); } ``` Or in VB: ...
To strip invalid characters: ``` static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); // Builds a string out of valid chars var validFilename = new string(filename.Where(ch => !invalidFileNameChars.Contains(ch)).ToArray()); ``` To replace invalid characters: ``` static readonly char[] inval...
Is there a way of making strings file-path safe in c#?
[ "", "c#", ".net", "string", "filepath", "" ]
How to truncate and shrink large log files in SQL Server 2005? How to apply truncation at regular intervals? Is there any difference between truncation and shrinking? Thanks in advance
Use DBCC SHRINKFILE and schedule it as a job that runs regularly (preferably during off-hours). Just be aware that there is a performance hit from regularly growing and shrinking the log file. If you have the space, you may want to set the file size to the maximum that it normally grows to and just leave it.
Reliable shrinking is achieved by * Backup (can be truncate only) * Checkpoint * Shrink
How to truncate and shrink log files?
[ "", "sql", "sql-server-2005", "transaction-log", "" ]
So I have this GIF file on my desktop (it's a 52 card deck of poker cards). I have been working on a program that cuts it up into little acm.graphics.GImages of each card. Now, however, I want to write those GImages or pixel arrays to a file so that I can use them later. I thought it would be as straight forward as wri...
Something along these lines should do the trick (modify the image type, dimensions and pixel array as appropriate): ``` BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster raster = image.getRaster(); for ( i=0; i<width; i++ ) { for ( j=0; j<height; j++ ) { i...
I had to create GIF's out of Java Images for a university project, and I found this. I would recommend Acme's Open-Source GifEncoder Class. Nice and easy to use, I still remember it over 2 years later. Here's the link: [<http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html>](http://www.acme.com/java/soft...
Writing a GIF file in Java
[ "", "java", "gif", "" ]
I am writing a JSR-168 portlet that can be added to a container multiple times. Each container (Liferay, JBoss, etc.) has its own internal way of differentiating between multiple instantiations of the same portlet. I, however, would like to uniquely identify my portlet instance inside the `doView()` method itself. Is...
Portlet 1.0 (168) provides the [RenderResponse.getNamespace()](http://portals.apache.org/pluto/portlet-1.0-apidocs/javax/portlet/RenderResponse.html) method, which should be unique per portlet instance. From spec: **PLT.12.3.4 Namespace encoding**: > The getNamespace method must provide > the portlet with a mechanism...
No, there is no common ID for the instance. I have implemented a portlet container myself, there is no per instance id in the public api - the container has one, of cause. The portlet session (`javax.portlet.PortletRequest#getPortletSession()`) is unique for one portlet (definition by tag in `portlet.xml`) and one user...
Uniquely identify an instance of a JSR-168 portlet
[ "", "java", "portlet", "" ]
I'm using version 3.3.2, I know that regular Eclipse for Java does variable highlighting. Notepad++ does it regardless of what language you're using (if you select any text, it highlights similar text) I know it's not critically important, and a back/forward incremental search is an adequate workaround, but it would b...
You can download new PDT 2.0 All-in-one together with Eclipse 3.4 - this feature as "mark occurences" is here an there is some new features. I use it now and found it stable. <http://www.eclipse.org/pdt/downloads/>
I believe 'mark occurrences' is the option which is the closest of what you call 'syntax highlighting' But [PHP Development Tools](http://www.eclipse.org/pdt/) (PDT) had not that feature in 2007, according to [this discussion](http://dev.eclipse.org/newslists/news.eclipse.tools.php/msg01188.html). However [this bug](...
Can you enable variable highlighting with Eclipse PDT?
[ "", "php", "eclipse", "ide", "eclipse-pdt", "" ]
I am trying to use the `System.Net.Mail.MailMessage` class in C# to create an email that is sent to a list of email addresses all via `BCC`. I do not want to include a `TO` address, but it seems that I must because I get an exception if I use an empty string for the `TO` address in the `MailMessage` constructor. The er...
I think if you comment out the whole `emailMessage.To.Add(sendTo);` line , it will send the email with `To` field empty.
Do the same thing you do for internal mail blasts where you don't want people to reply-to-all all the time. Send it **to** yourself (or a dummy account), then add your BCC list.
Sending Mail via SMTP in C# using BCC without TO
[ "", "c#", "email", "smtp", "bcc", "" ]
I have a MySQL query in which I want to include a list of ID's from another table. On the website, people are able to add certain items, and people can then add those items to their favourites. I basically want to get the list of ID's of people who have favourited that item (this is a bit simplified, but this is what i...
You can't access variables in the outer scope in such queries (can't use `items.id` there). You should rather try something like ``` SELECT items.name, items.color, CONCAT(favourites.userid) as idlist FROM items INNER JOIN favourites ON items.id = favourites.itemid WHERE items.id = $someid GROUP BY...
OP almost got it right. `GROUP_CONCAT` should be wrapping the columns in the subquery and not the [complete subquery](https://stackoverflow.com/a/4455991/838733) (I'm dismissing the separator because comma is the default): ``` SELECT i.*, (SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist ...
Using GROUP_CONCAT on subquery in MySQL
[ "", "mysql", "sql", "group-concat", "mysql-error-1242", "" ]
We are experiencing an exceedingly hard to track down issue where we are seeing ClassCastExceptions *sometimes* when trying to iterate over a list of unmarshalled objects. The important bit is *sometimes*, after a reboot the particular code works fine. This seems to point in the direction of concurrency/timing/race con...
Out of despair we turned to synchronizing on the `JAXBContext.class` object, seeing this as the only remaining possibility for some race condition and at least we have not been able to reproduce this issue again. Here's the critical code: ``` synchronized (JAXBContext.class) { context = JAXBContext.newInstance(pac...
I get this exception ONLY when I forget to tell JAXBContext about ALL to-be-marshalled types it could be dealing with. ``` JAXBContext.newInstance(MyClass1.class,MyClass2.class, [...]); ```
Intermittent ClassCastException from ElementNSImpl to own type during unmarshalling
[ "", "java", "exception", "jaxb", "race-condition", "unmarshalling", "" ]
Java 5 introduced generics, and they were added to many interfaces in the `java.lang` package. However, `Cloneable` did not get generics. I wonder why? --- **Edit:** In reply to the answers of @Jon and @litb, and the comment of @Earwicker, I was thinking `Cloneable` might be: ``` public interface Cloneable<T> { ...
The Cloneable interface doesn't contain any members. What would be the point of making it generic? (If Cloneable contained the clone() method, it would make sense - but that's declared in java.lang.Object.) EDIT: clone() is in java.lang.Object as it has an implementation (which does a field-by-field copy). A better d...
If `Cloneable` was `Cloneable<T>`, then it would be impossible to do this: ``` class A extends B implements Cloneable<A> class B implements Cloneable<B> ``` You can't implement the same interface with different parameters, and class `A` implements `Cloneable<A>` and `Cloneable<B>`.
Why is Java's Cloneable Interface Not Generic?
[ "", "java", "generics", "" ]
Is there some easy way to pad Strings in Java? Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
Apache [`StringUtils`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html) has several methods: [`leftPad`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int)), [`rightPad`](https...
Since Java 1.5, [`String.format()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-) can be used to left/right pad a given string. ``` public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } public static String pa...
How can I pad a String in Java?
[ "", "java", "string", "padding", "" ]
I've trying to achieve something like this: ``` class Base { public: Base(string S) { ... }; } class Derived: Base { public: int foo; string bar() { return stringof(foo); // actually, something more complex }; Derived(int f) : foo(f), Base(bar()) { }; } ``` Now, this doesn't work as I...
Yes, using a function (static class method or regular function) that takes *foo* as a parameter and returns a string is a good solution. You can call this same function from Derived::bar to prevent code duplication. So, your constructor would look like this: ``` Derived(int f) : Base(stringof(f)), foo(f) {} ``` I pla...
You can only call static functions in the initializer list. The way you have it in your code: ``` class Derived: Base { public: int foo; string bar() { return stringof(foo); // actually, something more complex }; Derived(int f) : foo(f), Base(bar()) { }; } ``` Will still initialize Base first, and...
How to pass method result as parameter to base class constructor in C++?
[ "", "c++", "inheritance", "constructor", "initialization", "composition", "" ]
I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between: ``` public void myFunction(ref MyClass someClass) ``` and ``` public void myFunction(out MyClass someClass) ``` Which should I use and why?
`ref` tells the compiler that the object is initialized before entering the function, while `out` tells the compiler that the object will be initialized inside the function. So while `ref` is two-ways, `out` is out-only.
The `ref` modifier means that: 1. The value is already set and 2. The method can read and modify it. The `out` modifier means that: 1. The Value isn't set and can't be read by the method *until* it is set. 2. The method *must* set it before returning.
What's the difference between the 'ref' and 'out' keywords?
[ "", "c#", "reference", "keyword", "out", "ref", "" ]
I'm trying to use the `Html.DropDownList` extension method but can't figure out how to use it with an enumeration. Let's say I have an enumeration like this: ``` public enum ItemTypes { Movie = 1, Game = 2, Book = 3 } ``` How do I go about creating a dropdown with these values using the `Html.DropDownLis...
## For MVC v5.1 use Html.EnumDropDownListFor ``` @Html.EnumDropDownListFor( x => x.YourEnumField, "Select My Type", new { @class = "form-control" }) ``` --- ## For MVC v5 use EnumHelper ``` @Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "Select My Type", new { @clas...
I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute. For example: ``` public enu...
How do you create a dropdownlist from an enum in ASP.NET MVC?
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
The `JFileChooser` seems to be missing a feature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get replaced when the user starts typing). Is there a way around this?
If I understand you correctly, you need to use the `setSelectedFile` method. ``` JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setSelectedFile(new File("fileToSave.txt")); jFileChooser.showSaveDialog(parent); ``` The file doesn't need to exist. If you pass a File with an absolute path, `JFileChooser` ...
setSelectedFile doesn't work with directories as mentioned above, a solution is ``` try { FileChooserUI fcUi = fileChooser.getUI(); fcUi.setSelectedFile(defaultDir); Class<? extends FileChooserUI> fcClass = fcUi.getClass(); Method setFileName = fcClass.getMethod("setFileName", String.class); setFil...
How do I set a suggested file name using JFileChooser.showSaveDialog(...)?
[ "", "java", "swing", "jfilechooser", "" ]
I have a query which is meant to show me any rows in table A which have not been updated recently enough. (Each row should be updated within 2 months after "month\_no".): ``` SELECT A.identifier , A.name , TO_NUMBER(DECODE( A.month_no , 1, 200803 , 2, 200804 , 3, 2008...
This is not possible directly, because chronologically, WHERE happens *before* SELECT, which always is the last step in the execution chain. You can do a sub-select and filter on it: ``` SELECT * FROM ( SELECT A.identifier , A.name , TO_NUMBER(DECODE( A.month_no , 1, 200803 , 2, 200804 ,...
``` SELECT A.identifier , A.name , TO_NUMBER(DECODE( A.month_no , 1, 200803 , 2, 200804 , 3, 200805 , 4, 200806 , 5, 200807 , 6, 200808 , 7, 200809 , 8, 200810 , 9, 200811 , 10, 200812 , 11, 200701 ...
Using an Alias in a WHERE clause
[ "", "sql", "oracle", "alias", "decode", "ora-00904", "" ]
How can I remove duplicate values from an array in PHP?
Use [`array_unique()`](http://php.net/array_unique) for a one-dimensional array. From the PHP manual: > Takes an input array and returns a new array without duplicate values. > > Note that keys are preserved. If multiple elements compare equal under the given flags, then the key and value of the first equal element wi...
Use `array_values(array_unique($array));` `array_unique`: for unique array `array_values`: for reindexing
How to remove duplicate values from an array in PHP
[ "", "php", "arrays", "duplicate-data", "" ]
I'm implementing a JAX-WS webservice that will be consumed by external Java and PHP clients. The clients have to authenticate with a username and password stored in a database per client. What authentication mechanism is best to use to make sure that misc clients can use it?
Basic WS-Security would work with both Java and PHP clients (amongst others) plugged in to JAAS to provide a database backend . How to implement that kind of depends on your container. Annotate your web service methods with the @RolesAllowed annotation to control which roles the calling user must have. All J2EE contain...
For our Web Service authentication we are pursuing a twofold approach, in order to make sure that clients with different prerequisites are able to authenticate. * Authenticate using a username and password parameter in the HTTP Request Header * Authenticate using HTTP Basic Authentication. Please note, that all traff...
JAX-WS authentication against a database
[ "", "java", "web-services", "security", "" ]
As the title says, whats the difference between ``` MyFunction = function() { } ``` and ``` function MyFunction() { } ``` Nothing? **Duplicate:** [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionna...
The first form is actually a variable with an **anonymous function** assigned to it, the second is a **declared function**. They're *almost* interchangeable, but have some differences: debuggers have a harder time with anons (because they lack a name) and the JS engine can directly access declared functions wherever t...
I think you mean ``` var MyFunction = function() { } ``` And in many cases, there is little difference. The var syntax is sometimes useful when you are inside some sort of wrapping class and want to be sure of your namespace (like in greasemonkey). Also, I believe the function-are-constructors stuff (with .prototyp...
What is the difference between these 2 function syntax types
[ "", "javascript", "" ]
Assuming the file exists (using `os.path.exists(filename)` to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.
[os.stat()](http://docs.python.org/library/os.html#os.stat) ``` import os filename = "/etc/fstab" statbuf = os.stat(filename) print("Modification time: {}".format(statbuf.st_mtime)) ``` Linux does not record the creation time of a file ([for most fileystems](https://unix.stackexchange.com/q/24441/61642)).
``` >>> import os >>> f = os.path.getmtime('test1.jpg') >>> f 1223995325.0 ``` since the beginning of (epoch)
How do I get the time a file was last modified in Python?
[ "", "python", "file", "time", "" ]
I am attempting to mock a call to an indexed property. I.e. I would like to moq the following: ``` object result = myDictionaryCollection["SomeKeyValue"]; ``` and also the setter value ``` myDictionaryCollection["SomeKeyValue"] = myNewValue; ``` I am doing this because I need to mock the functionality of a class my...
It appears that what I was attempting to do with MOQ is not possible. Essentially I was attempting to MOQ a HTTPSession type object, where the key of the item being set to the index could only be determined at runtime. Access to the indexed property needed to return the value which was previously set. This works for i...
It's not clear what you're trying to do because you don't show the declaration of the mock. Are you trying to mock a dictionary? `MyContainer[(string s)]` isn't valid C#. This compiles: ``` var mock = new Mock<IDictionary>(); mock.SetupGet( p => p[It.IsAny<string>()]).Returns("foo"); ```
How to MOQ an Indexed property
[ "", "c#", "tdd", "mocking", "moq", "" ]
Using jQuery, **how do you match elements that are prior to the current element in the DOM tree?** Using `prevAll()` only matches previous siblings. eg: ``` <table> <tr> <td class="findme">find this one</td> </tr> <tr> <td><a href="#" class="myLinks">find the previous .findme</a></td> ...
Ok, here's what I've come up with - hopefully it'll be useful in many different situations. It's 2 extensions to jQuery that I call `prevALL` and `nextALL`. While the standard `prevAll()` matches previous siblings, `prevALL()` matches ALL previous elements all the way up the DOM tree, similarly for `nextAll()` and `nex...
Presumably you are doing this inside an onclick handler so you have access to the element that was clicked. What I would do is do a prevAll to see if it is at the same level. If not, then I would do a parent().prevAll() to get the previous siblings of the parent element, then iterate through those backwards, checking t...
jQuery to find all previous elements that match an expression
[ "", "javascript", "jquery", "" ]
i wind up having about 20 different parameters in the constructor of the model class, one for each service? Is this normal or a sign that something is off.
I think, categorically, that your controller is interacting with too many services. I've not seen your code - so I'm going off assumptions - but it seems to me that your controller is composing business logic by calling numerous "small" services, rather than drawing on fewer, "larger" services that compose business log...
You might try consolidating some services or think about refactoring the controller-view parts in to smaller scoped components. Also, a dependency injection style framework like Spring can help with things like this.
MVC lots of services make the controller constructor very large .
[ "", "c#", "mvp", "" ]
I'm tackling project euler's [problem 220](http://projecteuler.net/index.php?section=problems&id=220) (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!) So far I have: ``` D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") ...
Python strings are not going to be the answer to this one. Strings are stored as immutable arrays, so each one of those replacements creates an entirely new string in memory. Not to mention, the set of instructions after 10^12 steps will be at least 1TB in size if you store them as characters (and that's with some mino...
The trick is in noticing which patterns emerge as you run the string through each iteration. Try evaluating `iterate(D,n)` for n between 1 and 10 and see if you can spot them. Also feed the string through a function that calculates the end position and the number of steps, and look for patterns there too. You can then...
How to work with very long strings in Python?
[ "", "python", "" ]
Is there anything better than a [Trie](http://en.wikipedia.org/wiki/Trie) for this situation? * Storing a list of ~100k English words * Needs to use minimal memory * Lookups need to be reasonable, but don't have to be lightning fast I'm working with Java, so my first attempt was to just use a Set<String>. However, I'...
What are you doing? If it's spell checking, you could use a bloom filter - see this [code kata](http://codekata.pragprog.com/2007/01/kata_five_bloom.html).
One structure I saw for minimizing space in a spelling dictionary was to encode each word as: * the number of characters (a byte) in common with the last; and * the new ending. So the word list ``` HERE would encode as THIS sanctimonious 0,sanctimonious sanction ...
Space-Efficient Data Structure for Storing a Word List?
[ "", "java", "data-structures", "" ]
I got a table with a custom TableCellEditor (extending DefaultCellEditor) with a JFormattedTextField as the editor component. Now I got problem: when I press a separate button while editing. When the button is pressed, the editor remains "open and active" while I'd want it to stop editing so that the changes made woul...
You may try `jtable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);`
Thanks asalamon74, that works quite nicely. There's debate over the thing at Sun Bug Database : [Bug 4724980: JTable: Add API to control what happens to edits when table loses focus.](https://bugs.java.com/bugdatabase/view_bug?bug_id=4724980) (also other bug entries are found). The terminateEditOnFocusLost turns on "c...
How to stop editing with DefaultCellEditor when a separate JBtton is pressed
[ "", "java", "swing", "focus", "jtable", "tablecelleditor", "" ]
I am writing a console program in C#. Is there a way I can use a Console.Clear() to only clear certain things on the console screen? Here's my issue: I have a logo (I put it on screen using Console.WriteLine()) and a 2d array which I want to keep constant and clear everything below it.
You could use a custom method to clear parts of the screen... ``` static void Clear(int x, int y, int width, int height) { int curTop = Console.CursorTop; int curLeft = Console.CursorLeft; for (; height > 0;) { Console.SetCursorPosition(x, y + --height); Console.Write(new string(' ',wid...
**Edit**: The answer [here](https://stackoverflow.com/questions/377927/c-console-consoleclear-problem#378036) shows how you can manipulate the console much more powerfully than I was aware. What I originally wrote still applies, and might be useful if you don't have these facilities available, perhaps in a different la...
c# console, Console.Clear problem
[ "", "c#", "console-application", "" ]
Good morning, I am working on a C# winform application that is using validation for the controls. The issue I'm having is that when a user clicks into a textbox and attempts to click out, the validation fires and re-focuses the control, basically the user cannot click out of the control to another control. My desired...
The simplest way would be just to put all the validation in the Submit button handler, instead of having it in the controls.
The form has AutoValidate property, that can be set to allow focus change
Textbox validation, focus switching issue
[ "", "c#", "winforms", "validation", "controls", "focus", "" ]
There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.
I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation. <http://docs.python.org/library/signal.html> So your code is going to look something like this. ``` import ...
An improvement on @rik.the.vik's answer would be to use the [`with` statement](http://www.python.org/dev/peps/pep-0343/) to give the timeout function some syntactic sugar: ``` import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def ...
How to limit execution time of a function call?
[ "", "python", "" ]
I'm getting some really wierd linking errors from a class I wrote. I am completely unable to find anything that will describe what is happening. Visual Studio (Windows XP) > players.obj : error LNK2019: unresolved external symbol "public: \_\_thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) refere...
When you define your template in a .cpp file, you have to explicitly instantiate it with all the types / template parameters known the template will be used beforehand like this (put it in the .cpp file): ``` template class TreeNode<Player>; ``` If you don't know with which template parameters the template will be us...
Well you are declaring ~TreeNode(), but are you defining it? When you declare the destructor you stop the compiler from generating one for you, but you must define it somewhere, even if it is empty. If your intent was to have an empty destructor you have two options: -Remove the declaration of ~TreeNode() entirely, ...
C++ Linking Errors: Undefined symbols using a templated class
[ "", "c++", "linker", "" ]
In a software-project written in java you often have resources, that are part of the project and should be included on the classpath. For instance some templates or images, that should be accessible through the classpath (getResource). These files should be included into a produced JAR-file. It's clear that these reso...
I prefer your latter solution: a separate directory that mimicks the source code’s package structure. This way they won’t clobber your source code but will be right next to the compiled class files in the packaged JAR file.
[Maven](http://maven.apache.org/) puts them into src/main/resources/ (Java code would go to src/main/java/). The main reason is that Maven can compile code in various languages and it makes sense to keep them separate so one compile isn't confused by files for another. In the case of resources, Maven will replace vari...
How you organize non-source-resources available at the classpath in your java-project?
[ "", "java", "resources", "classpath", "structure", "" ]
I am trying to implement a ListView data control for displaying and editing lookup table/ application level variables. There are multiple entity classes which can be bound to the ListView, so the ItemTemplate needs to be dynamically bound to the selected entity object. For example i have: ``` AddressType { AddressTyp...
Ok in answer to your questions: * You can iterate over the ListViewItems by using the OnItemDataBound event in the parent ListView. You can then use this to databind nested child ListViews (or insert Html or manipulate the contents of the list in any way you need). Make sure you use ListViewItemEventArgs in your code ...
maybe your answer is to bind a repeater inside the itemTemplate and the repeater will get the datasource of the <%# Eval("DataDictionary") %>.
Asp.NET ListView Data Control Dynamically Databind
[ "", "c#", "asp.net", "data-binding", "listview", "" ]
I've saved an entire webpage's html to a string, and now **I want to grab the "href" values** from the links, preferably with the ability to save them to different strings later. What's the best way to do this? I've tried saving the string as an .xml doc and parsing it using an XPathDocument navigator, but (surprise s...
Regular expressions are one way to do it, but it can be problematic. Most HTML pages can't be parsed using standard html techniques because, as you've found out, most don't validate. You could spend the time trying to integrate [HTML Tidy](http://tidy.sourceforge.net/) or a similar tool, but it would be much faster t...
I can recommend the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). I've used it in a few cases where I needed to parse HTML and it works great. Once you load your HTML into it, you can use [XPath](http://msdn.microsoft.com/en-us/library/ms256115.aspx) expressions to query the document and get your anchor...
C# - Best Approach to Parsing Webpage?
[ "", "c#", "html", "xml", "html-content-extraction", "" ]
Is there a way to debug javascript using Safari 3.2 in Windows Vista? I found a [link](http://pietschsoft.com/post/2007/12/Safari-3-for-Windows-Enable-JavaScript-Debugging.aspx) to a debugger named Drosera but I can't get it to work because the information seams to be outdated.
Well, apart from the **Error Console** that can be opened from the Develop menu (which in turn can be enabled in (Prefences / Advanced / Show Develop menu in menu bar) there aren't many javascript debugging options in Safari AFAIK. Still, the error console is quite useful as it shows javascript errors and also lets yo...
I stumbled across this question via google - although it's rather old, none of the answers are quite right, (due to safari being updated to 5.1 since this question was asked) Enable the `develop menu` as DrJokepu mentioned: > Prefences / Advanced / Show Develop menu in menu bar Now you'll see an option in the page m...
Debugging javascript in Safari for Windows
[ "", "javascript", "windows", "windows-vista", "safari", "cross-browser", "" ]
What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format. I tried the following function: ``` function get_date_offset($start_date, $end_date) { $start_time = strtotime($start_date); $end_time = strtotime($end_date); return round(($end_time-$sta...
If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help: ``` function dateDifference($date1, $date2) { $d1 = (is_string($date1) ? strtotime($date1) : $date1); $d2 = (is_string($date2) ? strtotime($date2) : $date2); $diff_secs = abs($d1 - $d2); $base...
The PEAR Date class offers all kinds of features for finding the differences between dates and about 1000 other things as well. The docs for it are [here...](http://pear.php.net/package/Date/)
PHP date calculation
[ "", "php", "windows", "date", "format", "" ]
I have a multi-browser page that shows vertical text. As an ugly hack to get text to render vertically in all browsers I've created a custom page handler that returns a PNG with the text drawn vertically. Here's my basic code (C#3, but small changes to any other version down to 1): ``` Font f = GetSystemConfiguredFo...
To fix the text "blockiness", can't you just do... ``` g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; ``` after this line... ``` Graphics g = Graphics.FromImage( (Image) image ); ```
IIRC you need to specify the PixelFormat in the bitmap constructor.
Can you make an alpha transparent PNG with C#?
[ "", "c#", ".net", "gdi+", "" ]
Our logging class, when initialised, truncates the log file to 500,000 bytes. From then on, log statements are appended to the file. We do this to keep disk usage low, we're a commodity end-user product. Obviously keeping the first 500,000 bytes is not useful, so we keep the last 500,000 bytes. Our solution has some...
> "I would probably create a new file, seek in the old file, do a buffered read/write from old file to new file, rename the new file over the old one." I think you'd be better off simply: ``` #include <fstream> std::ifstream ifs("logfile"); //One call to start it all. . . ifs.seekg(-512000, std::ios_base::end); // ...
If you happen to use windows, don't bother copying parts around. Simply tell Windows you don't need the first bytes anymore by calling [`FSCTL_SET_SPARSE`](http://msdn.microsoft.com/en-us/library/aa364596%28VS.85%29.aspx) and [`FSCTL_SET_ZERO_DATA`](http://msdn.microsoft.com/en-us/library/aa364597%28VS.85%29.aspx)
Remove all but the last 500,000 bytes from a file with the STL
[ "", "c++", "logging", "stl", "" ]
I have a database for an E-commerce storefront. MSSQL 2008. I have a table called Products and a table called Tags. This is a many to many relationship that is bound together by a table called ProductTags. Products: id, name, price Tags: id, name, sortorder, parentid(allow nulls) ProductTags: productid, tagid...
``` SELECT Tags.ID, Tags.Name, Tags.SortOrder, Tags.ParentID, COUNT(DISTINCT ProductTags.ProductID) AS ProductCount, COUNT(DISTINCT ChildTags.ID) AS ChildTagCount FROM Tags LEFT OUTER JOIN ProductTags ON Tags.ID = ProductTags.TagID LEFT OUTER JOIN Tags ChildTags ON Tags.ID = ChildTags.ParentID GROUP BY T...
``` Select T.id, T.Name, T.sortorder, T.parentid, (select count(*) from productstags where tagid=T.TagId) as ProductCount, (select count(*) from Tags where parentid=T.TagId) as ChildTagCount from Tags T ``` would that work?
SQL Query for Product-Tag relationship
[ "", "sql", "" ]
I have a method which is given the parameter "bool sortAscending". Now I want to use LINQ to create sorted list depending on this parameter. I got then this: ``` var ascendingQuery = from data in dataList orderby data.Property ascending select data; var descendingQuery = fr...
You can easily create your own extension method on IEnumerable or IQueryable: ``` public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool descending) { return descending ? source.OrderByDescending(keySelecto...
In terms of how this is implemented, this changes the *method* - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query... ``` var qry = from .... // or just dataList.AsEnumerable()/AsQueryable() if(sortAscending) { qry = qry.OrderBy(x=>x.Property);...
ascending/descending in LINQ - can one change the order via parameter?
[ "", "c#", "linq", "" ]
**What happens in the memory when a class instantiates the following object?** ``` public class SomeObject{ private String strSomeProperty; public SomeObject(String strSomeProperty){ this.strSomeProperty = strSomeProperty; } public void setSomeProperty(String strSomeProperty){ this.st...
Let's step through it: ``` SomeObject so1 = new SomeObject("some property value"); ``` ... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as: ``` String tmp = new String("some property value"); SomeObject so1 = new SomeObject(tmp); // Not that you wou...
[Determining Memory Usage in Java](http://www.javaspecialists.eu/archive/Issue029.html) by Dr. Heinz M. Kabutz gives a precise answer, plus a program to calculate the memory usage. The relevant part: > 1. The class takes up at least 8 bytes. So, if you say new Object(); you will allocate 8 bytes on the heap. > 2. Each...
Steps in the memory allocation process for Java objects
[ "", "java", "object", "memory", "heap-memory", "" ]
I have two implementations of a method, one for value types and another for reference types: ``` public static Result<T> ImplRef(T arg) where T : class {...} public static Result<T> ImplVal(T arg) where T : struct {...} ``` I want to write a method which calls the correct implementation like this ``` public static R...
The idea with generics is usually to do the same logic with whichever inputs you are given, although obviously you need to be practical. Personally, I'd probably use two different methods, rather than brute-force them into the same method, but that would make it hard to call from a generic method just knowing about `T`...
Do you actually *use* the constraints in `ImplRef` and `ImplVal`? If not (i.e. if it's just so you can behave differently) you could drop the constraints, make the methods private, and just call them appropriately from `Generic` - or possibly have: ``` public static Result<T> ImplRef(T arg) where T : class { retu...
How to make a .Net generic method behave differently for value types and reference types?
[ "", "c#", "generics", "" ]
Hey there, I've got a block of HTML that I'm going to be using repeatedly (at various times during a users visit, not at once). I think that the best way to accomplish this is to create an HTML div, hide it, and when needed take its innerHTML and do a replace() on several keywords. As an example HTML block... ``` <div...
I doubt there will be anything more efficient. The alternative would be splitting it into parts and then concatenating, but I don't think that would be much efficient. Perhaps even less, considering that every concatenation results in a new string which has the same size as its operands. **Added:** This is probably th...
It looks like you want to use a template. ``` //Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output. function template( templateid, data ){ return document.getElementById( templateid ).innerHTML .replace( /%(\w*)%/g, // or /{(\w*)}/g for "{this} instead of %this%" ...
Efficient Javascript String Replacement
[ "", "javascript", "string", "performance", "replace", "" ]
Which is the best PHP library for openID integration?
For PHP, I find **[Zend Framework OpenID Component](http://framework.zend.com/manual/en/zend.openid.html)** to be really good. You can also see all available OpenID libraries at [**this link**](http://wiki.openid.net/Libraries)
The [PHP OpenID library](http://openidenabled.com/php-openid/) is good.
PHP library for openID
[ "", "php", "openid", "" ]
Does dot net have an interface like IEnumerable with a count property? I know about interfaces such as IList and ICollection which do offer a Count property but it seems like these interfaces were designed for mutable data structures first and use as a read only interface seems like an afterthought - the presence of an...
The key difference between the ICollection family and the IEnumerable family is the absence of certainty as to the count of items present (quite often the items will be generated/loaded/hydrated as needed) - in some cases, an Enumerable may not ever finish generating results, which is why the Count is missing. Derivin...
As of .Net 4.5, there are two new interfaces for this: [`IReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/hh881542%28v=vs.110%29) and [`IReadOnlyList<T>`](http://msdn.microsoft.com/en-us/library/hh192385%28v=vs.110%29). `IReadOnlyCollection<T>` is `IEnumerable<T>` with a `Count` property added, `IReadO...
Does dot net have an interface like IEnumerable with a Count property?
[ "", "c#", ".net", "" ]
To do DataBinding of the `Document` in a WPF `RichtextBox`, I saw 2 solutions so far, which are to derive from the `RichtextBox` and add a `DependencyProperty`, and also the solution with a "proxy". Neither the first or the second are satisfactory. Does somebody know another solution, or instead, a commercial RTF cont...
There is a much easier way! You can easily create an attached `DocumentXaml` (or `DocumentRTF`) property which will allow you to bind the `RichTextBox`'s document. It is used like this, where `Autobiography` is a string property in your data model: ``` <TextBox Text="{Binding FirstName}" /> <TextBox Text="{Binding La...
I know this is an old post, but check out the [Extended WPF Toolkit](https://github.com/xceedsoftware/wpftoolkit). It has a RichTextBox that supports what you are tryign to do.
Richtextbox wpf binding
[ "", "c#", "wpf", "data-binding", "richtextbox", "" ]
Here's the situation: we have an Oracle database we need to connect to to pull some data. Since getting access to said Oracle database is a real pain (mainly a bureaucratic obstacle more than anything else), we're just planning on linking it to our SQL Server and using the link to access data as we need it. For one of...
If the inner join significantly reduces the total number of rows, then option 1 will result in much less network traffic (since you won't have all the rows from table1 having to go across the db link
I'd go with your first option especially if your query contains a where clause to select a sub-set of the data in the tables. It will require less work on both servers, assuming there are indices on the tables in the Oracle server that support the join operation.
Join in linked server or join in host server?
[ "", "sql", "sql-server-2005", "oracle", "join", "linked-server", "" ]
I have a couple of tables which are used to log user activity for an application. The tables looks something like this (pseudo code from memory, may not be syntactically correct): ``` create table activity ( sessionid uniqueidentifier not null, created smalldatetime not null default getutcdate() ); create table a...
There's probably more efficient ways to do this as well, but this is closest to your original: ``` truncate table activity_summary; insert into activity_summary (sessionid, first_activity_desc, last_activity_summary) select a.sessionid ,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a....
``` insert into activity_summary (sessionid, first_activity_desc, last_activity_desc) select agg.sessionid, adf.activity_description, adl.activity_description from (SELECT sessionid, MIN(created) as firstcreated, MAX(created) as lastcreated from activity_detail group by session...
SQL Server - update one table with first and last rows from another table
[ "", "sql", "sql-server", "sql-server-2005", "" ]
An answer and subsequent [debate in the comments](https://stackoverflow.com/questions/360899/c-math-problem#360931) in another thread prompted me to ask: In C# || and && are the short-circuited versions of the logical operators | and & respectively. Example usage: ``` if (String.IsNullOrEmpty(text1) | String.IsNullO...
> In terms of coding practice which is the better to use and why? Simple answer: always use the short-circuited versions. There’s simply no reason not to. Additionally, you make your code clearer because you express your *intent*: logical evaluation. Using the bitwise (logical) operations implies that you want just th...
I am going to answer this question in reverse: when is the **only** time I use the logic operators? I will sometimes use the logical comparisons when I have a series of (low-cost) conditionals that must all be met. For example: ``` bool isPasswordValid = true; isPasswordValid &= isEightCharacters(password); isPasswo...
What is the best practice concerning C# short-circuit evaluation?
[ "", "c#", "" ]
I know I could have an attribute but that's more work than I want to go to... and not general enough. I want to do something like ``` class Whotsit { private string testProp = "thingy"; public string TestProp { get { return testProp; } set { testProp = value; } } } ... Whotsit who...
No, there's nothing to do this. The expression `whotsit.TestProp` will evaluate the property. What you want is the mythical "infoof" operator: ``` // I wish... MemberInfo member = infoof(whotsit.TestProp); ``` As it is, you can only use reflection to get the property by name - not from code. (Or get all the propertie...
It is possible (without reflection) but only with latest C# 3.0 **quick & very very dirty** ``` class Program { static void Main() { string propertyName = GetName(() => AppDomain.CurrentDomain); Console.WriteLine(propertyName); // prints "CurrentDomain" Console.ReadLine(); } p...
How do I get the name of a property from a property in C# (2.0)
[ "", "c#", "reflection", "properties", "" ]
I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the following signature: ``` public CustomObject get(String key, Date ifModifiedSince) ``` Basically the method is supposed to return the `CustomObject` as...
It sounds like you actually want to return two items: the response code and the object found. You might consider creating a lightweight wrapper that holds both and return them together. ``` public class Pair<K,V>{ public K first; public V second; } ``` Then you can create a new Pair that holds your response code ...
With the given requirement you cannot do this. *If you designed the contract*, then add a condition and make the caller invoke ``` exists(key): bool ``` The service implementation look like this: ``` if (exists(key)) { CustomObject o = get(key, ifModifiedSince); if (o == null) { setResponseCode(302);...
How Can I Avoid Using Exceptions for Flow Control?
[ "", "java", "exception", "return-type", "control-flow", "" ]
I have a JPanel full of JTextFields... ``` for (int i=0; i<maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); } ``` How do I later get the JTextFields in that JPanel? Like if I want their values with ``` TextField.getText(); ``` Thanks
Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime ) In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here: ``` List<JTextField> list = new ArrayLists...
Every JPanel in Java is also an AWT container. Thus, you should be able to use getComponents to get the array of contained components in the panel, iterate over them, check their types (To make sure you didn't get other controls), and do whatever you need with them. However, this is generally poor design. If you know ...
Java get JPanel Components
[ "", "java", "swing", "jframe", "jpanel", "jcomponent", "" ]
For example I can point the `url '^/accounts/password/reset/$'` to `django.contrib.auth.views.password_reset` with my template filename in the context but I think need to send more context details. I need to know exactly what context to add for each of the password reset and change views.
If you take a look at the sources for [django.contrib.auth.views.password\_reset](http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py) you'll see that it uses [`RequestContext`](http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py). The upshot is, you can use Contex...
Strongly recommend this article. I just plugged it in and it worked <http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html>
How do I use the built in password reset/change views with my own templates
[ "", "python", "django", "passwords", "" ]
I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as lon...
How about ``` if ((bool1? 1:0) + (bool2? 1:0) + (bool3? 1:0) + (bool4? 1:0) + (bool5? 1:0) > 1) // do something ``` or a generalized method would be... ``` public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools) { int trueCnt = 0; foreach(bool b in bools) if...
I was going to write the Linq version, but five or so people beat me to it. But I really like the params approach to avoid having to manually new up an array. So I think the best hybrid is, based on rp's answer with the body replace with the obvious Linqness: ``` public static int Truth(params bool[] booleans) { r...
Elegantly determine if more than one boolean is "true"
[ "", "c#", "hammingweight", "" ]
I have a few modules of block of code in VBA to run on few Access databases. I would like to know how I should proceed if I want to convert the coding to C# environment. And is it possible to implement and obtain the same results as I am getting now with Access and VBA? I am completely new to C# at this point.
Automatic conversion isn't possible at the moment, but doing it manually will also help improve your C# skills. There's a Top 10 article here that takes you through the common differences: <http://msdn.microsoft.com/en-us/library/aa164018%28office.10%29.aspx> You may also find the following links useful: The MSDN pa...
One thing to be aware of is that some object name spaces and library references are included automatically when you are coding in VBA. These need to be explicitly added when working in C#. For example, ``` Selection.TypeText("foo") ``` in VBA becomes ``` using Microsoft.Office.Interop.Word; Application word = new A...
Is it possible to convert VBA to C#?
[ "", "c#", "vba", "ms-access", "" ]
How would you get a reference to an executing class several stack frames above the current one? For example, if you have: ``` Class a { foo() { new b().bar(); } } Class b { bar() { ... } } ``` Is there a way to get the value that would be retrieved by using 'this' in foo() while the ...
No, you can't. In all the languages that use a stack that I know of, the contents of other stack frames are hidden from you. There are a few things you can do to get it, beyond the obvious passing it as a parameter. One of the aspect oriented frameworks might get you something. Also, you can get a bit of debugging info...
You have three choices. You can pass the calling object into the bar method: ``` Class A { foo() { new B().bar(this); } } Class B { bar(A caller) { ... } } ``` Or you can make class B an inner class of class A: ``` Class A { foo() { new B().bar(); } Class B { ...
Java: Retrieve this for methods above in the stack
[ "", "java", "" ]
There are too many method for embedding flash in html, which way is the best? Requirements are: * Cross-browser support * Support for alternative content (if flash is not supported by the browser) * Possibility to require a specific version of the flash player I have been reading about [SWFobject](http://code.google....
In a project I work on we use SWFobject which works like a charm, it allows you to check for a specific version and also display alternative content if flash is not supported. ``` var fn = function() { if(swfobject.hasFlashPlayerVersion("9.0.115")) { var att = { data:"flash.swf", width:"y", height:"x" ...
I would highly recommend using [flashembed](http://flowplayer.org/tools/flash-embed.html). It has support for everything you need and more, without being that complicated to use. It was originally developed for embedding [flowplayer](http://flowplayer.org/), which I can also recommend, but it works for any flash file. ...
Best way to embed flash in html
[ "", "javascript", "html", "flash", "embed", "" ]
I have been using PRETTY\_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them. In C++ how can I get the function name of the calling routine?
Here are two options: 1. You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the [GNU backtrace functions](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html). See [my answer here](https://stackoverflow.com/questions/77005/how...
Here is a solution you can often use. It has the advantage of requiring no changes to the actual function code (*no adding calls to stackwalk functions, changing parameters to pass in function names, or linking to extra libraries.*). To get it working, you simply need to use a bit of preprocessor magic: ## Simple Exam...
How do I find the name of the calling function?
[ "", "c++", "debugging", "" ]
From reading here and around the net, I'm close to assuming the answer is "no", but... Let's say I have an ASP.Net page that sometimes has a query string parameter. If the page has the query string parameter, I want to strip it off before, during, or after postback. The page already has a lot of client-side script (pu...
iam not sure this is what you are looking for, but if understand correctly you could do this: -on page load check for the QS value, if its not there use a hidden input field. -first time page loads with QS, do your normal processing and store QS value in a hidden input field. -if no QS then use the hidden input valu...
I would use an [**HTTPModule**](http://msdn.microsoft.com/en-us/library/ms972974.aspx) to intercept and rewrite the URL and query as it came in. I'm not 100%, but I don't believe this has any impact with viewstate. It sounds (and looks) complex, but it's actually fairly trivial and open to a ton of refinement and exte...
Is there any way to modify query strings without breaking an ASP.Net postback?
[ "", "asp.net", "javascript", "jquery", "html", "asp.net-2.0", "" ]
Is this functionality going to be put into a later Java version? Can someone explain why I can't do this, as in, the technical way Java's `switch` statement works?
Switch statements with `String` cases have been implemented in [Java SE 7](http://openjdk.java.net/projects/jdk7/features/), at least 16 years [after they were first requested.](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=1223179) A clear reason for the delay was not provided, but it likely had to do with perf...
If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired. Of course...
Why can't I use switch statement on a String?
[ "", "java", "string", "switch-statement", "" ]
I have a simple function in which an array is declared with size depending on the parameter which is int. ``` void f(int n){ char a[n]; }; int main() { return 0; } ``` This piece of code compiles fine on [GNU C++](http://en.wikipedia.org/wiki/G%2B%2B), but not on MSVC 2005. I get the...
What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression. There was a feature added to C in the 1999 update to that language called variable length arrays, where ...
Your method of allocating from the stack is a g++ extension. To do the equivalent under MSVC, you need to use \_alloca: ``` char *a = (char *)_alloca(n); ```
C++ array size dependent on function parameter causes compile errors
[ "", "c++", "arrays", "parameters", "declaration", "" ]
Im trying to do a dialog box with jquery. In this dialog box Im going to have terms and conditions. The problem is that the dialog box is only displayed for the FIRST TIME. This is the code. JavaScript: ``` function showTOC() { $("#TOC").dialog({ modal: true, overlay: { opacity: 0....
Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well: ``` $(document).ready({ $('a.TOClink').click(function(){ showTOC(); }...
I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works. The $('#myDiv').dialog() command creates/instantiates the dia...
jQuery Dialog Box
[ "", "javascript", "jquery", "jquery-ui", "dialog", "" ]
I'm coming from a .net background and want to know the accepted way of creating a method that returns a boolean and modifies a string that was passed in via parameter. I understand Strings are immutable in Java so the below snippet will always produce an empty string. I am constrained to return boolean only. Exceptions...
Use a java.lang.StringBuilder - basically a mutable String. However, it would be safer and more "Java style" to return the modified String.
I strongly suggest you do not use StringBuilder, holder or similar. They are hacks. You want to be working with Strings, not builders. The most obvious approach is to return an object containing the data you want to return. David's [bombe.livejournal.com's] solution covers that, so I won't repeat it. However, I would ...
Java String Parameters
[ "", "java", "parameters", "string", "idioms", "" ]
EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers. I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class. All the objects that create and use the base class objects shouldn'...
This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know h...
Usually, base class/ derived class pattern is used when you have an interface in base class, and that interface is implemented in derived class (IS-A relationship). In your case, the base class does not seem to have any connection with derived class - it may as well be void\*. If there is no connection between base cl...
Registering derived classes in C++
[ "", "c++", "design-patterns", "templates", "abstract-class", "factory", "" ]
I wish to execute a javascript function after asp.net postback with out using ajax. I've tried the following in my even method with no luck: ``` Page.ClientScript.RegisterStartupScript(GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);"); ```
You should rather use the ScriptManager class, since the Page.ClientScript property is deprecated... > The ClientScriptManager class is new in ASP.NET 2.0 and replaces Page class methods for managing scripts that are now deprecated. > [Reference: MSDN - Page.ClientScript Property](http://msdn.microsoft.com/en-us/lib...
**Solution** I needed to add the script tags using the following overload. ``` Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "alert('Success!');", true); ``` Found : [Re: execute javascript after postback](http://forums.asp.net/p/1314545/2605856.aspx)
Execute javascript function after asp.net postback without Ajax
[ "", "c#", "asp.net", ".net-2.0", "" ]
How do you build a hierarchical set of tags with data in PHP? For example, a nested list: ``` <div> <ul> <li>foo </li> <li>bar <ul> <li>sub-bar </li> </ul> </li> </ul> </div> ``` This would be build from flat data like th...
*Edit: Added formatting* As already said in the comments, your data structure is somewhat strange. Instead of using text manipulation (like OIS), I prefer DOM: ``` <?php $nested_array = array(); $nested_array[] = array('name' => 'foo', 'depth' => 0); $nested_array[] = array('name' => 'bar', 'depth' => 0); $nested_ar...
You mean something like ``` function array_to_list(array $array, $width = 3, $type = 'ul', $separator = ' ', $depth = 0) { $ulSpace = str_repeat($separator, $width * $depth++); $liSpace = str_repeat($separator, $width * $depth++); $subSpace = str_repeat($separator, $width * $depth); foreach ($array as ...
Build hierarchical html tags in PHP from flat data
[ "", "php", "html", "hierarchy", "" ]
I have a service that sometimes calls a batch file. The batch file takes 5-10 seconds to execute: ``` System.Diagnostics.Process proc = new System.Diagnostics.Process(); // Declare New Process proc.StartInfo.FileName = fileName; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pro...
Here is what i use to execute batch files: ``` proc.StartInfo.FileName = target; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit ( (timeout <= 0) ? i...
``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace VG { class VGe { [STAThread] static void Main(string[] args) { Process proc = null; tr...
Service hangs up at WaitForExit after calling batch file
[ "", "c#", ".net", "service", "windows-services", "" ]
NHibernatians! I have a table [dbo].[Wibble] and another table [dbo].[WibbleExtended]. [Wibble] is the main table and [WibbleExtended] is an optional table where some other fields are stored. There are far fewer entries in the [WibbleExtended] table than the main [Wibble] table. I think this was done back in the day ...
Have you considered using the [Join element](http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-join) that was introduced in NHibernate 2.0? This element allows you to join multiple tables to form one entity; that relationship can also be optional.
The error you are getting: > Invalid index n for this > SqlParameterCollection with Count=n. is due to **two properties mapped to the same column**. Use insert=false and update=false in one of the two. reference <http://groups.google.com/group/nhusers/browse_thread/thread/84830b1257efd219>
NHibernate mapping - one-to-one (or one-to-zero)
[ "", "c#", "nhibernate", "nhibernate-mapping", "" ]
Say I have an interface like this: ``` public interface ISomeInterface { ... } ``` I also have a couple of classes implementing this interface; ``` public class SomeClass : ISomeInterface { ... } ``` Now I have a WPF ListBox listing items of ISomeInterface, using a custom DataTemplate. The databinding engine will ...
In order to bind to explicit implemented interface members, all you need to do is to use the parentheses. For example: implicit: ``` {Binding Path=MyValue} ``` explicit: ``` {Binding Path=(mynamespacealias:IMyInterface.MyValue)} ```
[This answer](http://social.msdn.microsoft.com/Forums/vstudio/en-US/1e774a24-0deb-4acd-a719-32abd847041d/data-templates-and-interfaces) from Microsoft forums by [Beatriz Costa - MSFT](http://social.msdn.microsoft.com/profile/beatriz%20costa%20-%20msft/?ws=usercard-inline) is worth reading (rather old): > The data bind...
WPF databinding to interface and not actual object - casting possible?
[ "", "c#", "wpf", "data-binding", "" ]
I'm using LINQ to SQL to pull records from a database, sort them by a string field, then perform some other work on them. Unfortunately the Name field that I'm sorting by comes out of the database like this ``` Name ADAPT1 ADAPT10 ADAPT11 ... ADAPT2 ADAPT3 ``` I'd like to sort the Name field in numerical order. Right...
Force the hydration of the elements by enumerating the query (call ToList). From that point on, your operations will be against in-memory objects and those operations will not be translated into SQL. ``` List<Adaptation> result = dbContext.Adaptation .Where(aun => aun.EventID = iep.EventID) .ToList(); result.Fo...
Implement a `IComparer<string>` with your logic: ``` var adaptationsUnsorted = from aun in dbContext.Adaptations where aun.EventID == iep.EventID select new Adaptation { StudentID = aun.StudentID, ...
Regex Replace to assist Orderby in LINQ
[ "", "c#", "regex", "linq", "linq-to-sql", "" ]
I want to align my member variables based on a class template type but I'm not sure if it is actually possible. The following is a (very) simple example of what I'd like to do ``` template<int Align> class MyClass { private: struct MyStruct { // Some stuff } __declspec(align(Align)); __declspec(align(Ali...
Custom alignment isn't in the standard, so how the compilers deal with it is up to them - looks like VC++ doesn't like combining templates with \_\_declspec. I suggest a work-around using specialisation, something like this: ``` template<int A> struct aligned; template<> struct aligned<1> { } __declspec(align(1)); te...
Boost has solved this problem already. They use the technique in [boost::optional](http://www.boost.org/doc/libs/1_35_0/libs/optional/doc/html/index.html) ([link to header](http://www.boost.org/doc/libs/1_32_0/boost/optional/optional.hpp)), which has to hold enough space for an aligned, arbitrary type but can't (won't)...
Aligning Member Variables By Template Type
[ "", "c++", "templates", "" ]
I'd like to know if there's a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (about 60 chars wide before it must wrap), about 495 pixels. The font is also a fixed size (12points afaik), but the text is not. What I want to do is in...
How about `Graphics.MeasureString`, with the overload that accepts a string, the font, and the max width? This returns a `SizeF`, so you can round round-off the `Height`. ``` using(Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(text, lbl.Font, 495); lbl.Height = (int) Mat...
System.Drawing.Graphics has a MeasureString method that you can use for this purpose. Use the overload that takes a string, a font, and an int "width" parameter; this last parameter specifies the maximum width allowed for the string - use the set width of your label for this parameter. MeasureString returns a SizeF ob...
Determine Label Size based upon amount of text and font size in Winforms/C#
[ "", "c#", ".net", "winforms", "" ]
I have a bunch of pretty large CSV (comma separated values) files and I want to analyze them. SQL queries are ideal for this. So far I have been using MS Access to import the CSV files and execute queries on them. However, in addition to having a very bad SQL editor and having stupid arbitrary rules about when a query/...
there's also an Oracle Express Edition. I guess it depends on where you are already proficient. Or maybe where you **want to be** proficient.
Why don't just import them to MySQL, it's easy. ``` LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE some_table FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1, filed2, field3); ``` And then you can easilly run queries of any complexity...
Fast, Free Desktop SQL tool for CSV files
[ "", "sql", "csv", "" ]