Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like [PXLS](http://community.moertel.com/pxsl/) or JSON? Also I know that XML is human readable, I'm looking for something with less annoying redundancy, somethin...
To Serialize into JSON in .NET you do as follows: ``` public static string ToJson(IEnumerable collection) { DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType()); string json; using (MemoryStream m = new MemoryStream()) { ...
I found a exaustive documentation here: <http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx> with this usefull class (support generics) ``` using System.Runtime.Serialization; using System.Runtime.Serialization.Json; public class JSONHelper { public static stri...
Serialize in a human readable text format
[ "", "c#", ".net", "serialization", ".net-2.0", "" ]
When debugging in Internet Explorer, I first get an alert box with extremely limited if not useless information (sorry IE) and choose to debug it. After selecting yes, I get another option *every time* to choose between 'New instance of Microsoft script debugger' and 'New instance of Visual Studio'. I'm fed up with hav...
Apparently the problem happens if you do not uninstall the old (crappy) Microsoft Script Debugger before you install the newer Microsoft Script Editor. You would think that all you need to do is to uninstall the old debugger - however, according to a blog posting (which I can't recall at the moment), if you uninstall ...
If all other solutions fail, you can try another route: using a macro language (à la AutoHotkey or AutoIt) to dismiss all prompts with one key...
How to stop IE asking which debugger to choose when **trying** to debug?
[ "", "javascript", "visual-studio", "debugging", "internet-explorer", "" ]
I have a script that needs to extract data temporarily to do extra operations on it, but then doesn't need to store it any further after the script has run. I currently have the data in question in a series of temporary local tables (CREATE TABLE #table), which are then dropped as their use is completed. I was consider...
Temporary tables are a big NO in SQL Server. * They provoke query plan recompilations which is costly. * Creating and dropping the table are also costly operations that you are adding to your process. * If there is a big amount of data going to the temporary data your operations will be slow on the lack of indexes. Yo...
What kind of data operations are you doing, and how much data are you working with? I would stick with the temporary tables - for large data sets, I've always found it to be by far the best way to go, and not just in SQL Server. You could try a global temporary table (CREATE TABLE ##tablename), which lasts beyond just...
What is the comparative speed of temporary tables to physical tables in SQL?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have a python script that I would like to add a "Shutdown when done" feature to. I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the...
gksudo should have a timeout, I believe it's from the time you last executed a gksudo command. So I think I'd just throw out a "gksudo echo meh" or something every minute. Should reset the timer and keep you active until you reboot.
Instead of `chmod u+s`ing the shutdown command, allowing passwordless sudo access to that command would be better.. As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script?
How can I ask for root password but perform the action at a later time?
[ "", "python", "linux", "ubuntu", "" ]
is there a way to have a mysql select statement return fully qualified column names like "table.field" without using AS for every single field? like so: ``` SELECT * FROM table1 LEFT JOIN table2 on table1.f_ID = table2.ID ``` and the result would be: "table1.ID", "table1.name", "table2.ID", "table2.name", ...
Not really. You could write some dynamic SQL to accomplish this, but it wouldn't be simple. If you really want the dynamic SQL, let me know and I could try to whip something up.
If you are using PHP you can use PDO to get this result. `$PDO->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true);` See [SQL Select \* from multiple tables](https://stackoverflow.com/questions/2523631/sql-select-from-multiple-tables) for more information.
have mysql select statement return fully qualified column names like table.field
[ "", "sql", "mysql", "" ]
With SQLAlchemy, is there a way to know beforehand whether a relation would be lazy-loaded? For example, given a lazy parent->children relation and an instance X of "parent", I'd like to know if "X.children" is already loaded, without triggering the query.
I think you could look at the child's `__dict__` attribute dictionary to check if the data is already there or not.
You can get a list of all unloaded properties (both relations and columns) from `sqlalchemy.orm.attributes.instance_state(obj).unloaded`. See: [Completing object with its relations and avoiding unnecessary queries in sqlalchemy](https://stackoverflow.com/questions/5795492/completing-object-with-its-relations-and-avoid...
How to find out if a lazy relation isn't loaded yet, with SQLAlchemy?
[ "", "python", "sqlalchemy", "" ]
I'm trying to make a PHP script, I have the script finished but it takes like 10 minutes to finish the process it is designed to do. This is not a problem, however I presume I have to keep the page loaded all this time which is annoying. Can I have it so that I start the process and then come back 10mins later and just...
Well, you can use [`ignore_user_abort`](https://www.php.net/manual/en/function.ignore-user-abort.php) So the script will continue to work (keep an eye on script duration, perhaps add "[set\_time\_limit](https://www.php.net/manual/en/function.set-time-limit.php)(0)") But a warning here: You will not be able to stop a ...
Sounds like you should have a queue and an external script for processing the queue. For example, your PHP script should put an entry into a database table and return right away. Then, a cron running every minute checks the queue and forks a process for each job. The advantage here is that you don't lock an apache th...
PHP Background Processes
[ "", "php", "background-process", "" ]
I'm using event delegation to listen for events lower in the DOM, but it's not working for an onchange event on a select box. Does the onchange event propagate or bubble up the DOM? Googling has failed in finding a conclusive answer.
[According to specification](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents-h3), `change`, `submit`, `reset` should bubble and `focus` and `blur` should not bubble. This behavior is implemented properly in all web browsers except IE < 9, that is, `change`, `submit`, `reset` do bub...
In jQuery 1.4+ the change event bubbles in all browsers, including IE. ``` $('div.field_container').change(function() { // code here runs in all browers, including IE. }); ```
Does the onchange event propagate?
[ "", "javascript", "html", "dom", "" ]
I'm trying to work through the problems on [projecteuler.net](http://projecteuler.net) but I keep running into a couple of problems. The first is a question of storing large quanities of elements in a `List<t>`. I keep getting OutOfMemoryException's when storing large quantities in the list. Now I admit I might not b...
Consider [System.Numerics.BigInteger](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger).
You need to use a large number class that uses some basic math principals to split these operations up. This [implementation of a C# BigInteger library](http://www.codeproject.com/KB/cs/biginteger.aspx) on CodePoject seems to be the most promising. The article has some good explanations of how operations with massive n...
working with incredibly large numbers in .NET
[ "", "c#", ".net", "biginteger", "largenumber", "" ]
I have a two years of experience of programming in Visual C# and Visual C++. I would like to know some good online sources to start learning ASP.NET or anything else I should/need to learn before diving into ASP.NET. I found some online videos that are proving to be quite useful. Perhaps I would like to know about some...
Sorry, but I'm going to have to suggest the immediately obvious first: [Official Microsoft ASP .Net Site](http://www.asp.net) There's a link at the top to both "Get Started" and "Learn", and I have found this site incredibly useful over the past year or so.
Speaking as a convert from WinForms to the Web, I offer the following tips * Learn the ASP.NET Life-cycle * Get to grips with the concepts of client vs server-side code; know how pages are served up etc * Don't bite off too much too soon, there are A LOT of new things to learn, and it changes very quickly. But you don...
Good place to start learning ASP.NET
[ "", "c#", "asp.net", "" ]
I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#): ``` int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToD...
You can cast: ``` int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m ); ``` Also, because `int`/`decimal` results in a `decimal` you can remove one of the casts: ``` int ItemCount = (int) Math.Ceiling( BrandCount / 4m ); ```
Why are you even using a decimal? ``` int ItemCount = (BrandCount+3)/4; ``` The `+3` makes sure you round up rather than down: ``` (37+3)/4 == 40/4 == 10 (38+3)/4 == 41/4 == 10 (39+3)/4 == 42/4 == 10 (40+3)/4 == 43/4 == 10 ``` In general: ``` public uint DivUp(uint num, uint denom) { return (num + denom - 1) /...
Integer math in c#
[ "", "c#", "math", "casting", "rounding", "" ]
I'm trying to copy both an image from a file and text from a file to the clipboard. My intention is to then open a word document or an outlook email and paste both the text and the image in one standard paste command (CTRL-V for example). I can do both separately easily enough, but doing them both in one operation does...
I noticed only an object can be passed in. In that case, when the user presses the command to paste, your code could execute two functions, or one function recursively, and each time get the data you want and paste it in. So, look at looping or recursion.
You could use RTF, which could combine text and graphics. Note that you CAN have CF\_BITMAP and CF\_TEXT on the clipboard at the same time. But it's not useful. You'd get the text when you paste into notepad, you'd get the bitmap when you paste into Paint, and most other apps would pick one or the other, but never both...
How do I copy an image and text to the clipboard as one object?
[ "", "c#", ".net", "clipboard", "copy-paste", "" ]
Just starting to explore the 'wonders' of regex. Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors... My experiments are in PHP using ereg(). Anyway. I work with first and last names separately but for now using the same regex. So...
* Hyphenated Names (Worthington-Smythe) Add a - into the second character class. The easiest way to do that is to add it at the start so that it can't possibly be interpreted as a range modifier (as in `a-z`). ``` ^[A-Z][-a-zA-Z]+$ ``` * Names with Apostophies (D'Angelo) A naive way of doing this would be as above,...
This regex is perfect for me. ``` ^([ \u00c0-\u01ffa-zA-Z'\-])+$ ``` It works fine in php environments using preg\_match(), but doesn't work everywhere. It matches `Jérémie O'Co-nor` so I think it matches all UTF-8 names.
Regex for names
[ "", "php", "regex", "" ]
What's the best way to remove a page frame automatically? I've used this type of code before: ``` <script language="JavaScript"> setTimeout ("changePage()", 3000); function changePage() { if (self.parent.frames.length != 0) self.parent.location="http://www.example.com"; } </script> ```
Do you mean if someone has put a frame around your content? If so, you need the following any where in your HTML page to jump out of the iframe: ``` <script type="text/javascript"> if (window.top.location != window.location) { window.top.location = window.location; } </script> ```
Here's an alternative that's more generic in that it doesn't name the parent URL, nor use the separate function call: ``` // is the current page at the top of the browser window hierarchy? if (top.location != self.location) { // it isn't, so force this page to be at // the top of the hierarchy, in its own w...
How do I automatically remove an HTML page frame?
[ "", "javascript", "html", "frame", "" ]
We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option. Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?
Consider executing the DOS command that maps a network drive as in the following code: ``` String command = "c:\\windows\\system32\\net.exe use f: \\\\machine\\share /user:user password"; Process p = Runtime.getRuntime().exec(command); ... ``` See details on net use command: ``` The syntax of this command is: NET ...
You can use JCIFS <http://jcifs.samba.org/src/docs/api/jcifs/smb/SmbFile.html> or if you want higher level API and support for other protocols like FTP, Zip and others: <http://commons.apache.org/vfs/filesystems.html> Both options are pure Java and cross platform.
How can I mount a windows drive in Java?
[ "", "java", "windows-services", "unc", "" ]
Suppose to have a code like this: ``` <div class="notSelected"> <label>Name <input type="text" name="name" id="name" /> </label> <div class="description"> Tell us what's your name to make us able to fake to be your friend when sending you an email. </div> </div> ...
I would recommend a look at jQuery for your task. It is quite easy to learn and produces nice effects quickly. But your described effect alone, pure JavaScript would also be enough. Make your DIVs always have a class called "selectable". You can toggle other CSS classes later on. Create a CSS class named "selected" an...
There's also a pure CSS solution to this problem. However, it doesn't work in MSIE 6. Technically, it works similar to Tomalek's solution but instead of using JavaScript to toggle the element's class, it uses CSS to toggle its style: ``` .selectable { /* basic styles … */ } .selectable:hover { /* hover styles … */ } ...
How to change the style of an element/container when the focus is "inside" it?
[ "", "javascript", "javascript-framework", "" ]
I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a `BiDictionaryOneToOne<T, S>` which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't b...
OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement : ``` /// <summary> /// This is a dictionary guaranteed to have only one of each value and key. /// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1. /// </summary> /// <typeparam ...
A more complete implementation of bidirectional dictionary: * **Supports almost all interfaces** of original `Dictionary<TKey,TValue>` (except infrastructure interfaces): + `IDictionary<TKey, TValue>` + `IReadOnlyDictionary<TKey, TValue>` + `IDictionary` + `ICollection<KeyValuePair<TKey, TValue>>` (this one an...
Bidirectional 1 to 1 Dictionary in C#
[ "", "c#", ".net", "collections", "" ]
I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example: ``` class Foo { int getBar() const { return bar; } ... }; ``` Why do this? It seems like there are disadvantages. T...
The C++ standard says that methods defined inside the class definition are `inline` by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.
Often there's no reason other than it's just easier and saves time. It also saves a little clutter in the implementation file, while taking up the same number of lines in the header file. And being less readable is quite a stretch if it's limited to things like getters and setters.
Why are C++ methods sometimes defined inside classes?
[ "", "c++", "optimization", "compiler-construction", "inline-functions", "" ]
Let's have the following class definition: ``` CThread::CThread () { this->hThread = NULL; this->hThreadId = 0; this->hMainThread = ::GetCurrentThread (); this->hMainThreadId = ::GetCurrentThreadId (); this->Timeout = 2000; //milliseconds } CThread::~CThread () { //waitin...
The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared \_\_delcspec(thread) ) You are getting a crash due to a race condition. The thread you just created hasn't started running yet at th...
I'm trying to get my head around what you are trying to do. It looks overly complicated for something like a thread-class. Would you mind post the class-definition as well? Start by removing the C-style cast of the process-argument to CreateThread(): ``` this->hThread = ::CreateThread (NULL, 0,&runProcess, (void *)(t...
How to get pointer from another thread?
[ "", "c++", "multithreading", "" ]
Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/*Project File*. This file has the /branches /tags and /trunk directories recommended by subversion. I have no problem properly uploading files to the repository, but do I...
You can do an `svn export` into your www directory. That will give you a "clean" version of your repo, without the .svn directories. ``` cd /var/www svn export /home/administrator/MyProject/trunk MyProject ``` --- Edit: adding in some good ideas from the comments... Some options for when you want to update your exp...
You can simply check out a copy of the repository in the /var/www folder, and then run **svn update** on it whenever you require (or switch it to a new branch/tag, etc). Thus you have one copy of the respository checked out on your local machine where you make changes and updates, and another copy on your webserver. U...
What is the best way to make files live using subversion on a production server?
[ "", "php", "linux", "svn", "" ]
As I mention in an earlier question, I'm refactoring a project I'm working on. Right now, everything depends on everything else. Everything is separated into namespaces I created early on, but I don't think my method of separtion was very good. I'm trying to eliminate cases where an object depends on another object in ...
You seem to have two conflicting requirements: > Inside GameName.Gui I > have a **MapView object that displays** a > Map and **any IRenderable** objects on it. and > But, the **MapView also needs the object > to implement ILocateable**, so it can > see its location and know when its > changed via an event, LocationC...
In all cases, the IRenderable objects would also have to implement ILocateable, so I'm doing what @Sklivvz suggested and make IRenderable implement ILocateable: ``` public interface IRenderable : ILocateable { // IRenderable interface } ``` This pattern is used heavily in .NET. For example, the ICollection interfac...
Combining two interfaces into one
[ "", "c#", ".net", "oop", "" ]
What order of precedence are events handled in JavaScript? Here are the events in alphabetical order... 1. onabort - Loading of an image is interrupted 2. onblur - An element loses focus 3. onchange - The user changes the content of a field 4. onclick - Mouse clicks an object 5. ondblclick - Mouse double-clicks...
This was not, so far as i know, explicitly defined in the past. Different browsers are free to implement event ordering however they see fit. While most are close enough for all practical purposes, there have been and continue to be some odd edge cases where browsers differ somewhat (and, of course, the many more cases...
For anyone wanting to know the sequence relative events get called in, see below. So far I have only tested in Chrome. 1. mouseover 2. mousemove 3. mouseout --- 1. mousedown 2. change (on focused input) 3. blur (on focused element) 4. focus 5. mouseup 6. click 7. dblclick --- 1. keydown 2. keypress 3. keyup
DOM event precedence
[ "", "javascript", "event-handling", "dom-events", "eventqueue", "" ]
I'm relatively new to the Python world, but this seems very straight forward. Google is yelling at me that this code needs to be optimized: ``` class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('lin...
The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty. If you do need an entity for each link, try this: ``` # For each line in the input, add to the databa...
Looks pretty tight to me. I see one thing that may make a small improvement. Your calling, "self.request.get('links')" twice. So adding: ``` unsplitlinks = self.request.get('links') ``` And referencing, "unsplitlinks" could help. Other than that the loop is the only area I see that would be a target for optimizati...
How can I optimize this Google App Engine code?
[ "", "python", "google-app-engine", "optimization", "" ]
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example `xmlWriter.writeString("foo");` would produce something like `<aTag>foo</aTag>` to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solutio...
Use a [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html) and then get the data out of that using [toByteArray()](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()). This won't test *how* it writes to the stream (one byte at a time or as...
If you can pass a Writer to XmlWriter, I would pass it a `StringWriter`. You can query the `StringWriter`'s contents using `toString()` on it. If you have to pass an `OutputStream`, you can pass a `ByteArrayOutputStream` and you can also call `toString()` on it to get its contents as a String. Then you can code somet...
Testing what's written to a Java OutputStream
[ "", "java", "junit", "outputstream", "" ]
Suppose I have a python object `x` and a string `s`, how do I set the attribute `s` on `x`? So: ``` >>> x = SomeObject() >>> attr = 'myAttr' >>> # magic goes here >>> x.myAttr 'magic' ``` What's the magic? The goal of this, incidentally, is to cache calls to `x.__getattr__()`.
``` setattr(x, attr, 'magic') ``` For help on it: ``` >>> help(setattr) Help on built-in function setattr in module __builtin__: setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. ``` However, you should note that you can't...
Usually, we define classes for this. ``` class XClass( object ): def __init__( self ): self.myAttr= None x= XClass() x.myAttr= 'magic' x.myAttr ``` However, you can, to an extent, do this with the `setattr` and `getattr` built-in functions. However, they don't work on instances of `object` directly. ``` >...
How do you programmatically set an attribute?
[ "", "python", "attributes", "object", "" ]
I have multiple ordered lists. Unfortunately, the order of the items isn't a simple alpha or numeric comparison, otherwise this is trivial. So what I have is something like: ``` List #1 List #2 List #3 groundhog groundhog easter mothersday mayday mothersday midsummer laborday ...
You may want to have a look at [topological sorting](http://en.wikipedia.org/wiki/Topological_sort). I think it applies quite well to your case.
I agree with @bdumitriu, you want topological sorting. This type of sort assumes you have a *partial order* among your data items, which means that for *certain pairs* of items, you can compare them to see which one precedes the other. In this case, like you say, there are multiple ways to create a single list of the ...
Multiple ordered lists boiled down to one list, where order is relative
[ "", "c#", "sorting", "diff", "" ]
I need to pack all my js, but need to edit it going into source control. is there a nice easy plugin for ccnet, or nant, that will allow me to pack my js, and store them in the same files on the way out to production. Not really looking for file combining, just minifying each file.
Here is the best answer I have found. It calls the YUI version of minify and just uses plain old Nant to do so and replace the existing js files with the minifyed ones. <http://codeclimber.net.nz/archive/2007/08/22/How-to-use-YUI-JS-Compressor-inside-a-NAnt-build.aspx>
I use copy concatenation and the YUI Compressor in a post build script. Old-school batch file style. The [compressor](http://www.julienlecomte.net/yuicompressor/README) works like a charm. My .NET website application uses the website deployment project and is continuously built by TeamCity. A bit hackish perhaps, but ...
Best packing strategy for js during continuous integration?
[ "", "javascript", "deployment", "continuous-integration", "minify", "" ]
Google hosts some popular JavaScript libraries at: <http://code.google.com/apis/ajaxlibs/> According to google: > The most powerful way to load the libraries is by using google.load() ... What are the real advantages of using `google.load("jquery", "1.2.6")` vs. `<script type="text/javascript" src="http://ajax.go...
Aside from the benefit of Google being able to bundle multiple files together on the request, there is no perk to using google.load. In fact, if you know all libraries that you want to use (say just jQuery 1.2.6), you're possibly making the user's browser perform one unneeded HTTP connection. Since the whole point of u...
1. It allows you to [dynamically load](http://code.google.com/apis/ajax/documentation/#Dynamic) the libraries in your code, wherever you want. 2. Because it lets you switch directly to a new version of the library in the javascript, without forcing you to rebuild/change templates all across your site.
What are advantages of using google.load('jQuery', ...) vs direct inclusion of hosted script URL?
[ "", "javascript", "optimization", "" ]
We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation. Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build. Of course we ca...
Normally you would add a profile to your maven configuration that runs a different set of tests: run this with mvn -Pintegrationtest install ``` <profile> <id>integrationtest</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId>...
Adding to **krosenvold**'s answer, to ensure no unexpected behavior, make sure you also have a default profile that is active by default that *excludes* the integration or stresstests you want to run in your special profile. ``` <profile> <id>normal</id> <build> <plugins> <plugin> ...
Is there a way to separate long running (e.g. stress tests) out so they're not run by default in Maven 2?
[ "", "java", "maven-2", "build-process", "junit", "build-automation", "" ]
I am the tech intern for an online independent newspaper, and the writers on the staff are not tech-savvy. They don't quite understand how web pages work, and often they upload and include images straight from their digital cameras, or scanned from original media. These images become a burden when there are 10 images o...
You'd be better off doing the GD image processing during the upload process. GD can take up quite a bit of resources, so processing each image on every request would not be a preferable solution. If you can't do it during the upload process, you should cache all the resampled images and use those if/when available.
It's certainly possible, and I'd be very surprised if Joomla! doesn't already have modules that do just that.
PHP Replace Images with GD Library Resampled Images in Joomla
[ "", "php", "image", "joomla", "gd", "" ]
I'd like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database. So for example, I've got either 255.255.255.0 or its decimal value (4294967040) stored in the database. I'd like to do a select and get back /24 representation via the query. I've done th...
I think I have found the solution to my issue. Here is what I have done: ``` select CONCAT(INET_NTOA(ip_addr),'/',32-log2((4294967296-ip_mask))) net from subnets order by ip_addr ``` Basically I take my decmial mask and subtract it from the maximum decimal value. I then to a log2 on that value to get the logarithm ...
SQL queries don't have a procedural looping construct (notwithstanding procedural language), but you can compare one set of rows to another set of rows, which is kind of like a loop. You only have 32 possible subnet masks. In cases like this, it makes sense to create a small table that stores these 32 masks and the as...
Using SQL to determine cidr value of a subnet mask
[ "", "sql", "subnet", "bitmask", "cidr", "" ]
I'm pulling email address records from a table in SQL Server 2005, and want to build a single string to use as the `@recipients` list with `sp_send_dbmail`. The table has a field called EmailAddress and there are 10 records in the table. I'm doing this: ``` DECLARE @email VARCHAR(MAX) SELECT @email = ISNULL(@emai...
Because for each row you concatentate the current value of `@email` with the next result in `EmailAddress`. String concatenation is just like calling a function, in that it must evaluate the result for each row in sequence.
Say you have 3 addresses: ``` a@b.c b@b.c c@b.c ``` For the first row, `@email` is `NULL`, so it becomes `"" + "a@b.c"`, so `"a@b.c"`. For the second row, `@email` becomes `"a@b.c" + "; " + "b@b.c"`, so `"a@b.c; b@b.c"`. For the last row, `@email` becomes `"a@b.c; b@b.c" + "; " + "c@b.c"`, so `"a@b.c; b@b.c; c@b.c"...
Why does this SQL script work as it does?
[ "", "sql", "sql-server", "t-sql", "" ]
On an ASP.NET page, I have a GridView populated with the results of a LINQ query. I'm setting the DataSource in code, then calling DataBind on it. In the GridView's RowDataBound event, I'm selectively hiding links in some GridView fields based on the query results. (For instance, I hide the "Show Parent" link of the ro...
Here's how I ended up solving this: 1. I created a serializable class with readonly properties: PK of a row, and a boolean for each link indicating whether it's enabled or not. We'll call it `LinkVisibility`. 2. I created a serializable class inheriting from KeyedCollection to hold instances of the class above. 3. I c...
The RowDataBound event only fires when the GridView's data changes during the postback. The event is short-circuited for speed so it's not re-generating the exact same data unnecessarily. Use the RowCreated event to manipulate the HTML instead - it fires on every postback regardless of whether the data has changed.
GridView RowDataBound doesn't fire on postback
[ "", "c#", "asp.net", "vb.net", "gridview", "postback", "" ]
currently I have the following code: ``` String select = qry.substring("select ".length(),qry2.indexOf(" from ")); String[] attrs = select.split(","); ``` which works for the most parts but fails if given the following: ``` qry = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a"; ``` what I'm look...
``` [^,]+\([^\)]+\)|[^,]+, ``` Should do it nicely provided you always add a final ',' to your select string: ``` a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff ``` would fail to split the last 'fff' attributes, but: ``` a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff, ``` wo...
Your answer in the form of a quote: > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. — Jamie Zawinski Your regex would have to take into account all possible functions, nested functions, nested strings, etc. Your solution probably isn't a r...
java regex to split an attribute list from an sql query into a String[] of attrs
[ "", "java", "regex", "" ]
[**According to spec**](http://www.w3.org/TR/REC-html40/interact/scripts.html), only the `BODY` and `FRAMESET` elements provide an "onload" event to attach to, but I would like to know when a dynamically-created DOM element has been added to the DOM in JavaScript. The super-naive heuristics I am currently using, which...
UPDATE: For anyone interested in it, here is the implementation I finally used: ``` function isInDOMTree(node) { // If the farthest-back ancestor of our node has a "body" // property (that node would be the document itself), // we assume it is in the page's DOM tree. return !!(findUltimateAncestor(node).b...
The most straightforward answer is to make use of the [`Node.contains`](https://developer.mozilla.org/en-US/docs/DOM/Node.contains) method, supported by Chrome, Firefox (Gecko), Internet Explorer, Opera, and Safari. Here is an example: ``` var el = document.createElement("div"); console.log(document.body.contains(el))...
How can I determine if a dynamically-created DOM element has been added to the DOM?
[ "", "javascript", "dom", "" ]
The subject doesn't say much cause it is not easy to question in one line. I have to execute a few programs which I read from the registry. I have to read from a field where somebody saves the whole paths and arguments. I've been using System.Diagnostics.ProcessStartInfo setting the name of the program and its argume...
I have tackled this the same way as the poster above, using cmd.exe with process start info. ``` Process myProcess = New Process; myProcess.StartInfo.FileName = "cmd.exe"; myProcess.StartInfo.Arguments = "/C " + cmd; myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; myProcess.StartInfo.CreateNoWindow = True...
There are several, in fact. 1. You can call cmd.exe with /C [your command line] as the arguments. This causes cmd.exe to process your command, and then quit. 2. You could write the command to a batch file and launch that. And of course there's the approach you're taking now, namely parsing the command line.
How do you run a program you don't know where the arguments start?
[ "", "c#", ".net", "registry", "system.diagnostics", "processstartinfo", "" ]
I'm looking for Ruby's Active record for PHP. Something that is so simple that I just define my fields, extend the base ORM class, and I get ACID operations for free. I should get default getters and setters without writing any code, but overriding a default getter or setter is as easy as declaring get$fieldName or set...
Both CodeIgniter (<http://codeigniter.com/user_guide/database/active_record.html>) and its PHP5 only fork Kohana (<http://docs.kohanaphp.com/libraries/orm>) contain implementations of the ActiveRecord pattern.
I'm a big fan of [Doctrine](http://www.doctrine-project.org/) which is a full featured ORM that will be replacing Propel as Symfony's default ORM. It's got your basic ORM stuff you'd expect along with a full featured query builder that I've found to be wonderful. It comes with a full suite of command line tools to ma...
What is the easiest to use ORM framework for PHP?
[ "", "php", "orm", "" ]
How do I access a page's HTTP response headers via JavaScript? Related to [**this question**](https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript), which was modified to ask about accessing two specific HTTP headers. > **Related:** > [How do I access the HTTP req...
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been [repeatedly asked](https://stackoverflow.com/questions/12258705/how-can-i-read-the-current-headers-without-making-a-new-request-with-js), too, because some peopl...
It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current. --- Use the following JavaScript code to get all the HTTP headers by performing a `get` request: ``` var req = new XMLHttpRe...
Accessing the web page's HTTP Headers in JavaScript
[ "", "javascript", "http", "http-headers", "" ]
In the `IDisposable.Dispose` method is there a way to figure out if an exception is being thrown? ``` using (MyWrapper wrapper = new MyWrapper()) { throw new Exception("Bad error."); } ``` If an exception is thrown in the `using` statement I want to know about it when the `IDisposable` object is disposed.
**No**, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause. See this [post on my blog](http://samsaffron.com/blog/archive/2007/08/06/16.aspx), for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with ...
You can extend `IDisposable` with method `Complete` and use pattern like that: ``` using (MyWrapper wrapper = new MyWrapper()) { throw new Exception("Bad error."); wrapper.Complete(); } ``` If an exception is thrown inside the `using` statement `Complete` will not be called before `Dispose`. If you want to k...
Intercepting an exception inside IDisposable.Dispose
[ "", "c#", ".net", "idisposable", "" ]
I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen [the W3C solution](http://web.archive.org/web/20100208164146/http://www.spoono.com/html/tutorials/tutorial.php?id=19), which doesn't even work on Firefox, and [this pretty cool solution](http:/...
**Things have changed** since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding. Paul Irish put together [Bulletproof @font-face syntax](http://paulirish.com/2009/bulletproof-font-face-imple...
Try [Facetype.js](https://gero3.github.io/facetype.js/ "Facetype.js"), you convert your .TTF font into a Javascript file. Full SEO compatible, supports FF, IE6 and Safari and degrades gracefully on other browsers.
How to embed fonts in HTML?
[ "", "javascript", "html", "flash", "fonts", "embed", "" ]
I am curious as to why an implicit cast fails in... ``` int? someValue = SomeCondition ? ResultOfSomeCalc() : null; ``` and why I have to perform an explicit cast instead ``` int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null; ``` It seems to me that the compiler has all the information it need to mak...
The relevant section of the C# 3.0 spec is 7.13, the conditional operator: The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then, If X and Y are the same type, then this is the type of the conditional Otherwise,...
I also am annoyed that it can't infer the type based on the assignment, especially when it's a value type. There are reasons though when you get into object heirarchies. **If "ResultOfSomeCalc()" returned a "int?", then this would work**. C# needs to figure out the type regardless of what is to the left of the assignm...
In C# why can't a conditional operator implicitly cast to a nullable type
[ "", "c#", "conditional-operator", "nullable", "" ]
I need to be able to compare some month names I have in an array. It would be nice if there were some direct way like: ``` Month.toInt("January") > Month.toInt("May") ``` My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it w...
`DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month` Although, for your purposes, you'll probably be better off just creating a `Dictionary<string, int>` mapping the month's name to its value.
You could do something like this: ``` Convert.ToDate(month + " 01, 1900").Month ```
How to parse a month name (string) to an integer for comparison in C#?
[ "", "c#", "parsing", "integer", "compare", "" ]
Scenario: An **event** is raised in class A that needs to be handled by a **method** in class B. (currently via a delegate) The data that gets passed from the **event** to the **method** is currently wrapped in class C. This obviously requires class B to be dependent on class C. Is there any techniques/ref...
unrolling to primitives would work, but be certain that you really do want to remove this dependency. It is perfectly valid for classes A and B to both depend on C if C is a bridge between them, or if C feeds both of them, etc. unrolling to primitives removes a compilation dependency, but not a data dependency, and ma...
I agree with Steven Lowe; The dependency probably is valid. The only alternative I can offer is to depend on an interface instead of an actual class, but it pretty much boils down to the same thing.
Techniques to remove dependencies?
[ "", "c#", "class", "dependencies", "" ]
This is just a general question - I was sitting and waiting for a bit of software to compile (we use Incredibuild here but can still take 10/15 mins) and it got me wondering, does anyone know how long it took to compile Windows XP or Vista? I did some googling but didn't really find any useful information
OP is asking about ***Windows***: > "There are no other software projects > like this," [Lucovsky](http://en.wikipedia.org/wiki/Mark_Lucovsky) said, "but the > one thing that's remained constant > [over the years] is how long it takes > to build [Windows]. ***No matter which > generation of the product, it takes 12 > ...
Third-hand information I have is that it takes about a day to complete a Windows build. Which is more or less in line with attempting to build your favorite OSS Operating System from scratch. Building a modern operating system is a complex and difficult task. The only reason why it doesn't take longer is because compa...
Operating System compile time
[ "", "c++", "c", "operating-system", "compilation", "buildfarm", "" ]
I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics. I have distilled the problematic code as follows: `template_test.h`: ``` template<class BaseClass> class Templated : public B...
With templated classes, the definitions must be available for each translation unit that uses it. The definitions can go in a separate file, usually with `.inl` or `.tcc` extension; the header file `#include`s that file at the bottom. Thus, even though it's in a separate file, it's still `#include`d for each translatio...
The problem is that when your Templated file is compiled, the compiler doesn't know what types it will need to generate code for, so it doesn't. Then when you link, main.cpp says it needs those functions, but they were never compiled into object files, so the linker can't find them. The other answers show ways to sol...
Templated superclass linking problem
[ "", "c++", "templates", "" ]
What is the best OS for Java development? People from Sun are pushing the Solaris, yes Solaris have some extra features included in itself such as (dTrace, possibility for Performance tuning the JVM, etc.. ). Some friends of mine, had port their application on solaris, and they said to me that the performances was bril...
Of the three I've used (Mac OS X, Linux, Windows), I consider Linux the best place to do Java development. My primary personal machine is a Mac, and I've done quite a lot of Java development there and been happy with it. Unfortunately, however, Apple lags behind the official JDK releases and you're pretty much limited...
Develop on whatever you like. As a java programmer you might want to avoid Mac OS X, primarily because new features seem to have been significantly delayed, and also because you can find you've no longer got a machine that supports the new versions of Java. Having said that I imagine developing on Mac OS X must be very...
Best OS for java development?
[ "", "java", "operating-system", "jvm", "solaris", "" ]
The company I work for has recently been hit with many header injection and file upload exploits on the sites we host and while we have fixed the problem with respect to header injection attacks, we have yet to get the upload exploits under control. I'm trying to set up a plug-and-play-type series of upload scripts to...
The best solution, IMHO, is to put the directory containing the uploaded files outside of the "web" environment and use a script to make them downloadable. In this way, even if somebody uploads a script it can not be executed by calling it from the browser and you don't have to check the type of the uploaded file.
1. **Allow only authorized users to upload a file.** You can add a captcha as well to hinder primitive bots. 2. First of all, **set the `MAX_FILE_SIZE` in your upload form**, and set the **maximum file `size` and `count` on the server** as well. ``` ini_set('post_max_size', '40M'); //or bigger by multiple files ...
What is the most secure method for uploading a file?
[ "", "php", "security", "file-upload", "" ]
At my work everyone has sql snippets that they use to answer questions. Some are specific to a customer, while some are generic for a given database. I want to consolidate those queries into a library/repository that can be accessed by anyone on the team. The requirements would be: 1. Accessible 2. Searchable 3. Tagab...
You could use a wiki. You could get started with something as simple as [Tiddly wiki](http://www.tiddlywiki.com/).
A wiki is a great approach. For database specific or project specific snippets it's also very useful to have links to where a similar construct occurs in the code. We use trac's wiki which gives nice integration with out SVN for this.
How do you maintain a library of useful SQL in a team environment?
[ "", "sql", "" ]
Is there a good way to determine if a person has a popup blocker enabled? I need to maintain a web application that unfortunately has tons of popups throughout it and I need to check if the user has popup blockers enabled. The only way I've found to do this is to open a window from javascript, check to see if it's ope...
Read [Detect a popup blocker using Javascript](http://www.visitor-stats.com/articles/detect-popup-blocker.php): Basically you check if the 'window.open' method returns a handle to a newly-opened window. Looks like this: ``` var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no'); if(mine) var...
As others have said, you'll have to try it and see, but checking for the resulting window object being non-"falsy" isn't sufficient for all browsers. Opera still returns a `Window` object when a popup is blocked, so you have to examine the object sufficiently to determine if it's a real window: ``` var popup = window...
Popup detection before user logs in
[ "", "javascript", "browser", "popup", "" ]
If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it. My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for...
One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change **any** logic concerning how that field is stored then the rest of your code will be left unaffected. For example you might change that from a local variable t...
It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis. When you go directly to the private field, you know that the field is being set to exactly what you say. When you go through the Property, the value gets set according to...
Should you access a variable within the same class via a Property?
[ "", "c#", "variables", "properties", "" ]
Could you recommend a lightweight SQL database which doesn't require installation on a client computer to work and could be accessed easily from .NET application? Only basic SQL capabilities are needed. Now I am using Access database in simple projects and distribute .MDB and .EXE files together. Looking for any alter...
Depends on what you mean by lightweight. Easy on RAM? Or lighter db file? Or lighter connector to connect to db? Or fewer files over all? I'll give a comparison of what I know: ``` no of files cumulative size of files db size Firebird 2.5 5 6.82 MB 25...
Check [SQLite](http://www.sqlite.org/), it's a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It has many [wrappers](http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers) for .NET
Lightweight SQL database which doesn't require installation
[ "", "sql", ".net", "database", "ms-access", "" ]
I have a C# Windows application which runs a service. I would like to leverage PowerShell in order to offer a command line management interface for administering my running service. From my point of view, I am trying to offer the same administrative interface a la Exchange 2007. Do you have any suggestion or sample c...
The key here is to start by writting an API that you can access from .Net, then you can easily wrap the calls to this API into a DLL that exposes classes that are PowerShell cmdlets. If you want someone to be able to administer your service remotely then I think probably the best thing is to create either a webservice ...
A solution would be for your Windows Service to expose an administrative interface through WCF. Your PowerShell commands would use this WCF service to pull out information and make the Windows Service perform actions.
Send administrative commands to my C# Windows Service using own PowerShell CmdLets
[ "", "c#", "powershell", "powershell-cmdlet", "" ]
I need to apply some xml templates to various streams of xml data (and files, on occasion) and there seem to be a large number of xml libraries for java out there -- enough that it's difficult to quickly determine which libraries are still active, how they differ from the other options that are also active, and what cr...
saxon is the xslt and xquery parser -- <http://saxon.sourceforge.net/>. this is built by a known xslt expert(who was on the xslt spec committe and who has authored books). there is an open source version and a commercial version. It(xslt piece) gets continuously improved . the other xslt tool in java, is of course, ...
No one has mentioned JAXP, the Java API for XML Processing. Comes right out of the box with the jdk, with default xml library implementations.
What xml/xslt library(ies) currently work well for java?
[ "", "java", "xml", "xslt", "" ]
So, I want to export all my contacts from Outlook as vcards. If I google that, I get a bunch of shareware programs, but I want something free that just works. If I'm to code it myself, I guess I should use the Microsoft.Office.Interop.Outlook assembly. Has anyone already code to convert ContactItems to vcards? **Edit...
I solved it in a non-programmatically way: * Selected all contacts in Outlook * Forwarded them as cards to myself * Saved all the attachments (vcards) in a folder, `c:\temp` * Opened a command prompt and typed the command `copy /a *.vcf c:\allcards.vcf` which concatenates all vcards into one
For what it's worth - I just came across this thread looking for the same export to individual .VCF files from outlook. I haev 2007 (don't know if that makes a difference) but I selected all contacts and dragged them to a new email message to be added as individual .VCF files. After they were all added, I clicked in th...
Export all contacts as vcards from Outlook
[ "", "c#", ".net", "outlook", "vcf-vcard", "" ]
I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked. ``` function FakeName() { $("input:checked").parent("form").submit(); } ``` My forms look like: ``` ...
The `onsubmit` handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again) However, of course you can call the `processRow()` function yourself in...
Look up [dispatchEvent](https://developer.mozilla.org/index.php?title=En/DOM/Element.dispatchEvent) and it's equivalent [fireEvent](http://msdn.microsoft.com/en-us/library/ms536423(VS.85).aspx). It's not the easiest thing in the world to use, but I think that's what you are looking for. I'm surprised that there's no l...
How to get function to fire when buttonless form is submitted
[ "", "javascript", "" ]
I have a class with the following member functions: ``` /// caller pid virtual pid_t Pid() const = 0; /// physical memory size in KB virtual uint64_t Size() const = 0; /// resident memory for this process virtual uint64_t Rss() const = 0; /// cpu used by this process virtual double PercentCpu() const = 0; ///...
Process info comes from `pidinfo`: ``` cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize); ``` cpu load comes from `host_statistics`: ``` cristi:~ diciu$ grep -r host_statistics /usr/include/ /usr/include/mach/host_info.h:/* h...
Since you say no Objective-C we'll rule out most of the MacOS frameworks. You can get CPU time using getrusage(), which gives the total amount of User and System CPU time charged to your process. To get a CPU percentage you'd need to snapshot the getrusage values once per second (or however granular you want to be). ...
Determine Process Info Programmatically in Darwin/OSX
[ "", "c++", "c", "macos", "operating-system", "darwin", "" ]
I understand that creating too many threads in an application isn't being what you might call a "good neighbour" to other running processes, since cpu and memory resources are consumed even if these threads are in an efficient sleeping state. What I'm interested in is this: **How much memory (win32 platform) is being ...
I have a server application which is heavy in thread usage, it uses a configurable thread pool which is set up by the customer, and in at least one site it has 1000+ threads, and when started up it uses only 50 MB. The reason is that Windows *reserves* 1MB for the stack (it maps its address space), but it is not necess...
Adding to Fabios comments: Memory is your second concern, not your first. The purpose of a threadpool is usually to constrain the context switching overhead between threads that want to run concurrently, ideally to the number of CPU cores available. A context switch is very expensive, often quoted at a few thousand t...
How much memory does a thread consume when first created?
[ "", "c++", "multithreading", "winapi", "" ]
Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method. I mean something like this: ``` [TriggersMyCustomAction()] public void DoSomeStuff() { } ``` I a...
The only way I know how to do this is with [PostSharp](https://www.postsharp.net/). It post-processes your IL and can do things like what you asked for.
This concept is used in **[MVC](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework) web applications.** The **.NET Framework 4.x** provides several attributes which trigger actions, e.g.: `ExceptionFilterAttribute` (handling exceptions), `AuthorizeAttribute` (handling authorization). Both are defined in `System.Web.Ht...
C#: How to create an attribute on a method triggering an event when it is invoked?
[ "", "c#", ".net", "events", "methods", "attributes", "" ]
I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in `$(document).ready` . For example: ``` $(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); }); ``` Of course, this works fine the first t...
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel. What I've done to work around this is re-subscribe to the events I need after every update. I use `$(document).r...
``` <script type="text/javascript"> function BindEvents() { $(document).ready(function() { $(".tr-base").mouseover(function() { $(this).toggleClass("trHover"); }).mouseout(function() { $(this).removeClass("trHover"); ...
jQuery $(document).ready and UpdatePanels?
[ "", "javascript", "jquery", "asp.net", "asp.net-ajax", "jquery-events", "" ]
I'm reading *The C++ Programming Language.* In it Stroustrup states that `sizeof(char) == 1` and `1 <= sizeof(bool)`. The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?
In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and...
Because in C++ you can take the address of a boolean and most machines cannot address individual bits.
Why is a char and a bool the same size in c++?
[ "", "c++", "boolean", "" ]
I have a simple application with the following code: ``` FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List<Thread> threads = new List<Thread>(files.Length); foreach (FileInfo f in files) { Thread t = new Thread(delegate() { Console.WriteLine(f.FullName); ...
The anonymous method keeps a **reference** to the variable in the enclosing block -- not the actual value of the variable. By the time the methods are actually executed (when you start the threads) `f` has been assigned to point to the last value in the collection, so all 3 threads print that last value.
Here are some nice articles about anonymous methods in C# and the code that will be generated by compiler: <http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx> <http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx> <http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx> I thin...
C# 2.0 Threading Question (anonymous methods)
[ "", "c#", "multithreading", ".net-2.0", "anonymous-methods", "" ]
I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP. Doing this should be quite easy using the SMO.Transfer class and it almost works! My code is as follows (somewhat simplified): ``` Server server = new Server("serve...
Well, after contacting Microsft Support I got it working properly, but it is slow and more or less useless. Doing a backup and then a restore is much faster and I will be using it as long as the new copy should live on the same server as the original. The working code is as follows: ``` ServerConnection conn = new Se...
Try setting [**SetDefaultInitFields**](http://msdn.microsoft.com/en-us/library/ms210363.aspx) to true on the **Server** object. I had the same issue with the SMO database object running slowly. I guess this is because sql server doesn't like to retrieve entire objects and collections at once, instead lazy loading ever...
Using SMO to copy a database and data
[ "", "c#", ".net", "sql-server-2008", "smo", "" ]
I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected. ``` switch (msg.ResultType) { case 0: $('#txtConsole').val("Some Val 0"); break; case 1: $('#txtConsole').val("Some Val 1"); break; case 2: $('#txtConsole').text("Some Val 2...
I'm sure that a switch uses === for comparison in Actionscript and since JS and AS both follow the ECMAScript standard, I guess the same applies to JS. My guess is that the value is not actually a Number, but perhaps a String. You could try to use parseInt(msg.ResultType) in the switch or use strings in the cases.
I ran into a similar problem and the issue turned out to be that where as it was showing as an int value, the switch statement was reading it as a string variable. May not be the case here, but that is what happened to me.
JavaScript switch statement
[ "", "javascript", "" ]
I remember some rules from a time ago (pre-32bit Intel processors), when was quite frequent (at least for me) having to analyze the assembly output generated by C/C++ compilers (in my case, Borland/Turbo at that time) to find performance bottlenecks, and to safely mix assembly routines with C/C++ code. Things like usin...
You are asking about "application binary interface" (ABI) and calling conventions. These are typically set by operating systems and libraries, and enforced by compilers and linkers. Google for "ABI" or "calling convention." Some starting points from [Wikipedia](http://en.wikipedia.org/wiki/Calling_convention) and [Debi...
Agner Fog's "Calling Conventions" document summarizes, amongst other things, the Windows and Linux 64 and 32-bit ABIs: <http://www.agner.org/optimize/calling_conventions.pdf>. See Table 4 on p.10 for a summary of register usage. One warning from personal experience: don't embed assumptions about the ABI in inline asse...
Register allocation rules in code generated by major C/C++ compilers
[ "", "c++", "c", "assembly", "compiler-construction", "cpu-registers", "" ]
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: ``` def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM ob...
I would just raise [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError), unless you need a more specific exception.. ``` def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") ``` There's really no point i...
I would inherit from `ValueError` ``` class IllegalArgumentError(ValueError): pass ``` It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible. If you need to catch that specific error, it is helpful to have a name.
Which exception should I raise on bad/illegal argument combinations in Python?
[ "", "python", "exception", "arguments", "" ]
How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.
``` import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print(m.start(), m.group()) ```
Taken from [*Regular Expression HOWTO*](http://docs.python.org/3.3/howto/regex.html) > span() returns both start and end indexes in a single tuple. Since the > match method only checks if the RE matches at the start of a string, > start() will always be zero. However, the search method of RegexObject > instances scan...
Python Regex - How to Get Positions and Values of Matches
[ "", "python", "regex", "" ]
I need to implement a SSO between a SharePoint site and a custom PHP-based site which resides on a different domain. I need to use the SharePoint user accounts to log in the PHP site. (I'll have a full control over the PHP source) Is this possible? Any tips and tricks?
My assumption is you have full control over your php app/domain, but a different team is managing the sharepoint server. Also assume you can ask the sharepoint team to create a simple webpart for your SSO functionality. If this is the case, you can ask the sharepoint team to create a webpart which has a link to your s...
I don't know much about this area but hopefully this might help point you in the right direction. **Investigate LDAP...** You can set up PHP to use LDAP credentials. If your SharePoint site uses Active Directory, then you can expose this directory as an LDAP source and use that in the PHP application. **Automated si...
SharePoint SSO with a PHP application on a different server?
[ "", "php", "sharepoint", "single-sign-on", "" ]
Heres a tricky one . . I have a webpage (called PageA) that has a header and then simply includes an iframe. Lets call the page within the iframe PageB. PageB simply has a bunch of thumbnails but there are a lot so you have to scroll down on PageA to view them all. When i scroll down to the bottom of the pageB and cl...
@mek after trying various methods, the best solution I've found is this: In the outer page, define a scroller function: ``` <script type="text/javascript"> function gotop() { scroll(0,0); } </script> ``` Then when you define the iframe, set an onload handler (which fires each time the iframe source loads i....
Javascript is your best bet. You can use the [scroll() method](http://www.java2s.com/Code/JavaScriptReference/Javascript-Methods/scrollSyntaxParametersandNote.htm) to scroll back up to the top of your IFRAME. Add a javascript handler in the body load so that each time you click a thumbnail, call a function that calls s...
asp.net IFrame scroll bar push to top . .
[ "", "asp.net", "javascript", "html", "iframe", "scroll", "" ]
I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default. I have found in certain places referencing the below code at [msdn](http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx). ``` [ConfigurationPrope...
This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page. ``` <configuration> <system.web> <httpRuntime maxRequestLength="xxx" /> </system.web> </configuration> ``` "xxx" is in KB. The default is 4096 (= 4 MB).
For IIS 7+, as well as adding the httpRuntime maxRequestLength setting you also need to add: ``` <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="52428800" /> <!--50MB--> </requestFiltering> </security> </system.webServer> ``` Or in IIS (7): > *...
How to increase the max upload file size in ASP.NET?
[ "", "c#", ".net", "asp.net", "file-upload", "" ]
How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?
You definitely can. Consider a Form class which stores information about the form itself: the `method`, `action`, `enctype` attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own cla...
To be honest I wouldn't roll my own, considering there are a few mature form packages out there for PHP. I use PEAR's HTML\_QuickForm package (<http://pear.php.net/manual/en/package.html.html-quickform.php>) for PHP4 sites. For PHP5, I'd have a look into Zend\_Form (<http://framework.zend.com/manual/en/zend.form.html...
How to build a PHP form Dynamically with OOP?
[ "", "php", "oop", "class", "forms", "" ]
(If anything here needs clarification/ more detail please let me know.) I have an application (C#, 2.\* framework) that interfaces with a third-party webservice using SOAP. I used thinktecture's WSCF add-in against a supplied WSDL to create the client-side implementation. For reasons beyond my control the SOAP message...
You can utilize SoapExtension from existing WSE2.0 framework to intercept the responses from the server. ``` public class MyClientSOAPExtension : SoapExtension { Stream oldStream; Stream newStream; // Save the Stream representing the SOAP request or SOAP response into // a local memory buffer. ...
Here is an example you can setup using Visual studio web reference to <http://footballpool.dataaccess.eu/data/info.wso?WSDL> Basically, you must insert in the webservice call chain a XmlReader spyer that will reconstruct the raw XML. I believe this way is somehow simpler that using SoapExtensions. Solution solution ...
How do I get access to SOAP response
[ "", "c#", "xml", "web-services", "soap", "wse2.0", "" ]
We're using Microsoft.Practices.CompositeUI.EventBroker to handle event subscription and publication in our application. The way that works is that you add an attribute to your event, specifying a topic name, like this: ``` [EventPublication("example", PublicationScope.Global)] public event EventHandler Example; ``` ...
What you are trying to achieve is quite complicated, so I will try to provide something just to get you started. This is what I think you would need to combine in order to achieve something: 1. Define an abstract class `AbstractEventDebugger`, with a method `Search` that searches all of the `event` members, and regist...
Attributes are a compile-time feature (unless you are dealing with ComponentModel - but I suspect it is using reflection). As such, you cannot add attributes at runtime. It would a similar question to "how do I add an extra method to a type at runtime?". In regular C# / .NET (pre-DLR), you can't.
How do I add attributes to a method at runtime?
[ "", "c#", "reflection", "attributes", "reflection.emit", "" ]
Obviously (methinks), creating an index on a `BIT` column is unnecessary. However, if you had a column that you need to search in which every value is likely unique, like `BlogPost` or `StreetAddress` or something, then an index seems appropriate (again, methinks). But what's the cutoff? What if you expect 10,000 rows...
The best answer to this is to profile your queries and see if the index improves your queries. The difficulty in answering this is that it is nearly impossible to generalize the behavior of the query optimizer. That said, a rule-of-thumb is if your selectivity is 10% or less on a given query on a table, then you will ...
James hit the nail on the head. I'll just add that even a bit column might benefit from an index depending on how you are using the table. For example, if you need to count the number of rows that have a 1 many times throughout the day, an index there could be useful. Indexes aren't always about finding a single record...
When to create a new SQL Server Index?
[ "", "sql", "database", "t-sql", "" ]
I'm using MS SQL Server 2005. Is there a difference, to the SQL engine, between ``` SELECT * FROM MyTable; ``` and ``` SELECT ColA, ColB, ColC FROM MyTable; ``` When ColA, ColB, and ColC represent every column in the table? If they are the same, is there a reason why you should use the 2nd one anyway? I have a pro...
Generally, it's better to be explicit, so `Select col1, col2 from Table` is better. The reason being that at some point, an extra column may be added to that table, and would cause unneeded data to be brought back from the query. This isn't a hard and fast rule though.
1) The second one is more explicit about which columns are returned. The value of the 2nd one then is how much you value explicitly knowing which columns come back. 2) This involves potentially less data being returned when there are more columns than the ones explicitly used as well. 3) If you change the table by ad...
Is there a difference between Select * and Select [list each col]
[ "", "sql", "database", "linq", "linq-to-sql", "" ]
How to 'group by' a query using an alias, for example: ``` select count(*), (select * from....) as alias_column from table group by alias_column ``` I get 'alias\_column' : INVALID\_IDENTIFIER error message. Why? How to group this query?
``` select count(count_col), alias_column from ( select count_col, (select value from....) as alias_column from table ) as inline group by alias_column ``` Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, be...
Nest the query with the alias column: ``` select count(*), alias_column from ( select empno, (select deptno from emp where emp.empno = e.empno) as alias_column from emp e ) group by alias_column; ```
Group by alias (Oracle)
[ "", "sql", "oracle", "" ]
What's the best way to parse fragments of HTML in C#? For context, I've inherited an application that uses a great deal of composite controls, which is fine, but a good deal of the controls are rendered using a long sequence of literal controls, which is fairly terrifying. I'm trying to get the application into unit t...
If the HTML is XHTML compliant, you can use the built in System.Xml namespace.
Have a look at the [HTMLAgility](http://www.codeplex.com/htmlagilitypack) pack. It's very compatible with the .NET XmlDocument class, but it much more forgiving about HTML that's not clean/valid XHTML.
Parsing HTML Fragments
[ "", "c#", "asp.net", "unit-testing", "web-standards", "" ]
Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized. Honestly I can't see the reasoning. I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why? What problems does it prevent? (And if it's actually necessary, why can't the ...
If the object does not own the object monitor when it calls Object.wait(), it will not be able to access the object to setup a notify listener until the the monitor is released. Instead, it will be treated as a thread attempting to access a method on a synchronized object. Or to put it another way, there is no differe...
Lots of good answers here already. But just want to mention here that the other MUST DO when using wait() is to do it in a loop dependent on the condition you are waiting for in case you are seeing spurious wakeups, which in my experience do happen. To wait for some other thread to change a condition to true and notif...
Can anyone explain thread monitors and wait?
[ "", "java", "multithreading", "monitor", "" ]
I am trying to write a query for SQL Server 2005 but I can't figure out how to do it. I have a table with the following fields: **MessageID int CategoryID int Priority tinyint MessageText NVARCHAR(MAX)** I need a query that will return \* for each row that has the highest priority within a Category. For example...
Verified: ``` SELECT highest_priority_messages.* FROM ( SELECT m.MessageID , m.CategoryID , m.Priority , m.MessageText , Rank() OVER (PARTITION BY m.CategoryID ORDER BY m.Priority DESC) AS p_rank FROM [Message] m GROUP BY m.CategoryID , m.Priority ...
If you'd like to do it without all of the subqueries: ``` SELECT MessageID, CategoryID, Priority, MessageText FROM dbo.Messages M1 LEFT OUTER JOIN dbo.Messages M2 ON M2.CategoryID = M1.CategoryID AND M2.Priority > M1.Priority WHERE M2.MessageID IS NULL ``` You might have to adj...
Semi-Tricky SQL Query
[ "", "sql", "sql-server", "" ]
I read all over the place about how Spring encourages you to use interfaces in your code. I don't see it. There is no notion of interface in your spring xml configuration. What part of Spring actually encourages you to use interfaces (other than the docs)?
When you define an interface for your classes, it helps with dependency injection. Your Spring configuration files don't have anything about interfaces in them themselves -- you just put in the name of the class. But if you want to inject another class that offers "equivalent" functionality, using an interface really ...
The [Dependency Inversion Principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle) explains this well. In particular, figure 4. > A. High level modules should not depend on low level modules. Both should depend upon abstractions. > > B. Abstraction should not depend upon details. Details should depend ...
spring and interfaces
[ "", "java", "spring", "" ]
I know they're using a jQuery plugin, but I can't seem to find which one they used. In particular, what I'm looking for is autocomplete with exactly the same functionality as SO's autocomplete, where it will perform an AJAX command with each new word typed in and allow you to select one from a dropdown.
Note that the tag editor [has been completely re-written now](https://meta.stackexchange.com/questions/100669/feedback-wanted-improved-tag-editor), and no longer resembles the original, simple text box w/ suggestion drop-down that adorned the site for nearly three years. If you're interested in the new form, see this ...
You might also like this one: * <http://code.google.com/p/jquery-autocomplete/> Read the history here: <http://code.google.com/p/jquery-autocomplete/wiki/History>
How does StackOverflow's 'tags' textbox autocomplete work?
[ "", "javascript", "jquery", "ajax", "textbox", "autocomplete", "" ]
1. We currently just utilize soap webservices for all our communication but have been thinking about moving to WCF instead. What are the benefits of using it over an asmx service? 2. If we do go with a WCF service, can other languages still communicate with it? SOAP is standardized and all languages can interact with i...
1. There's a bit of a learning curve with WCF, but once you learn it it's no harder to implement than an asmx web services. One advantage is you can easily switch protocols and serialization from binary remoting all the way to [web protocols](http://msdn.microsoft.com/en-us/library/ms730294.aspx). It's also easy to hos...
WCF is not a replacement for SOAP, and indeed, SOAP can be used as the serialization format between endpoints for communication. SOAP the standard also doesn't really define what goes in the message body, so in the case of WCF-to-WCF communication, a SOAP envelope is used, but the content is binary, so there's your pri...
What are the benefits of using WCF?
[ "", "c#", ".net", "wcf", ".net-3.5", "" ]
In C++ I'd like to do something like: ``` int n = get_int_from_user(); char* matrix = new char[n][n]; matrix[0][0] = 'c'; //... matrix[n][n] = 'a'; delete [][] matrix; ``` but of course this doesn't work. What is the best way to do something similar? I've seen some solutions to this but they seem pretty messy.
**The manual dynamic way:** Let's say you want an array of width\*height, the most efficient way is to just use a single dimensional array: ``` char *matrix = new char[width*height]; ``` To delete it: ``` delete[] matrix; ``` To access it: ``` char getArrayValue(char *matrix, int row, int col) { return matrix[r...
I usually do something like this: ``` char *matrix = new char [width * height]; matrix[i + j * width] = 'c'; // same as matrix[i][j] = 'c'; delete [] matrix; ```
Best way to represent a 2-D array in C++ with size determined at run time
[ "", "c++", "arrays", "dynamic", "matrix", "multidimensional-array", "" ]
I've been thinking of ways of providing syntactic sugar for a framework I have been working on. I want to deal with Immitable objects exclusively. ### Say I have an immutable object and wish to create a modified version of it. Would, in your view, a non-instantiable class with a single static factory method break OO p...
I don't think it's a good idea to create one class per method. You could instead create a static only methods class, named e.g StringUtils and implement the methods. This way you would call: String lowerCaseString = StringUtils.lowercase( targetString ); This would also offer you intellisense help while you are typin...
Usually on immutable objects, I would have a method returning a modified version of the object. So if you have some immutable collection, it can have a sort() method, that returns a new collection that is sorted. However, in your String example this is not possible, since you cannot touch the String class. Your approa...
Java: Immutable to Immutable Conversions
[ "", "java", "static", "frameworks", "methods", "factory", "" ]
I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file. I added a static method to my class CallRate that returns a `List<CallRate>`. Is it ok for a class to generate new instances of itself by calling one of its own constructors?...
It is perfectly fine to get object(s) of its own from the static method. e.g. One of the dot net libraries does the same thing as you did, ``` XmlReadrer reader = XmlReader.Create(filepathString); ```
Sure that's fine, even encouraged in some instances. There are several [design patterns that deal with object creation](http://en.wikipedia.org/wiki/Design_Patterns#Creational_patterns), and a few of them do just what you're describing.
Should a c# class generate instances of itself?
[ "", "c#", "class-design", "" ]
Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order? The object I wish to use will be declared *once* and will never be modified. Suppose I have: ``` var myObject = { A: "Hello", B: "World" }; ``` And I further us...
[Quoting John Resig](http://ejohn.org/blog/javascript-in-chrome/): > Currently all major browsers loop over the properties of an object in the order in > which they were defined. Chrome does this as well, except for a couple cases. [...] > This behavior is explicitly left undefined by the ECMAScript specification. > I...
*Bumping this a year later...* It is **2012** and the major browsers **still** differ: ``` function lineate(obj){ var arr = [], i; for (i in obj) arr.push([i,obj[i]].join(':')); console.log(arr); } var obj = { a:1, b:2, c:3, "123":'xyz' }; /* log1 */ lineate(obj); obj.a = 4; /* log2 */ lineate(obj); del...
Elements order in a "for (… in …)" loop
[ "", "javascript", "for-loop", "" ]
I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values. I'm curious if there is a good way in C++ to store variant data for a situation like th...
As of C++17, there’s [`std::variant`](http://en.cppreference.com/w/cpp/utility/variant). If you can’t use that yet, you might want [Boost.Variant](http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html). A similar, but distinct, type for modelling polymorphism is provided by [`std::any`](http://en.cppreference.com...
While Konrad's answer (using an existing standardized solution) is certainly preferable to writing your own bug-prone version, the boost variant has some overheads, especially in copy construction and memory. A common customized approach is the following modified Factory Pattern: 1. Create a Base interface for a gene...
How to store variant data in C++
[ "", "c++", "variant", "" ]
I'm writing an application that uses renaming rules to rename a list of files based on information given by the user. The files may be inconsistently named to begin with, or the filenames may be consistent. The user selects a list of files, and inputs information about the files (for MP3s, they would be Artist, Title, ...
Easiest would be to replace each `%Label%` with `(?<Label>.*?)`, and escape any other characters. ``` %Artist%-%Album%-%Track%-%Title%.mp3 ``` becomes ``` (?<Artist>.*?)-(?<Album>.*?)-(?<Track>.*?)-(?<Title>.*?)\.mp3 ``` You would then get each component into named capture groups. ``` Dictinary<string,string> matc...
Not the answer to the question you asked, but an [ID3 tag](http://en.wikipedia.org/wiki/ID3) reading library might be a better way to do this when you are using MP3s. A quick Google came up with: [C# ID3 Library](http://sourceforge.net/projects/csid3lib). As for guessing which string positions hold the artist, album, ...
Pattern matching and placeholder values
[ "", "c#", "regex", "" ]
I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details. I have a table 'posts' with the following columns: > id, caption, text and a table 'comments' with the following columns: > id, name, text, post\_id What would the (single...
``` select p.caption, count(c.id) from posts p join comments c on p.id = c.post_id group by p.caption having count (c.id) > 0 ```
``` SELECT DISTINCT p.caption, p.id FROM posts p, comments c WHERE c.post_ID = p.ID ``` I think using a join would be a lot faster than using the IN clause or a subquery.
SQL: Get all posts with any comments
[ "", "sql", "mysql", "" ]
In C# I sometimes wish I could make special methods for certain "instantiations" of generic classes. **UPDATE: The following code is just a dumb example of a more abstract problem - don't focus too much on time series, just the principles of "adding extra methods" for certain T**. Example: ``` class Timeseries<T> {...
You could always use the self-referential generics trick: ``` public class TimeSeries<T, U> where U : TimeSeries<T, U> { U Slice(...) } public class TimeSeriesDouble : TimeSeries<double, TimeSeriesDouble> { ... } ``` It can get a bit brain-bending, but it can work.
``` interface ITimeSeries<T> { ... } abstract class TimeSeriesBase<TS> where TS : TimeSeriesBase<TS> { public TS Slice() { ... } } class TimeSeries<T>:TimeSeriesBase<TimeSeries<T>>,ITimeSeries<T> {} class TimeSeriesDouble:TimeSeriesBase<TimeSeriesDouble>,ITimeSeries<double> { public double Interpolate() { ... }...
Pattern for specialization of generic class in C#?
[ "", "c#", ".net", "design-patterns", "generics", "" ]
Suppose I have a SELECT statement that returns some set of results. Is there some way I can number my results in the following way: > SELECT TOP 3 Name FROM PuppyNames ORDER BY NumberOfVotes would give me... > Fido > > Rover > > Freddy Krueger ...but I want... > 1, Fido > > 2, Rover > > 3, Freddy Krueger where of...
In Microsoft SQL Server 2005, you have the `ROW_NUMBER()` function which does exactly what you want. If you are stuck with SQL Server 2000, the typical technique was to create a new temporary table to contain the result of your query, plus add an `IDENTITY` column and generate incremental values. See an article that t...
With SQL 2000 you need to use a correlated sub-query. ``` SELECT ( SELECT COUNT(*) FROM PuppyNames b WHERE b.Popularity <= a.Popularity ) AS Ranking , a.Name FROM PuppyNames a ORDER BY a.Popularity ```
SQL: Numbering the rows returned by a SELECT statement
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I am on Vista 64 bits and I have a project built with x86 configuration. All work fine. Now, we are at the time to create test. We have NUnit 2.4.8 but we have a lot of problem. The test are loading trough the Nunit.exe (gui) when we select the .dll directly but when executing we have a system.badimageformatexception....
Ok I found the solution in this [website](http://cloudnine.no/2008/07/msbuild-nunit-running-32-bit-unit-tests-on-64-bin-machine). You have to use the \NUnit-2.4.8\bin\nunit-x86.exe instead of \NUnit-2.4.8\bin\nunit.exe... didn't know that the \bin\ had 2 nunit!!! Thx all
The NUnit host is likely running as a 64 bit process (you can confirm that by looking in task manager). If you assembly is x86 only then it won't be able to run in that process. You can try running [corflags](http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx) on the NUnit executable to force it to run x86, ...
Nunit.exe cannot work on Vista 64bits if x86 build
[ "", "c#", ".net", ".net-2.0", "nunit", "64-bit", "" ]
How can I create an instance of the following annotation (with all fields set to their default value). ``` @Retention( RetentionPolicy.RUNTIME ) public @interface Settings { String a() default "AAA"; String b() default "BBB"; String c() default "CCC"; } ``` I tried `new...
You cannot create an instance, but at least get the default values ``` Settings.class.getMethod("a").getDefaultValue() Settings.class.getMethod("b").getDefaultValue() Settings.class.getMethod("c").getDefaultValue() ``` And then, a dynamic proxy could be used to return the default values. Which is, as far as I can tel...
To create an instance you need to create a class that implements: * [`java.lang.annotation.Annotation`](https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Annotation.html) * and the annotation you want to "simulate" For example: `public class MySettings implements Annotation, Settings` But you need to pa...
Create Annotation instance with defaults, in Java
[ "", "java", "annotations", "instantiation", "" ]
I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing? ``` public class SomeClass: ISomeInterface { MyAttribute GetAttribute() { StackTrace stac...
The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method "Foo" ...
Mark's method will work for non-generic interfaces. But it appears that I am dealing with some that have generics ``` interface IFoo<T> {} class Foo<T>: IFoo<T> { T Bar() } ``` It appears that the T is replaced with the actual classType in the map.TargetMethods.
Attributes on an interface
[ "", "c#", "reflection", "attributes", "interface", "" ]
I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly. I want to programmatically generate a project for the application. The `.project` and `.classpath` files are easy enough to figure out, and I'...
You should be able to accomplish this by writing a small Eclipse plugin. You could even extend it out to being a "headless" RCP app, and pass in the command line arguments you need. The barebones code to create a project is: ``` IProgressMonitor progressMonitor = new NullProgressMonitor(); IWorkspaceRoot root = Resou...
Use [AntEclipse](http://ant-eclipse.sourceforge.net) It can create eclipse projects from ant.
Programmatically generate an Eclipse project
[ "", "java", "eclipse", "" ]
In C# which is more memory efficient: Option #1 or Option #2? ``` public void TestStringBuilder() { //potentially a collection with several hundred items: string[] outputStrings = new string[] { "test1", "test2", "test3" }; //Option #1 StringBuilder formattedOutput = new StringBuilder(); foreach (...
Several of the answers gently suggested that I get off my duff and figure out it myself so below are my results. I think that sentiment generally goes against the grain of this site but if you want something done right, you might as well do.... :) I modified option #1 to take advantage of @Ty suggestion to use StringB...
Option 2 should (I believe) actually outperform option 1. The act of calling `Remove` "forces" the StringBuilder to take a copy of the string it's already returned. The string is actually mutable within StringBuilder, and StringBuilder doesn't take a copy unless it needs to. With option 1 it copies before basically cle...
Is using StringBuilder Remove method more memory efficient than creating a new StringBuilder in loop?
[ "", "c#", "memory-leaks", "garbage-collection", "stringbuilder", "" ]
I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following: ``` CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME) ``` but this results in the wrong date. What is the correct way to turn the three date...
Assuming `y, m, d` are all `int`, how about: ``` CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME) ``` Please see [my other answer](https://stackoverflow.com/a/10142966/18255) for SQL Server 2012 and above
Try this: ``` Declare @DayOfMonth TinyInt Set @DayOfMonth = 13 Declare @Month TinyInt Set @Month = 6 Declare @Year Integer Set @Year = 2006 -- ------------------------------------ Select DateAdd(day, @DayOfMonth - 1, DateAdd(month, @Month - 1, DateAdd(Year, @Year-1900, 0))) ``` It works as w...
Create a date from day month and year with T-SQL
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
My problem is that all the textbox's my formview are getting cleared when I hit the submit button. I currently have a page with a small section that has an update panel around it. This small section adds an address to my databse. To the left of this form there is a gridview that is tied into the formview. So if i clic...
is the ViewState enabled?
in the page\_load are you using if(!Page.IsPostback) { ... } so if it's a postback nothing gets re-bound?
Formview Being Cleared
[ "", "c#", "asp.net", "gridview", "formview", "" ]
I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use `win32com.client.Dispatch`. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008: ``` import win32com.client app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok ap...
I don't know if this will help you with 2008, but with Visual Studio 2005 and win32com I'm able to do this: ``` >>> import win32com.client >>> b = win32com.client.Dispatch('VisualStudio.DTE') >>> b <COMObject VisualStudio.DTE> >>> b.name u'Microsoft Visual Studio' >>> b.Version u'8.0' ``` Unfortunately I don't have 2...
Depending on what exactly you're trying to do, [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) may meet your needs. In fact, I'm sure it will do anything you need it to do. Taken from my [other post](https://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python#155587) about h...
How to script Visual Studio 2008 from Python?
[ "", "python", "visual-studio", "visual-studio-2008", "visual-c++", "" ]
I have a property on a domain object that is declared in a many-to-one element. The basic syntax of this property looks like this: ``` <many-to-one name="propertyName" class="propertyClass" fetch="select" not-found="ignore" lazy="proxy" /> ``` Now, the idea is to have Hibernate NOT eagerly fetch this property. It may...
If the other end of the association can be *null*, I believe hibernate must query for the association end in order to determine if it should use a proxy or not (no need for proxy if the other end is *null*). I can't find the reference to this right now, but I remember reading it somewhere. In order to provide lazy-loa...
> I found lazy=no-proxy, but the > documentation talks about some sort of > bytecode modification and doesn't go > into any details. Can someone help me > out? I'll assume you're using ANT to build your project. ``` <property name="src" value="/your/src/directory"/><!-- path of the source files --> <property name="li...
How to stop Hibernate from eagerly fetching many-to-one associated object
[ "", "java", "hibernate", "" ]
I have a T4 template that generates classes from an xml file. How can I add a dependency between the xml file and the template file so that when the xml file is modified the template is rerun automatically without choosing "Run custom tool" from the context menu?
I don't believe T4 supports automatic template transformation based on an external dependency. I agree with Marc - if you only have one external file, you could create a custom "custom tool" for your XML file or simply use [ttxgen](http://code.msdn.microsoft.com/TTxGen). However, I don't think this approach scales up t...
How long does the tool take to execute? One lazy option might be to simply edit the csproj such that it *always* runs the tool during build (presumably via [`<Exec ... />`](http://msdn.microsoft.com/en-us/library/x8zx72cd.aspx) or a custom `targets` file) - of course, this depends on it being quick to execute. Another...
How to add a dependency to a arbitrary file to a T4 template?
[ "", "c#", ".net", "t4", "" ]