Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm trying to get: ``` document.createElement('div') //=> true {tagName: 'foobar something'} //=> false ``` In my own scripts, I used to just use this since I never needed `tagName` as a property: ``` if (!object.tagName) throw ...; ``` So for the second object, I came up with the following as a quick solution --...
This might be of interest: ``` function isElement(obj) { try { //Using W3 DOM2 (works for FF, Opera and Chrome) return obj instanceof HTMLElement; } catch(e){ //Browsers not supporting W3 DOM2 don't have HTMLElement and //an exception is thrown and we end up here. Testing some //properties th...
The [accepted answer](https://stackoverflow.com/a/384380/1204556) is a bit complicated, and does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML as well as SVG, etc. See it in action here: <https://jsfiddle.net/eLuhbu6r/> ``` function isEleme...
How do you check if a JavaScript Object is a DOM Object?
[ "", "javascript", "dom", "object", "" ]
How can I create a local user account using .NET 2.0 and c# and also be able to set the "Password never expires" to never. I have tried using "Net.exe" using Process.Start and passing its parameters but it seems that the "net user" is unable to set the "Password never expires" to never.
Read this excellent CodeProject article [**Howto: (Almost) Everything In Active Directory via C#**](http://www.codeproject.com/KB/system/everythingInAD.aspx) There is a section "Create User Account" and "Dealing with User Passwords". **UPDATE:** *To adapt the code for local accounts replace the respective lines wit...
This code will create a local account with the password never expires option set: ``` using System.DirectoryServices; DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"); DirectoryEntries entries = hostMachineDirectory.Children; bool userExists = false; ...
Creating local user account c# and .NET 2.0
[ "", "c#", ".net", "account", "" ]
I'm implementing a sparse matrix with linked lists and it's not fun to manually check for leaks, any thoughts?
The [`valgrind`](http://valgrind.org/) profiler for Unix offers a decent leak detection. However, this is only one part of a successful approach. The other part is to prevent (i.e. minimize) explicit memory handling. Smart pointers and allocators can help a great deal in preventing memory leaks. Also, *do* use the STL...
**On Windows:** Compuware BoundChecker (bit costly but very nice) Visual LeakDetector (free, google it) **On Linux/Unix:** Purify
What is the best way to check for memory leaks in c++?
[ "", "c++", "memory-leaks", "" ]
I'm trying to Remote Debugging a Windows Forms Application (C#), but i'm always getting this error: > *Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor > named 'XXX. The Visual Studio Remote > Debugger on the target computer cannot > connect back to this computer. > Authentication failed. Plea...
This is how it worked for me: Remote computer: Microsoft Virtual PC, "IHS\RDM" attached to my corporate domain, logged in as jdoe, administrator account. Local computer: Attached to local domain, logged in as jdoe, administrator account. 1) remote computer: install rdbgsetup.exe (from Visual Studio 2005\Disk 2\Remot...
The problem that I had is that I had 2 users: ``` mydomain\user1 mytestmachine\user1 ``` that is not correct (according to Gregg Miskely) i needed to define a local user in my development computer, for example: ``` mydevcomputer\debug mytestmachine\debug ``` with the same password and run the VS2008 and the Debuggi...
Remote Debugging in Visual Studio (VS2008), Windows Forms Application
[ "", "c#", ".net", "visual-studio-2008", "debugging", "remote-debugging", "" ]
In replies to [one of my questions](https://stackoverflow.com/questions/391503/if-condition-continue-or-if-condition-style-preference), I received a number of answers saying that style 2 may perform better than style 1. I don't understand how, since I believe they should emit essentially the same machine instructions (...
I had to check this. Here is my version of the code: ``` using System; using System.Collections.Generic; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Tester t=new Tester(); t.Method1(new Stack<string>(), new MsgParser(), true, true)...
I think performance would be negligibly different if it's different at all. A compiler may optimze them into the same form anyway. The only substantive difference is stylistic. I like style 1 just because the loop has one entry point (per iteration) and one exit point (per iteration) so it's easy to insert debug code...
Which one of these code samples has better performance?
[ "", "c#", "performance", "" ]
I would like to display tagcloud in my home page. Found this wordpress flash plugin <http://alexisyes.com/tags/wpcumulus> , but for that i needed to setup wordpress. I am wondering whether there is any other standalone plugin similar to wpcumulus which can be configurable. I don't want to install wordpress but i would...
You could definitely use wpcumulus (I just downloaded it and checked it out). You just have to figure out what data it needs to create a tag cloud. First, you need to download the swf and add it to your site. You can take a look of an installed version / demo of it to see the proper swf embed html. Next, you have to ...
In other words, I would like to have 'auto-refresh' functionality for the tag cloud. Can it be done?
Tag clouds: Are there any in either flash or javascript
[ "", "javascript", "flash", "" ]
I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory. Normally, I build the path using the following code:...
I found a solution. You need to check if the application is running as a script or as a frozen exe: ``` import os import sys config_name = 'myapp.cfg' # determine if application is a script file or frozen exe if getattr(sys, 'frozen', False): application_path = os.path.dirname(sys.executable) elif __file__: ...
According to the [documentation](https://pyinstaller.readthedocs.io/en/stable/runtime-information.html) of PyInstaller, the suggested method of recovering application path is as follows: ``` #!/usr/bin/python3 import sys, os if getattr(sys, 'frozen', False): # If the application is run as a bundle, the PyInstaller...
Determining application path in a Python EXE generated by pyInstaller
[ "", "python", "executable", "relative-path", "pyinstaller", "" ]
I'm currently using ReSharper's 30-day trial, and so far I've been impressed with the suggestions it makes. One suggestion puzzles me, however. When I explicitly define a variable, such as: ``` List<String> lstString = new List<String>(); ``` ReSharped adds a little squiggly green line and tells me to: > Use implic...
> So, is there some sort of performance gain to be had from changing the List to a var No but this is not the only valid reason for a refactoring. More importantly, it removes redundance and makes the code shorter without any loss in clarity. > I've always been taught that explicitly defining a variable, rather than ...
Nope. They emit the **exact same IL**. It's just a matter of style. `var` has the benefit that makes it easier for you to change the return type of functions without altering other parts of source code. For example change the return type from `IEnumerable<T>` to `List<T>`. However, it might make it easier to introduc...
C# 'var' keyword versus explicitly defined variables
[ "", "c#", "performance", "resharper", "" ]
If you use an `EnumSet` to store conventional binary values (1,2,4 etc), then when there are less than 64 items, I am led to believe that this is stored as a bit vector and is represented efficiently as a long. Is there a simple way to get the value of this long. I want a quick and simple way to store the contents of t...
As far as I'm aware, this isn't exposed. You could basically rewrite it yourself - have a look at the code for EnumSet to get an idea of the code - but it's a pity there isn't a nicer way of getting at it :(
I don't think this can be done in a generic way. Converting to a long is pretty easy: ``` public static <T extends Enum<T>> long enumSetToLong(EnumSet<T> set) { long r = 0; for(T value : set) { r |= 1L << value.ordinal(); } return r; } ``` I don't know how you can possibly convert from a l...
Getting the value from an EnumSet in Java
[ "", "java", "" ]
I'm using C# on Framework 3.5. I'm looking to quickly group a Generic List<> by two properties. For the sake of this example lets say I have a List of an Order type with properties of CustomerId, ProductId, and ProductCount. How would I get the sum of ProductCounts grouped by CustomerId and ProductId using a lambda exp...
``` var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID }) .Select(group => group.Sum(x => x.ProductCount)); ```
I realize this thread is very old but since I just struggled through this syntax I thought I'd post my additional findings - you can return the sum and the IDs (w/o foreach) in one query like so: ``` var sums = Orders .GroupBy(x => new { x.CustomerID, x.ProductID }) .Select(group =>new {group.K...
C# List<> GroupBy 2 Values
[ "", "c#", "linq", "list", "ienumerable", "group-by", "" ]
I am working on a project to redesign/ redo an application. The problem is that the old application was written in ASP.net 1.0 and the database is pretty large over 100 tables and 300 odd views.The database handles roles and membership in a very shoddy way. It involves a simple workflow too. The app is pain when it com...
Database redesign is a huge effort. If you or someone on your team is not an expert in database design and ETL, you could end up with a worse mess than you have now. However, is it possible to perhaps fix just the one or two worst parts of the database and thus achieve an improvement overall? Look at the worst perform...
Is your charge to redesign the database or the entire application? Are you on a solo mission or do you have a decent amount of help? Does your company employ any methodology standards (SDLC processes) or are you a maverick IT department? Four months sounds very aggressive. You'll need to document the requirements, pla...
Dealing with application redesign
[ "", "c#", "asp.net", "database-design", "" ]
We mostly tend to following the above best practice. Have a look at [String vs StringBuilder](https://stackoverflow.com/questions/73883/string-vs-stringbuilder) But StringBuilder could throw **OutOfMemoryException even when there is sufficient memory available**. It throws OOM exception because it needs "continuous b...
The underyling string you create will also need a contiguous block of memory because it is represented as an array of chars (arrays require contiguous memory) . If the StringBuilder throws an OOM exception you woludn't be able to build the underlying without it. If creating a string causes an OOM, there is likely a mo...
If StringBuilder is going to throw an OutOfMemoryException in your particular situation, then doing manual string concatenation is NOT a better solution; it's much worse. This is exactly the case (creating an extremely, extremely long string) where StringBuilder is supposed to be used. Manual concatenation of a string ...
StringBuilder for string concatenation throws OutOfMemoryException
[ "", "c#", "out-of-memory", "stringbuilder", "" ]
Python provides the "\*" operator for unpacking a list of tuples and giving them to a function as arguments, like so: ``` args = [3, 6] range(*args) # call with arguments unpacked from a list ``` This is equivalent to: ``` range(3, 6) ``` Does anyone know if there is a way to achieve this in PHP? Some go...
You can use [`call_user_func_array()`](http://www.php.net/call_user_func_array) to achieve that: `call_user_func_array("range", $args);` to use your example.
In `php5.6` [Argument unpacking via `...` (splat operator)](http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat) has been added. Using it, you can get rid of `call_user_func_array()` for this simpler alternative. For example having a function: ``` function add($a, $b){ return $a...
unpacking an array of arguments in php
[ "", "php", "arguments", "iterable-unpacking", "" ]
I have the following classes: ``` public class Person { public String FirstName { set; get; } public String LastName { set; get; } public Role Role { set; get; } } public class Role { public String Description { set; get; } public Double Salary { set; get; } public Boolean HasBonus { set; get;...
``` public static List<String> DiffObjectsProperties(object a, object b) { Type type = a.GetType(); List<String> differences = new List<String>(); foreach (PropertyInfo p in type.GetProperties()) { object aValue = p.GetValue(a, null); object bValue = p.GetValue(b, null); if (p.P...
If the properties aren't value types, why not just call DiffObjectProperties recursively on them and append the result to the current list? Presumably, you'd need to iterate through them and prepend the name of the property in dot-notation so that you could see what is different -- or it may be enough to know that if t...
How to diff Property Values of two objects using GetType GetValue?
[ "", "c#", ".net", "reflection", "object", "properties", "" ]
Firstly, I'm a newbie to C# and SharePoint, (less than a month's experience) so apologies if this is an obvious or easy question but I've been trawling the net for a couple of days now with absolutely no success. I have an xslt file that I have stored in a subdirectory of 'Style Library' from within the new website bu...
Here is a bit of code to retrieve the list items from a list: ``` SPList list = web.Lists["MyLibrary"]; if (list != null) { var results = from SPListItem listItem in list.Items select new { ...
without linq: ``` int itemId = getItemId(); SPWeb currentWeb = SPContext.Current.Web; SPList list = currentWeb.Lists["MyList"]; if ( list != null ) { SPListItem theItem = list.Items.GetItemById(itemId); doWork(theItem); } ``` The SPWeb can be retrieved in numerous ways, using the SPContext will work if the...
Programmatically Accessing SharePoint Style Library from within C#
[ "", "c#", "sharepoint", "spsite", "spweb", "" ]
In the external code that I am using there is enum: ``` enum En {VALUE_A, VALUE_B, VALUE_C}; ``` In another external code that I am using there are 3 #define directives: ``` #define ValA 5 #define ValB 6 #define ValC 7 ``` Many times I have int X which is equal to ValA or ValB or ValC, and I have to cast it to the ...
Since you can't just cast here, I would use a free function, and if there are likely to be other enums that also need converting, try to make it look a little bit like the builtin casts: ``` template<typename T> T my_enum_convert(int); template<> En my_enum_convert<En>(int in) { switch(in) { case ValA: re...
While implicit casting is more convenient than translation functions it is also less obvious to see what's going on. An approach being both, convenient and obvious, might be to use your own class with overloaded cast operators. When casting a custom type into an enum or int it won't be easy to overlook some custom cast...
enum-int casting: operator or function
[ "", "c++", "enums", "casting", "" ]
*It is a messy question, hopefully you can figure out what I want :)* **What is the best way to use Win32 functionality in a Qt Open Source Edition project?** Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its in...
You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide t...
You could use win32 scopes in your .pro file; ``` win32:HEADERS+=mywinheader.h ``` or with .pri (pro include) files to compartmentalize it even more; ``` win32:include( mywinpri.pri ) ``` You would typically use this apprpoach with the PIMPL idiom as monjardin describes
Using Win32 API in Qt OSE project
[ "", "c++", "windows", "winapi", "qt", "qt4", "" ]
I am doing some population modeling (for fun, mostly to play with the concepts of Carrying Capacity and the Logistics Function). The model works with multiple planets (about 100,000 of them, right now). When the population reaches carrying capacity on one planet, the inhabitants start branching out to nearby planets, a...
Use units of megapeople to achieve more headroom. Also, Decimal lets you have 100,000 planets each with 100000000000000 times the population of the Earth, if [my arithmetic](http://www.google.co.uk/search?hl=en&rlz=1B5GGGL_enGB302GB302&q=(79228162514264337593543950335+%2F+100000)+%2F+6000000000&btnG=Search&meta=) is r...
Even if each planet has 100 billion people, the total is still only 1E16. This is well within the limit of a signed 64 bit integer (2^63 goes to 9,223,372,036,854,775,807 which is almost 1E19... You could go with a Million Billion people per planet, with 100000 planets before you got close to the limit... As to fract...
Very, very large C# floating-point numbers
[ "", "c#", "math", "bigdecimal", "" ]
I'm attempting to code a script that outputs each user and their group on their own line like so: ``` user1 group1 user2 group1 user3 group2 ... user10 group6 ``` etc. I'm writing up a script in python for this but was wondering how SO might do this. p.s. Take a whack at it in any language but I'd prefer py...
For \*nix, you have the [pwd](http://docs.python.org/2/library/pwd.html) and [grp](http://docs.python.org/2/library/grp.html) modules. You iterate through `pwd.getpwall()` to get all users. You look up their group names with `grp.getgrgid(gid)`. ``` import pwd, grp for p in pwd.getpwall(): print p[0], grp.getgrgid...
the `grp` module is your friend. Look at `grp.getgrall()` to get a list of all groups and their members. **EDIT** example: ``` import grp groups = grp.getgrall() for group in groups: for user in group[3]: print user, group[0] ```
Python script to list users and groups
[ "", "python", "linux", "system-administration", "" ]
I have this sample text, which is retrieved from the class name on an html element: ``` rich-message err-test1 erroractive rich-message err-test2 erroractive rich-message erroractive err-test1 err-test2 rich-message erroractive ``` I am trying to match the "test1"/"test2" data in each of these examples. I am currentl...
From what I am reading, your code already works. **`Regex.exec()` returns an array of results on success.** The first element in the array (index 0) returns the entire string, after which all `()` enclosed elements are pushed into this array. ``` var string = 'rich-message err-test1 erroractive'; var regex = new Reg...
You could try 'err-([^ \n\r]\*)' - but are you sure that it is the regex that is the problem? Are you using the whole result, not just the first capture?
Help with regex in javascript
[ "", "javascript", "regex", "classname", "" ]
This is really stumping me today. I'm sure its not that hard, but I have a System.Reflection.PropertyInfo object. I want to set its value based on the result of a database lookup (think ORM, mapping a column back to a property). My problem is if the DB returned value is DBNull, I just want to set the property value to...
I believe if you just do ``` prop.SetValue(obj,null,null); ``` If it's a valuetype, it'll set it to the default value, if it's a reference type, it'll set it to null.
``` object defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null; ```
.NET - Get default value for a reflected PropertyInfo
[ "", "c#", ".net", "reflection", "" ]
How do I copy text to the clipboard (multi-browser)? Related: *[How does Trello access the user's clipboard?](https://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard)*
# Overview There are three primary browser APIs for copying to the clipboard: 1. [Async Clipboard API](https://www.w3.org/TR/clipboard-apis/#async-clipboard-api) `[navigator.clipboard.writeText]` * Text-focused portion available in [Chrome 66 (March 2018)](https://developers.google.com/web/updates/2018/03/clipboa...
Automatic copying to the clipboard may be dangerous, and therefore most browsers (except Internet Explorer) make it very difficult. Personally, I use the following simple trick: ``` function copyToClipboard(text) { window.prompt("Copy to clipboard: Ctrl+C, Enter", text); } ``` The user is presented with the prompt ...
How do I copy to the clipboard in JavaScript?
[ "", "javascript", "clipboard", "copy-paste", "" ]
I actually have two questions regarding the same problem but I think it is better to separate them since I don't think they are related. Background: I am writing a Windows Mobile software in VB.NET which among its tasks needs to connect to a mail-server for sending and retrieving e-mails. As a result, I also need a Mi...
CF .NET requires you to use the signature: Encoding.GetString Method (array[], Int32 index, Int32 count) so try using: ``` ...GetString(b, 0, b.Length); ```
If you look up the Encoding class on MSDN you'll find information about the availability of methods in the compact framework. <http://msdn.microsoft.com/en-us/library/system.text.encoding.default.aspx> In your case the System.Text.Encoding.Default property is supported by the .NET Compact Framework 3.5, 2.0, 1.0 so y...
c# - error compiling targeting Compact Net Framework 3.5 - No overload for method 'GetString' takes '1' arguments
[ "", "c#", "windows-mobile", "compact-framework", "mime", "" ]
Is there an "easy" way to select either a file OR a folder from the same dialog? In many apps I create I allow for both files or folders as input. Until now i always end up creating a switch to toggle between file or folder selection dialogs or stick with drag-and-drop functionality only. Since this seems such a basi...
Technically, it is possible. The shell dialog used by FolderBrowseDialog has the ability to return both files and folders. Unfortunately, that capability isn't exposed in .NET. Not even reflection can poke the required option flag. To make it work, you'd have to P/Invoke SHBrowseForFolder() with the BIF\_BROWSEINCLUDE...
Based on the above tips I found some working code that uses the standard Folder Browser dialog at the following location: <http://topic.csdn.net/t/20020703/05/845468.html> The Class for the extended Folder Browser Dialog ``` Imports System Imports System.Text Imports System.Windows.Forms Imports System.Runti...
Select either a file or folder from the same dialog in .NET
[ "", "c#", ".net", "vb.net", "winforms", "openfiledialog", "" ]
Is there a CRUD generator utility in Java like Scaffolding in Rails? Can be in any framework or even plain servlets. Must generate controllers + views in jsp, not just DAO code...
[Spring Roo](http://www.springsource.org/roo) seems to be exactly what you're looking for: CRUD code generation, spits out pure Java code that can be made tun run entirely independant from the framework.
[Grails](http://grails.org/Scaffolding) has scaffolding.
Is there a CRUD generator utility in Java(any framework) like Scaffolding in Rails?
[ "", "java", "ruby-on-rails", "crud", "scaffolding", "" ]
Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call?
Instead of worrying about disposing your web services, you could keep only a single instance of each web service, using a [singleton pattern](http://csharpindepth.com/Articles/General/Singleton.aspx). Web services are stateless, so they can safely be shared between connections and threads on a web server. Here is an e...
I think the DataService inherits Dispose from Component.
Do I need to dispose a web service reference in ASP.NET?
[ "", "c#", "asp.net", "web-services", "dispose", "" ]
Within my a certain function of a class, I need to use `setInterval` to break up the execution of the code. However, within the `setInterval` function, "this" no longer refers to the class "myObject." How can I access the variable "name" from within the `setInterval` function? ``` function myObject() { this.name =...
``` myObject.prototype.test = function() { // this works alert(this.name); var oThis = this; var intervalId = setInterval(function() { // this does not work alert(oThis.name); clearInterval(intervalId); },0); } ``` This should work. The anonymous function's "this" is not th...
Here's the prototype bind function ``` Function.prototype.bind = function( obj ) { var _this = this; return function() { return _this.apply( obj, arguments ); } } ```
Javascript: How to access a class attribute from a function within one of the class's functions
[ "", "javascript", "oop", "class-design", "" ]
I know the possibilities of basic leak detection for Win32 using the *crtdbg.h* header, but this header is unavailable in the CE CRT library headers (i'm using the lastest SDK v6.1). Anyone knows how I can automatically detect leaks in a WinCE/ARMV4I configuration with VC 9.0? I don't want to override new/delete for m...
At work (developing WindowsCE based OS + Applications) we have created our own memory manager, roughly based on the [Fluid Studios Memory Manager](http://www.paulnettle.com/pub/FluidStudios/MemoryManagers/Fluid_Studios_Memory_Manager.zip) (the link which I found using SO!). I'm pretty sure with a few simple modificatio...
You want to use either [AppVerifier](http://msdn.microsoft.com/en-us/library/aa934674.aspx) or [Entrek CodeSnitch](http://entrek.com/products.htm#CodeSnitch). I've had much better luck getting CodeSnitch working in a short period of time. The caveat there is I don't do a whole lot of WinMo - mostly vanilla CE. I believ...
How to detect leaks under WinCE C/C+ runtime library?
[ "", "c++", "windows-mobile", "memory-leaks", "windows-ce", "crtdbg.h", "" ]
According to FXCop, List should not be exposed in an API object model. Why is this considered bad practice?
I agree with moose-in-the-jungle here: `List<T>` is an unconstrained, bloated object that has a lot of "baggage" in it. Fortunately the solution is simple: expose `IList<T>` instead. It exposes a barebones interface that has most all of `List<T>`'s methods (with the exception of things like `AddRange()`) and it doesn...
There are the 2 main reasons: * List<T> is a rather bloated type with many members not relevant in many scenarios (is too “busy” for public object models). * The class is unsealed, but not specifically designed to be extended (you cannot override any members)
Why is it considered bad to expose List<T>?
[ "", "c#", "fxcop", "" ]
I'm embedding a Flash ActiveX control in my C++ app (Flash.ocx, Flash10a.ocx, etc depending on your Flash version). I can load an SWF file by calling LoadMovie(0, filename), but the file needs to physically reside in the disk. How to load the SWF from memory (or resource, or stream)? I'm sure there must be a way, beca...
Appearantly I a going to need to supply details for a vote 'up'.. OK. The internal flash buffer when first initiailized indicates if a movie is loaded or if the buffer hold properties in the buffer fisrt four bytes. gUfU -- no movie loaded. properties to follow .... fUfU -- .. [4bytes] size as integer. then the UNC...
To spare you some typing. It works for me in this way (just works not extensively tested): ``` void flash_load_memory(FlashWidget* w, void* data, ULONG size) { FlashMemoryStream fStream = FlashMemoryStream(data, size); IPersistStreamInit* psStreamInit = NULL; w->mFlashInterface->QueryInterface(...
Flash ActiveX: How to Load Movie from memory or resource or stream?
[ "", "c++", "flash", "activex", "ocx", "shockwave", "" ]
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables? This is what I intend to do: ``` c = MyClass() c.foo = 123 c.bar = 123 # c.foo == 123 and c.bar == 123 d = {'bar': 456} c.update(d) # c.foo == 123 and c.bar == 456 ``` Something akin to dic...
there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in `c.__dict__` which isn't always true. ``` d = {'bar': 456} for key,value in d.items(): setattr(c,key,value) ``` or you could write a `update` method as part of `MyClass` so th...
Have you tried ``` f.__dict__.update( b ) ``` ?
Python update object from dictionary
[ "", "python", "iterable-unpacking", "" ]
Many developers seem to be either intimidated or a bit overwhelmed when an application design requires both procedural code and a substantial database. In most cases, "database" means an RDBMS with an SQL interface. Yet it seems to me that many of the techniques for addressing the "impedance mismatch" between the two ...
I implemented an ORM-to-isam library back in the 1990s that enjoyed some (very) modest success as shareware. I largely agree with what you say about the virtues of ISAMs and I think it better to use an ISAM when building an ORM layer or product if you are looking only for flexibility and speed. However, the risk that ...
Maybe Pig Latin is what you want? According to this article <http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=693D79B5EFDC0452E1C9A87D1C495D4C?doi=10.1.1.124.5496&rep=rep1&type=pdf> : > "Besides, many of the people who ana- > lyze this data are entrenched > procedural programmers, who find the > declarative, S...
Choosing ISAM rather than SQL
[ "", "sql", "orm", "isam", "" ]
I have a snippet of code that I'm working with to filter rows in a table. It works perfectly in every browser other than Firefox v3.0.x (works fine with 3.1 beta 2). When I run the snippet in Firefox 3.0.x, it says that `children is undefined`. I am using jQuery v1.2.6 also. Code Snippet: ``` var bodyRows = $("#resul...
Why not use jQuery to traverse the DOM elements instead. ``` var bodyRows = $("#resultsTable tbody tr"); bodyRows.each(function(){ var thirdCell = $(this).find('td').eq(2); if(!filterPattern.test($.trim(thirdCell.html()))){ this.style.display = 'none'; } else { this.style.display = ''; ...
``` if(!filterPattern.test($.trim(this.children[2].innerHTML))) ``` When an 'each' callback is invoked by jQuery, 'this' is a direct browser DOM node, not a jQuery object. Confusion occurs because jQuery offers a 'children' method on its DOM wrappers, and IE offers a non-standard 'children' collection on its native D...
jQuery each tr.children is undefined in Firefox 3.0
[ "", "javascript", "jquery", "firefox-3", "" ]
I am trying to create a sidebar for a site that will allow a user to select an item from a drop down menu and show an RSS Feed. The feed will change depending on which item is selected from the list. I am not sure how to acomplish this, but my first thought was to use z-index and show/hide layers. I have one layer and ...
you have two options: 1. pre-load all the rss feeds (i'm assuming your `<ul>`'s in your example page are the HTML output of your RSS feeds?), hide them all when your document loads, and then reveal them as selected 2. use AJAX to dynamically grab the selected feed information as your select box changes. here's a quic...
This uses jQuery and jFeed plugin to replace the contents of a DIV based on a dropdown selection. ``` // load first feed on document load $(document).ready( function() { load_feed( $('select#feedSelect')[0], 'feedDiv' ) ); // pick first } ); function load_feed( ctl, contentArea ) // load based on sele...
Creating a Drop Down Menu That Changes Page Content Using Show/Hide Layers and Z-Index
[ "", "javascript", "z-index", "data-layers", "drop-down-menu", "" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
One common convention is to use a "\_" as a variable name for the elements of the tuple you wish to ignore. For instance: ``` def f(): return 1, 2, 3 _, _, x = f() ```
You can use `x = func()[0]` to return the first value, `x = func()[1]` to return the second, and so on. If you want to get multiple values at a time, use something like `x, y = func()[2:4]`.
Ignore python multiple return value
[ "", "python", "function", "tuples", "" ]
I'm working on a project for the .net platform and would like to support multiple database types. I would like to keep the DDL under source control in a generic format then convert it to database specific DDL for deployment. So I'm looking for utilities that will convert generic DDL into database specific DDL. Ideally...
The only one that I know of that has support for SQL Server is [SQLFairy](http://sqlfairy.sourceforge.net/). It's written in Perl and is pretty feature rich. XML2DDL is pretty good too, but if it doesn't support your DBMS of choice it's not really viable.
NHibernate's [SchemaExport tool](http://hibernate.org/hib_docs/nhibernate/html/toolsetguide.html) can generate an appropriate DDL from the OR mappings for any of NHibernate's supported DBMS dialects. However, as others have implied, if you're working at that level you're really restricted to the rather thin common deno...
Best database independent SQL DDL utility?
[ "", ".net", "sql", "version-control", "ddl", "" ]
When I try to set the `z` variable in the code below, I get this compile time error: > Operator '\*' cannot be applied to operands of type 'double' and 'decimal' ``` decimal x = 1, y = 2, z; // There are two ways I set the z variable: z = (x*y)*(.8 * 1.732050808m); z = (1000 * x)/(y * 1.732050808m)* .8; ``` Why is ...
Be sure to use `.8m` instead of `.8`.
You didn't say which line it was, but I'm betting on these two: ``` z = (x*y)*(.8 * 1.732050808m); ``` And: ``` z = (1000 * x)/(y * 1.732050808m)* .8; ``` Note that your .8 does not have the 'm' qualifier. Every other place I see you did supply that.
Why am I getting a compile error when multiplying a decimal by a literal value?
[ "", "c#", "decimal", "" ]
I'm currently using the ModelStateDictionary in asp.net mvc to hold validation errors and pass then back to the user. Being able to check if the whole model is valid with ModelState.IsValid is particularly. However, a current application I'm working on has a need to be able to report warnings. These aren't as critical ...
So the route that I was headed down before turned out to be a bad idea, there just isn't enough access in the framework to get at the bits that you need. At least not without reinventing the wheel a few times. I decided to head down the route of extending the ModelState class to add a warnings collection to it: ``` p...
Why not simply add a list of warnings, or a dictionary, to the ViewData and then display them in your view? e.g. ``` ViewData[ "warnings" ] = new[] { "You need to snarfle your aardvark" } ; ```
Model Warnings in ASP.NET MVC
[ "", "c#", "asp.net-mvc", "model", "" ]
Does any one know of a control that i can use with a ASP.Net gridview that provides the functionality of the ASP.Net Ajax Control PagingBulletedList. I want to provide the users with a easier way to access the data in the grid. It should ideally work in the same way paging for the grid works except that it should show...
Unfortunatly there is nothing already buildt for this. To build your own you will have to create your own [PagerTemplate](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.pagertemplate.aspx). There is something similiar with code in it in this [tutorial](http://www.highoncoding.com/Articles/2...
it's ugly, but just have a paged datagrid, with a single cell that has a separate ul/li .. they'll line up together, and give you the functionality you want. Otherwise you may have to roll your own.
ASP.Net PagingBulletedList Extender For ASP.Net GridView
[ "", "c#", "asp.net", "" ]
I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only: ``` %config = ( 'color' => 'red', 'numbers' => [5, 8], qr/^spam/ => 'eggs' ); ``` What's the best way to convert the contents of these files into Python-equivalent data structures, using pure ...
Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python. Perl has this ``` %config = ( 'color' => 'red', 'numbers' => [5, 8], qr/^spam/ => 'eggs' ); ``` In Python, it would be ``` config = { 'color' : 'red', 'numbers' : [5, 8], re.com...
Is using pure Python a requirement? If not, you can load it in Perl and convert it to YAML or JSON. Then use PyYAML or something similar to load them in Python.
How can I read Perl data structures from Python?
[ "", "python", "perl", "configuration", "data-structures", "" ]
I would like to build a regexp in Java that would be passed in a FilenameFilter to filter the files in a dir. The problem is that I can't get the hang of the regexp "mind model" :) This is the regexp that I came up with to select the files that I would like to exclude ((ABC|XYZ))+\w\*Test.xml What I would like to d...
> What I would like to do is to select > all the files that end with `Test.xml` > but do not start with `ABC` or `XYZ`. Either you match all your files with this regex: ``` ^(?:(?:...)(?<!ABC|XYZ).*?)?Test\.xml$ ``` or you do the opposite, and take every file that does *not* match: ``` ^(?:ABC|XYZ).*?Test\.xml$ ```...
This stuff is easier, faster and more readable without regexes. ``` if (str.endsWith("Test.xml") && !str.startsWith("ABC")) ```
Java regexp for file filtering
[ "", "java", "regex", "" ]
I've got the following two tables (in MySQL): ``` Phone_book +----+------+--------------+ | id | name | phone_number | +----+------+--------------+ | 1 | John | 111111111111 | +----+------+--------------+ | 2 | Jane | 222222222222 | +----+------+--------------+ Call +----+------+--------------+ | id | date | phone_...
There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables: This is the shortest statement, and may be quickest if your phone book is very short: ``` SELECT * FROM Call WHERE phone_number NOT IN (SELECT phone_num...
``` SELECT Call.ID, Call.date, Call.phone_number FROM Call LEFT OUTER JOIN Phone_Book ON (Call.phone_number=Phone_book.phone_number) WHERE Phone_book.phone_number IS NULL ``` Should remove the subquery, allowing the query optimiser to work its magic. Also, avoid "SELECT \*" because it can break your code if s...
Find records from one table which don't exist in another
[ "", "sql", "mysql", "" ]
Not that I'm trying to prevent 'View Source' or anything silly like that, but I'm making some custom context menus for certain elements. EDIT: response to answers: I've tried this: ``` <a id="moo" href=''> </a> <script type="text/javascript"> var moo = document.getElementById('moo'); function handler(event)...
Capture the `onContextMenu` event, and return false in the event handler. You can also capture the click event and check which mouse button fired the event with `event.button`, in some browsers anyway.
If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag ``` <body oncontextmenu="return false;"> ``` This will block all access to the context menu (not just from the right mouse button but from the keyboard as well) However, there really is no po...
How to disable right-click context-menu in JavaScript
[ "", "javascript", "contextmenu", "" ]
Can anyone give me an idea how can we *show* or embed a YouTube video if we just have the URL or the Embed code?
You have to ask users to store the 11 character code from the youtube video. For e.g. <http://www.youtube.com/watch?v=Ahg6qcgoay4> The eleven character code is : Ahg6qcgoay4 You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from ...
Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the `<object>` embed code has been retired in favor of `<iframe>` embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or...
How to embed YouTube videos in PHP?
[ "", "php", "html", "video", "youtube", "youtube-api", "" ]
``` public class CovariantTest { public A getObj() { return new A(); } public static void main(String[] args) { CovariantTest c = new SubCovariantTest(); System.out.println(c.getObj().x); } } class SubCovariantTest extends CovariantTest { public B getObj() { return ...
This is because in Java member variables don't override, they *shadow* (unlike methods). Both A and B have a variable x. Since c is *declared* to be of type CovarientTest, the return of getObj() is implicitly an A, not B, so you get A's x, not B's x.
Java **doesn't override fields** (aka. attributes or member variables). Instead they [shadow over](http://leepoint.net/notes-java/data/variables/60shadow-variables.html) each other. If you run the program through the debugger, you'll find two `x` variables in any object that is of type `B`. Here is an explanation on w...
Java Covariants
[ "", "java", "" ]
I have a numerical field called `category_id` in my table. I want to do something like this. ``` $ids=implode(',',$id_array); $sql="SELECT * FROM myTbl WHERE IN(category_id,'$ids')"; ``` Which should output something like: ``` SELECT * FROM myTbl WHERE IN(category_id,'1,2,3,4,5,6'); ``` Is this possible and am I us...
From where do you get the id array? If it's from the database you should consider doing it all there: ``` SELECT * FROM myTbl WHERE c_id IN (SELECT c_id FROM yourTable WHERE ...); ```
Almost, but not quite - here is one way it could work ``` $ids="'".implode("','",$id_array)."'"; $sql="SELECT * FROM myTbl WHERE category_id IN($ids)"; ``` Which should output something like: ``` SELECT * FROM myTbl WHERE category_id IN('1', '2', '3', '4', '5', '6'); ``` Note that since the field is numeric, the qu...
Best query syntax for nested tables?
[ "", "sql", "mysql", "" ]
I'm trying to create proper header files which don't include too many other files to keep them clean and to speed up compile time. I encountered two problems while doing this: 1. Forward declaration on base classes doesn't work. ``` class B; class A : public B { // ... } ``` 2. Forward dec...
The first problem you can't solve. The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class. Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition....
As answered before by Earwicker, you can not use forward declarations in any of those cases as the compiler needs to know the size of the class. You can only use a forward declaration in a set of operations: * declaring functions that take the forward declared class as parameters or returns it * declaring member poin...
Forward Declaration of a Base Class
[ "", "c++", "class", "forward-declaration", "" ]
> **Possible Duplicate:** > [What static analysis tools are available for C#?](https://stackoverflow.com/questions/38635/what-static-analysis-tools-are-available-for-c) Guys, I'm looking for an open source or free source code analysis tool for C#. The tool should be able to generate metrics from the source code such...
There are many plugins for reflector (which is also free): [Reflector Add-Ins](http://www.codeplex.com/reflectoraddins) I believe the CodeMetrics plugin does what you need
NDepend will give you a vast number of stats for your code: <http://codebetter.com/blogs/patricksmacchia/archive/2008/11/25/composing-code-metrics-values.aspx> There is a free 'Trial' version which contains fewer features than the Professional product, but which is free to use for Open Source and Academic development...
Source code analysis tools for C#
[ "", "c#", "" ]
> Possible duplicate > [Debug Visual Studio Release in .NET](https://stackoverflow.com/questions/90871/debug-vs-release-in-net) What is the difference between Debug and Release in Visual Studio?
The most important thing is that in Debug mode there are no optimizations, while in Release mode there are optimizations. This is important because the compiler is very advanced and can do some pretty tricky low-level improving of your code. As a result some lines of your code might get left without any instructions at...
"Debug" and "Release" are actually just two labels for a whole slew of settings that can affect your build and debugging. In "Debug" mode you usually have the following: * Program Debug Database files, which allow you to follow the execution of the program quite closely in the source during run-time. * All optimizati...
What is the difference between Debug and Release in Visual Studio?
[ "", "c#", ".net", "visual-studio", "" ]
What are good online resources to learn Python, *quickly*, for some who can code decently in other languages? edit: It'll help if you could explain why you think that resource is useful.
[Dive into python](http://diveintopython.net/toc/index.html) I have gone over it in a weekend or so and it was enough to learn almost all the idioms of the language and get the feeling of what is "the Python way" :-)
Not sure if you already considered that, but [documentation at the official site](http://docs.python.org/3.0/) is very good. In particular, [Tutorial](http://docs.python.org/3.0/tutorial/index.html) lets you start quickly
Resources for moving to Python
[ "", "python", "" ]
Are Swing applications really used nowadays? I don't find a place where they are used. Is it okay to skip the AWT and Swing package (I learned a bit of the basics though)?
If you are writing for the web exclusively, you can probably skip Swing, but otherwise you're absolutely going to run into it. I've never worked on a non-trivial Java app without a Swing GUI. Also, Swing is one of the better APIs to use. If you use most others, you are going to find them more difficult to use and/or p...
You may checkout [Swing Sightings](http://java.sun.com/products/jfc/tsc/sightings/). This website is hosted by SUN and it is dedicated to sw projects that use Swing. There are a lot of projects using Swing ... <http://java.sun.com/products/jfc/tsc/sightings/>
Where are Swing applications used?
[ "", "java", "swing", "" ]
I’ve run into a limitation in the cURL bindings for PHP. It appears there is no easy way to send the same multiple values for the same key for postfields. Most of the workarounds I have come across for this have involved creating the URL encoded post fields by hand tag=foo&tag=bar&tag=baz) instead of using the associat...
I ended up writing my own function to build a custom CURLOPT\_POSTFIELDS string with multipart/form-data. What a pain. ``` function curl_setopt_custom_postfields($ch, $postfields, $headers = null) { // $postfields is an assoc array. // Creates a boundary. // Reads each postfields, detects which are @files,...
If you use `tag[]` rather than `tag` for the name, [PHP will generate an array](http://www.php.net/manual/en/faq.html.php#faq.html.arrays) for you, in other words, rather than ``` tag=foo&tag=bar&tag=baz ``` You need ``` tag[]=foo&tag[]=bar&tag[]=baz ``` Note that when urlencoded for transmission this should become...
Mixing multiple values for the same key and file uploads using cURL and PHP
[ "", "php", "curl", "" ]
I am trying to create an ActiveRecord object via a JSON request. However the controller fails to set the variables passed in the parameters in the newly created object. As an example, a person object has two fields: firstname and lastname. The JSON generated by the JSON.stringify function of the JSON.org library produ...
If you are just passing a hash of all of the person parameters (rather than a nested-hash with "person" as the key) then you should just be able to do `@person = Person.new(params)`.
As for ActiveRecord 3.0.7, you can just add ``` self.include_root_in_json = false ``` to your model (person.rb) to get rid from root ({ "Person" :") part.
Rails controller does not accept JSON?
[ "", "javascript", "ruby-on-rails", "json", "" ]
You can initialize an array like this: ``` int [ ] arr = { 1, 2, 3, 4, 5 }; ``` but `List<T>` doesn't allow this: ``` List<int> list = { 1, 2, 3, 4, 5 }; ``` What's the reason behind this? After all both allow this: ``` int [ ] arr = new int [ ] { 1, 2, 3, 4, 5 }; List<int> list = new List<int> { 1, 2, 3, 4, 5 ...
Your first sample is the standard language syntax for initializing an array of integers. The left-hand value evaluates to int[]. In the second sample you are attempting to assign an int[] to a List<int>. The assignment operator doesn't support this as they are different types. A List<int> is **not** an array of type in...
Here is what the **C# 3.0 Language Spec** has to say on the subject: > The following is an example of an > object creation expression that > includes a collection initializer: > > ``` > List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; > ``` > > The collection object to which a > collection initialize...
Collection initialization
[ "", "c#", ".net", "" ]
I'm in a ASP.NET project where I need to give several parameters to the administrator that is going to install the website, like: ``` AllowUserToChangePanelLayout AllowUserToDeleteCompany ``` etc... My question is, will be a good thing to add this into the web.config file, using my own configSession or add as a prof...
I usually use Settings - available via the project properties - Settings. These can be edited and saved in code, and I write a form / web page to edit them. If you want to use the XML configuration, there's an attribute called file that reads external files. You could have a web.config file and a someothername.config ...
just to let you guys know that I did what [configurator](https://stackoverflow.com/users/9536/configurator) recommended but with a twist. instead of asking all the time (that I need) for ``` System.Configuration.ConfigurationManager.AppSettings["myKey"]; ``` I just created a static class that would pull this values ...
create your own settings in xml
[ "", "c#", "asp.net", "configuration-files", "" ]
I have a web service that needs different settings for different environments (debug, test, prod). What's the easiest way to setup separate config files for these different environments? Everything I find on the web tells me how to use configuration manager to retrieve settings, but not how to find particular settings ...
I find having several config files for each environment works well. ie: * config\local.endpoints.xml * config\ dev.endpoints.xml * config\ test.endpoints.xml * config\ staging.endpoints.xml * config\ prod.endpoints.xml I then link to a "master" version of this using the built in configSource attribute within the web....
One way would be to maintain 3 different configuration files and choose them via MSBuild when deploying. ``` <Choose> <When Condition="$(BuildEnvironment) == 'debug'"> <PropertyGroup> <ConfigFile>debug.config</ConfigFile> </PropertyGroup> </When> <Whe...
How do you set up solution configuration specific config files?
[ "", "c#", "visual-studio", "web-services", "" ]
What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be ``` /** Split a list into two sublists. The original list will be modified to * have size i and will contain e...
Quick semi-pseudo code: ``` List sub=one.subList(...); List two=new XxxList(sub); sub.clear(); // since sub is backed by one, this removes all sub-list items from one ``` That uses standard List implementation methods and avoids all the running around in loops. The clear() method is also going to use the internal `re...
You can use common utilities, like Guava library: ``` import com.google.common.collect.Lists; import com.google.common.math.IntMath; import java.math.RoundingMode; int partitionSize = IntMath.divide(list.size(), 2, RoundingMode.UP); List<List<T>> partitions = Lists.partition(list, partitionSize); ``` The result is a...
Java: split a List into two sub-Lists?
[ "", "java", "list", "" ]
I have a large-ish Oracle table containing rows representing units of work, with columns for start time and end time in addition to other meta-data. I need to generate usage graphs from this data, given some arbitrary filtering criteria and a reporting time period. E.g., show me a graph of all of Alice's jobs for the ...
In terms of getting the data out, you can use 'group by' and '[truncate](http://www.techonthenet.com/oracle/functions/trunc_date.php)' to slice the data into 1 minute intervals. eg: ``` SELECT user_name, truncate(event_time, 'YYYYMMDD HH24MI'), count(*) FROM job_table WHERE event_time > TO_DATE( some start date time) ...
Your best bet is to have a table (a temporary one generated on the fly would be fine if the time-slice is dynamic) and then join against that.
Time slicing in Oracle/SQL
[ "", "sql", "oracle", "optimization", "reporting", "graphing", "" ]
By default the BinaryWriter class writes int values with the low bits on the left (e.g. (int)6 becomes 06 00 00 00 when the resulting file is viewed in a hex editor). I need the low bits on the right (e.g. 00 00 00 06). How do I achieve this? EDIT: Thanks strager for giving me the name for what I was looking for. I'v...
Jon Skeet has an EndianBitConverter [here](http://www.pobox.com/~skeet/csharp/miscutil/) that should do the job. Just use big/little endian as desired. Alternatively, just shift the data a few times ;-p ``` int i = 6; byte[] raw = new byte[4] { (byte)(i >> 24), (byte)(i >> 16), ...
Not really a built in way but you can use this: [EndianBit\*](http://www.yoda.arachsys.com/csharp/miscutil/). Thanks to Jon Skeet :P
How do I write ints out to a text file with the low bits on the right side (Bigendian)
[ "", "c#", "endianness", "" ]
I understand that the @ symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the @ symbol?
The @ symbol allows you to use reserved word. For example: ``` int @class = 15; ``` The above works, when the below wouldn't: ``` int class = 15; ```
The @ symbol serves 2 purposes in C#: Firstly, it allows you to use a reserved keyword as a variable like this: ``` int @int = 15; ``` The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this: ``...
What does the @ symbol before a variable name mean in C#?
[ "", "c#", "variables", "naming", "specifications", "reserved-words", "" ]
My Java UI unexpectly terminated and dumped an `hs_err_pid` file. The file says "The crash happened outside the Java Virtual Machine in native code." JNA is the only native code we use. Does anyone know of any know issues or bugs with any JNA version that might cause this. I've included some of the contents from the er...
I just hit that very same bug, it's apppearantly a bug in the new Direct3d accelerated Java2d functionality with 1.6.0\_11 that happens with machines with low video ram. If you start your app with -Dsun.java2d.d3d=false it should work again. The sun bug tracking this is the following: <https://bugs.java.com/bugdatabase...
Just because the only bit of native code you knowingly use is JNI/whatever doesn't mean a crash like yours is related to it in location or in time. There's all sorts of native support used silently in any given JVM/execution, and I was at one time getting bizarre crashes caused in the end by corruption that had happene...
JNA causing EXCEPTION_ACCESS_VIOLATION?
[ "", "java", "java-native-interface", "awt", "jna", "" ]
I have an application that I'm trying to debug a crash in. However, it is difficult to detect the problem for a few reasons: * The crash happens at shutdown, meaning the offending code isn't on the stack * The crash only happens in release builds, meaning symbols aren't available By crash, I mean the following except...
You can make the symbol files even for the release build. Do that, run your program, attach the debugger, close it, and see the cause of the crash in the debugger.
You seem to have something reading a null pointer - never good. I'm not sure what platform you are on. Under Linux, you could consider using `valgrind`. What is different about your release builds from your debug builds apart from the presence or absence of the debug information? Can you built the statically linked ...
How to diagnose Access Violation on application exit
[ "", "c++", "wtl", "" ]
I'm trying to use a dll, namely libcurl, with my program, but, it's not linking. Libcurl comes with .h files that I can include (takes care of dllimport), but then I guess I must specify which dll to actually use when linking somehow... How do I do that? I'm compiling with Borland C++ builder, but I really want to know...
As mentioned, you will need the static .lib file that goes with the .dll which you run through implib and add the result lib file to your project. If you have done that then: * You may need to use the stdcall calling convention. You didn't mention which version of Builder you are using, but it is usually under Pr...
There should be a program called IMPLIB.EXE in the bin or app directory for builder. Run that against the dll to create a .lib file. [IMPLIB.EXE, the Import Library Tool for Win32](https://docwiki.embarcadero.com/RADStudio/Alexandria/en/IMPLIB.EXE,_the_Import_Library_Tool_for_Win32)
Use a dll from a c++ program. (borland c++ builder and in general)
[ "", "c++", "dll", "c++builder", "dllimport", "" ]
I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff. I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever. I ...
Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields. ``` for (i = 0; i < numberOfTextFields; i++) { JTextField textField = new JTextField(); container.add(textField); /* also store textField somewhere else. */ } ```
Try something like this: ``` List<JTextField> nums = new ArrayList<JTextField>(); JTextField tempField; for (int i = 0; i < 10; i++) { tempField = new JTextField(); jPanel1.add(tempField); // Assuming all JTextFields are on a JPanel nums.add(tempField); } ``` Don't forget to set a proper layout manager f...
Java GUI Creating Components
[ "", "java", "user-interface", "jbutton", "jtextfield", "" ]
What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application?
Well, gSOAP of course. :) <http://www.cs.fsu.edu/~engelen/soap.html>
You could also look at: <http://pocoproject.org/>
What C++ HTTP frameworks are available?
[ "", "c++", "frameworks", "" ]
I have a .NET assembly which I have exposed to COM via a tlb file, and an installer which registers the tlb. I have manually checked that the installer works correctly and that COM clients can access the library. So far, so good... However, I am trying to put together some automated system tests which check that the i...
The Closest I've gotten to a solution is something like the following: ``` using System; class ComClass { public bool CallFunction(arg1, arg2) { Type ComType; object ComObject; ComType = Type.GetTypeFromProgID("Registered.ComClass"); // Create an instance of your COM Registered...
You should be able to create a wrapper class to your installed COM component using TLBImp then run your tests against that. You'll basically be writing a .Net assembly, installing that to COM then testing against the wrapper class so your tests will be routed as if it was called by a COM component
Is it possible to test a COM-exposed assembly from .NET?
[ "", "c#", "visual-studio", "com", "interop", "com-interop", "" ]
I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like ...
This is how you could do it in python: ``` #!/usr/bin/python2.5 from email.utils import parsedate import mailbox def extract_date(email): date = email.get('Date') return parsedate(date) the_mailbox = mailbox.mbox('/path/to/mbox') sorted_mails = sorted(the_mailbox, key=extract_date) the_mailbox.update(enumera...
Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon. There are a bug: messages shall prefix with 'from' line in format: ``` From - Tue Apr 27 19:42:22 2010 ``` but ImportExportTools prefix with such 'from' line: ``` From - Sat May 01 2010 15:07:31 GMT+0400 (R...
How can I reorder an mbox file chronologically?
[ "", "python", "email", "sorting", "mbox", "" ]
I'm aiming to create a set of objects, each of which has a unique identifier. If an object already exists with that identifier, I want to use the existing object. Otherwise I want to create a new one. I'm trying not to use the word Singleton, because I know it's a dirty word here... I can use a factory method: ``` ...
The static method is defined on the parent class, and it's called statically as well. So, there's no way of knowing in the method that you've called it on the subclass. The java compiler probably even resolves the call statically to a call to the parent class. So you will need to either reimplement the static method i...
Have you looked into Guice? Not sure if it would solve your problem exactly, but it acts as a generic factory and dependency injection container, and eliminates non-type safe String keys.
Polymorphic factory / getInstance() in Java
[ "", "java", "design-patterns", "polymorphism", "factory", "" ]
I'm trying to make a graph in Rails, for example the avg sales amount per day for each day in a given date range Say I have a products\_sold model which has a "sales\_price" float attribute. But if a specific day has no sales (e.g none in the model/db), I want to return simply 0. What's the best way in MySQL/Rails to...
Is there a reason (other than the date one already mentioned) why you wouldn't use the built-in group function capabilities in ActiveRecord? You seem to be concerned about "post-processing", which I don't think is really something to worry about. You're in Rails, so you should probably be looking for a Rails solution ...
For any such query, you will need to find a mechanism to generate a table with one row for each date that you want to report on. Then you will do an outer join of that table with the data table you are analyzing. You may also have to play with NVL or COALESCE to convert nulls into zeroes. The hard part is working out ...
Best way in MySQL or Rails to get AVG per day within a specific date range
[ "", "sql", "mysql", "ruby-on-rails", "ruby", "static-analysis", "" ]
Is it possible to use JavaScript to open an HTML select to show its option list?
Unfortunately there's a simple answer to this question, and it's "No"
I had this problem...and found a workable solution. I didn't want the select box to show until the user clicked on some plain HTML. So I overlayed the select element with `opacity=.01`. Upon clicking, I changed it back to `opacity=100`. This allowed me to hide the select, and when the user clicked the text the select ...
Is it possible to use JS to open an HTML select to show its option list?
[ "", "javascript", "html-select", "" ]
I have been investigating for some time now a way to prevent my user from accidently entering a data directory of my application. My application uses a folder to store a structured project. The folder internal structure is critic and should not be messed up. I would like my user to see this folder as a whole and not b...
Looks like some [Windows ports of FUSE](http://sourceforge.net/apps/mediawiki/fuse/index.php?title=OperatingSystems#Windows) are starting to appear. I think this would be the best solution since it would allow me to keep the legacy code (which is quite large) untouched.
Inside, or outside of your program? There are ways, but none of them easy. You are probably going to be looking at a Filter Driver on the file system.
Windows Explorer directory as bundle
[ "", "c++", "windows", "directory", "bundle", "windows-shell", "" ]
We have 2 applications that run under JBoss. I am looking for a way to reduce the overhead of the server. The main app runs under Tomcat. The other app is made up of MBeans. Is there a way to run MBeans under Tomcat? Alternative suggestions are appreciated.
MBeans are a part of the JMX specification which is included in the JRE. It should be possible to run MBeans under Tomcat. Tomcat 5 or later provides an MBean server.
You can use the following JVM arguments to startup Tomcat with MBean enabled ``` -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=4444 (could be anything) -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false ```
Can an MBean be run under Tomcat?
[ "", "java", "tomcat", "jboss", "mbeans", "" ]
> **Possible Duplicate:** > [LINQ equivalent of foreach for IEnumerable<T>](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet) The linq extension methods for ienumerable are very handy ... but not that useful if all you want to do is apply some computation to each item in the enu...
Shedding a little more light on why: LINQ is functional in nature. It is used to query data and return results. A LINQ query shouldn't be altering the state of the application (with some exceptions like caching). Because foreach doesn't return any results, it doesn't have many uses that don't involve altering the stat...
Actually, the Reactive Extensions framework from Microsoft Research did add this functionality. In the `System.Interactive` assembly they've included a `Run()` and a `Do()` extensions to `IEnumerable<T>`. **Do(action)** will execute the action on each element and yield it back. This is useful for adding logging to a l...
Existing LINQ extension method similar to Parallel.For?
[ "", "c#", "linq", "extension-methods", "iteration", "" ]
I need to be able to see if a form input in PHP is numeric. If it is not numeric, the website should redirect. I have tried is\_numeric() but it does not seem to work. Code examples will be nice. I am developing a shopping cart that accepts an integer value for the quantity. I am trying this: ``` if(!is_numeric($qua...
``` if(!is_numeric($quantity == 0)){ //redirect($data['referurl']."/badinput"); echo "is not numeric"; ``` What you have here are two nested conditions. Let's say $quantity is 1. The first condition evaluates 1 == 0 and returns FALSE. The second condition checks if FALSE is numeric and...
You should probably explain what you mean by "numeric" - integral, floating point, exponential notation etc? [`is_numeric()`](http://www.php.net/manual/en/function.is-numeric.php) will accept all of these. If you want to check that a string contains nothing other than digits, then you could use a regular expression, e...
How can I check if form input is numeric in PHP?
[ "", "php", "validation", "numeric", "" ]
I have a friend who likes to use metaclasses, and regularly offers them as a solution. I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order. Being a...
I have a class that handles non-interactive plotting, as a frontend to Matplotlib. However, on occasion one wants to do interactive plotting. With only a couple functions I found that I was able to increment the figure count, call draw manually, etc, but I needed to do these before and after every plotting call. So to ...
I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones. Most metaclasses I've seen do one of two things: 1. Registration (adding a class to a data structure): ``` models...
What are some (concrete) use-cases for metaclasses?
[ "", "python", "metaclass", "" ]
I am retrieving three different sets of data (or what should be "unique" rows). In total, I expect 3 different unique sets of rows because I have to complete different operations on each set of data. I am, however, retrieving more rows than there are in total in the table, meaning that I must be retrieving duplicate ro...
Consider if Name is not unique. If you have the following data: ``` Table 1 Table 2 ID Name Address ID Name Address 0 Jim Smith 1111 A St 0 Jim Smith 2222 A St 1 Jim Smith 2222 B St 1 Jim Smith 3333 C St ``` Then Query 1 gives you: ``` 0 Jim...
Are you sure that NAME and ID are unique in both tables? If not, you could have a situation, for example, where table 1 has this: NAME: Fred ID: 1 and table2 has this: NAME: Fred ID: 1 NAME: Fred ID: 2 In this case, the record in table1 will be returned by two of your queries: ID and NAME both match, and NAME mat...
Query three non-bisecting sets of data
[ "", "sql", "sql-server", "" ]
Is there a managed API to retrieve an application's install date using the Product GUID? Thanks. Scott
The "proper" way to get to that information is to use ::MsiGetProductInfo(). PInvoke should be trivial.
Thanks Rob! I've added a complete C# example below. ``` [DllImport("msi.dll", CharSet = CharSet.Unicode)] static extern Int32 MsiGetProductInfo(string product, string property, [Out] StringBuilder valueBuf, ref Int32 len); static void Main(string[] args) { Int32 len = 512; var builder ...
Get install date from managed code
[ "", "c#", "wix", "windows-installer", "" ]
Hey everyone, I'm working on a PHP application that needs to parse a .tpl file with HTML in it and I'm making it so that the HTML can have variables and basic if statements in it. An if statement look something like this: ` ``` <!--if({VERSION} == 2)--> Hello World <!--endif --> ``` To parse that, I've tried using `p...
I think you meant to do this: ``` '/<!--if\(([^)]*)\)-->([^<]*)<!--endif-->/' ``` Your regex has only one character class in it: ``` [^\]*)\)-->([^<] ``` Here's what's happening: * The first closing square bracket is escaped by the backslash, so it's matched literally. * The parentheses that were supposed close th...
You have a space between `endif` and `-->` but your regular expression doesn't allow this. Incidentally, this seems horribly insecure... Is there any reason you're not using a pre-built templating engine like Smarty?
Template ifs using regex
[ "", "php", "regex", "" ]
I have a `JPanel` subclass on which I add buttons, labels, tables, etc. To show on screen it I use `JFrame`: ``` MainPanel mainPanel = new MainPanel(); //JPanel subclass JFrame mainFrame = new JFrame(); mainFrame.setTitle("main window title"); mainFrame.getContentPane().add(mainPanel); mainFrame.setLocation(100, 100)...
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go: ``` MainPanel mainPanel = new MainPanel(); JFrame mainFrame = new JFrame(); mainFrame.setLayout(new BorderLayout()); mainFrame.add(mainPanel, BorderLayout.CENTER); mainFrame.pack(); mainFrame.setVisible(true);...
You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager. Simply adding the following line of code should fix your problems: ``` mainFrame.setLayout(new BorderLayout()); ``` (Do this before adding components to the JFrame)
Automatically size JPanel inside JFrame
[ "", "java", "swing", "size", "jframe", "jpanel", "" ]
There is a particular website I must use for work which is absolutely heinous and despised by all who must use it. In particular, the site's Javascript is fundamentally broken and works only in IE, which pretty much makes it the only site I must use outside my preferred browsers. So, to the question. If I could '***pa...
For Opera, you want [User JavaScript](http://www.opera.com/browser/tutorials/userjs/). Similar to Greasemonkey, but built-in to Opera. Built to be used for exactly the sort of situation you're in: fixing sites that are broken in Opera...
For Firefox, you could use the [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748) addon to do this.
How can I patch client side javascript on a website after loading it in Opera or Firefox?
[ "", "javascript", "firefox", "opera", "" ]
Even though I've been a developer for awhile I've been lucky enough to have avoided doing much work with XML. So now I've got a project where I've got to interact with some web services, and would like to use some kind of Object-to-XML Mapping solution. The only one I'm aware of is JAXB. Is that the best to go with? A...
If you're calling a web-service with a WSDL, JAXB is absolutely the best option. Take a look at wsimport, and you're be up and running in 10 minutes. I don't think JAXB 2.0 will be possible on Java 1.4. You may need to use Axis instead: ``` java -cp axis-1.4.jar;commons-logging-1.1.jar;commons-discovery-0.2.jar;jaxrp...
**JAXB is the best choice:** * [Public API included in Java SE 6](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/package-summary.html) * Binding layer for JAX-WS (Web Services) * Binding layer for JAX-RS (Rest) * [Can preserve XML Infoset](http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation...
What is the best Java OXM library?
[ "", "java", "oxm", "" ]
Is there any reason to prefer a `CharBuffer` to a `char[]` in the following: ``` CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append( buf.flip() ); buf.clear(); } ``` vs. ``` char[] buf = new char[DEFAULT_BUFFER_SIZE]; int n; while( (n = in.read(buf)) >= 0 ) { out...
No, there's really no reason to prefer a `CharBuffer` in this case. In general, though, `CharBuffer` (and `ByteBuffer`) can really simplify APIs and encourage correct processing. If you were designing a public API, it's definitely worth considering a buffer-oriented API.
I wanted to mini-benchmark this comparison. Below is the class I have written. The thing is I can't believe that the CharBuffer performed so badly. What have I got wrong? *EDIT: Since the 11th comment below I have edited the code and the output time, better performance all round but still a significant difference in...
CharBuffer vs. char[]
[ "", "java", "io", "buffer", "" ]
Say I have a package "mylibrary". I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace. I.e., I do: ``` import sys, types sys.modules['mylibrary.con...
You need to monkey-patch the module not only into sys.modules, but also into its parent module: ``` >>> import sys,types,xml >>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config') >>> import xml.config >>> from xml import config >>> from xml import config as x >>> x <module 'xml.config' (built-in)...
As well as the following: ``` import sys, types config = types.ModuleType('config') sys.modules['mylibrary.config'] = config ``` You also need to do: ``` import mylibrary mylibrary.config = config ```
Making a virtual package available via sys.modules
[ "", "python", "import", "module", "" ]
I'm writing a C# wrapper for a third-party native library, which we have as a DLL. I would like to be able to distribute a single DLL for the new assembly. Is it possible for me to embed the win32 DLL in my .NET DLL, and still make calls into it using P/Invoke? If so, how?
I've never done it but I know of an opensource project that does this. They embed the native SQLite3 code into the managed SQLite assembly using their own tool called [mergebin](http://www.koushikdutta.com/2008/09/day-6-mergebin-combine-your-unmanaged.html). Go and take a look at the [SQLite project for .NET by PHX](h...
Should work, if the native dll does not have any dependencies. You can compile the dll in as embedded resource, than access the stream from inside your code, serialize it to the temporary folder and use it from there. Too much to post example code here, but the way is not to complicated.
Can I embed a win32 DLL in a .NET assembly, and make calls into it using P/Invoke?
[ "", "c#", ".net", "pinvoke", "" ]
In Java, what are the performance and resource implications of using ``` System.currentTimeMillis() ``` vs. ``` new Date() ``` vs. ``` Calendar.getInstance().getTime() ``` As I understand it, `System.currentTimeMillis()` is the most efficient. However, in most applications, that long value would need to be conver...
`System.currentTimeMillis()` is obviously the most **efficient** since it does not even create an object, but `new Date()` is really just a thin wrapper about a long, so it is not far behind. `Calendar`, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and al...
Looking at the JDK, innermost constructor for `Calendar.getInstance()` has this: ``` public GregorianCalendar(TimeZone zone, Locale aLocale) { super(zone, aLocale); gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone); setTimeInMillis(System.currentTimeMillis()); } ``` so it already automatically does w...
System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()
[ "", "java", "performance", "date", "time", "calendar", "" ]
I have some code that prints out databse values into a repeater control on an asp.net page. However, some of the values returned are null/blank - and this makes the result look ugly when there are blank spaces. How do you do conditional logic in asp.net controls i.e. print out a value if one exists, else just go to ne...
It's going to be a pretty subjective one this as it completely depends on where and how you like to handle null / blank values, and indeed which one of those two you are dealing with. For example, some like to handle nulls at the database level, some like to code default values in the business logic layer and others l...
I suggest wrapping each key/value pair into custom control with 2 properties. This control will display itself only if value is not empty: ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ShowPair.ascx.cs" Inherits="MyWA.ShowPair" %> <% if (!string.IsNullOrEmpty(Value)) { %> <%=Key %> : <%=Value %...
Conditional Logic in ASP.net page
[ "", "c#", "asp.net", "conditional-statements", "" ]
In which cases, except development, would you prefer XAMPP over a complete installation and configuration of Linux, Apache, MySQL, and PHP?
Other than development, the only other time I use it is for demos - it's nice being able to take a "solution on a stick" to a customer. I'd never consider it for a live/public site though.
I would say that XAMPP would be preferred over a complete manual install, whenever one is not confident enough, skilled enough, experienced enough, or educated enough to properly install, the OS, HTTP server, database server, and language system with all the mainstream security and stability aspects in mind, and compen...
When to prefer XAMPP over a complete installation of Linux, Apache, MySQL, and PHP
[ "", "php", "mysql", "linux", "apache", "xampp", "" ]
Can I call a remote webservice from a Stored Procedure and use the values that areretuned?
If you're using SQL 2005/2008, you could do this from a CLR stored procedure if you have the ability to install and run these. For more info: <http://msdn.microsoft.com/en-us/library/ms190790.aspx>
Service Broker might provide the sort of functionality you're looking for here.
Webservice From SQL
[ "", "sql", "web-services", "t-sql", "" ]
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors. Here is what I did from my constructor: ``` m_cRedundencyManager->Init(this->RedundencyManagerCallBack); ``` This doesn't compile - I get the following error: > Er...
That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument. Instead you can pass a static member function as follows, which are like normal non-member functions in this regard: ``` m_cRedundencyManager->Init(&CLoggersInfra::Callbac...
This is a simple question but the answer is surprisingly complex. The short answer is you can do what you're trying to do with `std::bind1st` or `boost::bind`. The longer answer is below. The compiler is correct to suggest you use `&CLoggersInfra::RedundencyManagerCallBack`. First, if `RedundencyManagerCallBack` is a ...
How can I pass a class member function as a callback?
[ "", "c++", "callback", "function-pointers", "c++03", "" ]
How to know, in Python, that the directory you are in is inside a symbolic link ? I have a directory **/tmp/foo/kiwi** I create a symlink **/tmp/bar** pointing to **/tmp/foo** I enter into **/tmp/bar/kiwi** the linux command **pwd** tells me I'm in **/tmp/bar/kiwi**, which is correct. The python command prompt tel...
If you don't find anything else, you can use ``` os.getenv("PWD") ``` It's not really a portable python method, but works on POSIX systems. It gets the value of the `PWD` environment variable, which is set by the `cd` command (if you don't use `cd -P`) to the path name you navigated into (see `man cd`) before running...
If your symlink is set up in the way you state, then `/tmp/foo/kiwi` is the directory that you're really in. `/tmp/bar/kiwi` is just another way to get to the same place. Note that the shell command `pwd -P` will give you the physical path of the current directory. In your case, the shell is remembering that you got w...
How to know when you are in a symbolic link
[ "", "python", "" ]
Using the Java version of Lucene, how would you find out the number of documents in an index?
IndexReader contains the methods you need, in particular, numDocs <http://lucene.apache.org/core/3_6_0/api/all/org/apache/lucene/index/IndexReader.html#numDocs()>
The official documentation: <http://lucene.apache.org/java/2_4_0/api/org/apache/lucene/index/IndexReader.html#numDocs()>
Finding the number of documents in a Lucene index
[ "", "java", "lucene", "" ]
``` private HashMap<DataObject, HashSet> AllDataObjects; ... /** Returns all DataObject elements that are NOT in the specified set. */ private DataObject[] invert( HashSet<DataObject> set ) { HashSet<DataObject> keys = (HashSet) AllDataObjects.keySet(); keys = (HashSet) keys.clone(); keys.removeAll( set ...
Create a new set and give the one to be cloned as an argument. This avoids casting and so you don't lose generics. ``` private DataObject[] invert( Set<DataObject> set ){ Set<DataObject> keys = new HashSet<DataObject>(AllDataObjects.keySet()); keys.removeAll( set ); return keys.toArray(new DataObject[]{});...
Knowing that these sets were populated by a relational query, I would suggest that you at least trade off writing a better SQL query to get what you want rather than doing it in memory. There are several reasons why. First, most relational databases are optimized to do this more efficiently than your code will. Second,...
Cloning and subtracting sets - does this work?
[ "", "java", "collections", "clone", "set", "subtraction", "" ]
I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go. Up until now I've had a static class that does some common formatting e.g. Formatting.FormatCurrency Formatting.FormatBookingReferen...
One option is to use a helper class with extension methods like ``` public static class MyWebAppExtensions { public static string FormatCurrency(this decimal d) { return d.ToString("c"); } } ``` Then anywhere you have a decimal value you do ``` Decimal d = 100.25; string s = d.FormatCurrency(); `...
I agree with GeekyMonkey's suggestion, with one alteration: Formatting is an implementation detail. I would suggest `ToCurrencyString` to keep with the To\* convention and its intent.
Formatting strings in C# consistently throughout a large web application
[ "", "c#", ".net", "asp.net", "architecture", "formatting", "" ]
These are some questions for any developer whose made the jump from Java to .Net: If you could go back to the start of your switched, what would you do to make the transition easier? Any books you would recommend? How is .Net compared to Java EE? Anything that totally bugs you? And the most important, do you regret...
I did several years of C/C++ development in between Java and .NET, so my experience may be a bit different. I found the move from Java to C# very easy. The languages are very similar and much of the framework works in similar ways. I loved Java, but I don't think I will be going back. I think the biggest differences f...
Get a decent refactoring plugin for VS, because you will miss all the nice refactorings of your Java-IDE.
From Java to .Net
[ "", "java", ".net", "" ]
I need to check to see if a variable contains anything OTHER than `a-z`, `A-Z`, `0-9` and the `.` character (full stop).
``` if (preg_match('/[^A-Z\d.]/i', $var)) print $var; ```
There are two ways of doing it. Tell whether the variable contains any one character *not* in the allowed ranges. This is achieved by using a negative character class [^...]: ``` preg_match('/[^a-zA-Z0-9\.]/', $your_variable); ``` Th other alternative is to make sure that every character in the string *is* in the al...
Check if string only contains alphanumeric and dot characters
[ "", "php", "regex", "validation", "alphanumeric", "whitelist", "" ]
**Hi All,** It's clear wehn I change any control and then posts back the SaveViewState method saves the changes and apply them agian after postback, see the folowing code notice that server-side-code put in a scrispt in my code liske this <% %> ``` switch (myQuestion.QuestionType) { case 0: { ...
**Thanks All** I found the reason, the code script placed in .aspx file is called "code render block", its executed during the render phase and after save view state phase so the changes done by this kind of code **just renderd but not saved**, as simple as that.
try to do rdlistAnswers.Databind() and cblistAnswers.Databind() after the foreach.
I Can't see my dynamically generated RadioButtonList or CheckBoxList items after postback
[ "", "c#", ".net", "asp.net", "" ]
I'm looking for a kind of array data-type that can easily have items added, without a performance hit. * System.**Array** - `Redim Preserve` copies entire RAM from old to new, as slow as amount of existing elements * System.Collections.**ArrayList** - good enough? * System.Collections.**IList** - good enough?
Just to summarize a few data structures: **System.Collections.ArrayList**: untyped data structures are obsolete. Use List(of t) instead. **System.Collections.Generic.List(of t)**: this represents a resizable array. This data structure uses an internal array behind the scenes. Adding items to List is O(1) as long as t...
You should use the Generic List<> ([System.Collections.Generic.List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx)) for this. It operates in [constant amortized time](https://stackoverflow.com/questions/200384/constant-amortized-time). It also shares the following features with Arrays. * Fast random access (...
Array that can be resized fast
[ "", "c#", "arrays", "resize", "performance", "arraylist", "" ]
I built a Winform app several months ago that schedules appointments for repair techs. I'd like to update the app by adding a map for the customer's address on the customer form, and then print that map on the report the techs take when they leave the office. I've been looking around but I haven't found a good solutio...
Both Google Maps and Live Maps have a public api. Since you are doing winforms I'd probably use live maps. <http://dev.live.com/VirtualEarth/> There are a few examples on CodePlex. <http://codeplex.com/Project/ProjectDirectory.aspx?TagName=Virtual%20Earth>
There is [some example code](http://www.koushikdutta.com/2008/07/virtual-earth-and-google-maps-tiled-map.html) for developing a map viewer control (NB: I doubt this is strictly within their licence) Otherwise, depending on your budget, you could use the [MapPoint ActiveX control](http://msdn.microsoft.com/en-us/cc9057...
Display a map in a Windows Form app
[ "", "c#", "winforms", "maps", "" ]
The `()` seems silly. is there a better way? For example: `ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());`
Sort of! There is a new idiom in town, that is nice and may help you in some cases. It is not fully what you want, but sometimes I think you will like it. Since underscore ("\_") is a valid C# identifier, it is becoming a common idiom to use it as a parameter name to a lambda in cases where you plan to ignore the para...
For a lambda, no: you need `() =>` Is it for a delegate or an expression? For delegates, another option is `delegate {...}`. This may or may not be desirable, depending on the scenario. It is more keys, certainly... In some cases (not this one) you can use a target method directly - i.e. ``` ExternalId.IfNotNullDo(S...
Is there a better way to express a parameterless lambda than () =>?
[ "", "c#", "lambda", "" ]
What are some good end to end CPU profilers that exist for Java? Quick list of things I'm looking for: 1. Offline profiling - No user interaction or GUI required during program execution. Dumping the profile data to a file and then requiring viewing afterwards with a GUI is fine, I just don't want to have to babysit ...
My favorite, by far, is [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html). I didn't realize it until just now (because I always use the interactive profiling GUI), but it does in fact support offline profiling, exactly like you described. A few other cool features: * It profiles all your SQ...
I am not familiar with offline profiling. Isn't it what [hprof](http://java.sun.com/developer/technicalArticles/Programming/HPROF.html) is for?. Otherwise I've had very good experience with [YourKit profiler](http://www.yourkit.com/).
Looking for recommendations for end-to-end Java CPU Profilers
[ "", "java", "profiling", "" ]