Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following code in WCF service to throw a custom fault based on certain situations. I am getting a "The creator of this fault did not specify a Reason" exception. What am I doing wrong? ``` //source code if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - ...
After some addtional research, the following modified code worked: ``` if(!DidItPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason("Invalid Routing Code - No Approval...
The short answer is you are doing nothing wrong, just reading the results incorrectly. On the client side when you catch the error, what is caught is of the type `System.ServiceModel.FaultException<InvalidRoutingCodeFault>`. Your `InvalidRoutingCodeFault` object is actually in the `.detail` property of the FaultExce...
"The creator of this fault did not specify a Reason" Exception
[ "", "c#", ".net", "wcf", "faults", "" ]
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch. What's included, and where can I get other good quality libraries from?
Firstly, the [python libary reference](https://docs.python.org/2/library/index.html) gives a blow by blow of what's actually included. And the [global module index](http://docs.python.org/modindex.html) contains a neat, alphabetized summary of those same modules. If you have dependencies on a library, you can trivially...
run ``` pydoc -p 8080 ``` and point your browser to <http://localhost:8080/> You'll see everything that's installed and can spend lots of time discovering new things. :)
How to find all built in libraries in Python
[ "", "python", "" ]
I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why? ``` <a href="" onclick="javascript: DoSomething();">linky</a> ``` or ``` <...
You **must** have *something* for the `href` attribute, otherwise the browser will not treat it as a link (for example, making it focusable or giving it an underline) - that's why the use of "#" has become prevalent. Also, the contents of the event attributes (`onclick`, `onmouseover`, `on...`) are already treated as ...
Checkout the discussion over at [Href for Javascript links: “#” or “javascript:void(0)”?](https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0). Also, leaving `href` blank causes the browser to not use the pointer cursor when the user mouses over, though you can fix that with CSS.
Using an anchor as a javascript action, what should the link be?
[ "", "javascript", "html", "" ]
In C#, I'm trying to build an extension method for StringBuilder called AppendCollection() that would let me do this: ``` var sb1 = new StringBuilder(); var sb2 = new StringBuilder(); var people = new List<Person>() { ...init people here... }; var orders = new List<Orders>() { ...init orders here... }; sb1.AppendColl...
Use the `Func<T,string>` delegate. ``` public static void AppendCollection<T>(this StringBuilder sb, IEnumerable<T> collection, Func<T, string> method) { foreach(T x in collection) sb.AppendLine(method(x)); } ```
``` public static void AppendCollection<T>(this StringBuilder builder, IEnumerable<T> list, Func<T,string> func) { foreach (var item in list) { builder.AppendLine(func(item)); } } ``` I wouldn't return a string, I would just append it to the original...
StringBuilder extension method for appending a collection in C#
[ "", "c#", "generics", "lambda", "stringbuilder", "" ]
A link that stands out is <http://www.devdaily.com/blog/post/jfc-swing/handling-main-mac-menu-in-swing-application/> however the menu bar under Mac OS X displays as the package name as opposed to the application name. I'm using the code in the above link without any luck, so I'm unsure if anything's changed in recent M...
@Kezzer I think I see what's going on. If you put the main() method in a *different class*, then everything works. So you need something like: ``` public class RootGUILauncher { public static void main(String[] args) { try { System.setProperty("apple.laf.useScreenMenuBar", "true"); ...
You need to set the "com.apple.mrj.application.apple.menu.about.name" system property in the main thread, not in the Swing thread (in other words, just make it the first line in the program).
Native Swing Menu Bar Support For MacOS X In Java
[ "", "java", "swing", "macos", "" ]
I use XML serialization for the reading of my Config-POCOs. To get intellisense support in Visual Studio for XML files I need a schema file. I can create the schema with xsd.exe mylibrary.dll and this works fine. But I want that the schema is always created if I serialize an object to the file system. Is there any wa...
Look at the [`System.Xml.Serialization.XmlSchemaExporter`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlschemaexporter(v=vs.110).aspx) class. I can't recall the exact details, but there is enough functionality in that namespace to do what you require.
thank you, this was the right way for me. solution: ``` XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); Type type = toSerialize.GetType(); XmlTypeMapping map = importer.ImportTypeMapping(type); exporter.Ex...
XML Serialization and Schema without xsd.exe
[ "", "c#", "xml-serialization", "" ]
I would like to deploy a very simple DLL with my C# application, but any DLL that I build in Visual Studio 2008 seems to have a dependency on "Microsoft.VC90.CRT". Is it possible to build a DLL using VS2008 without this dependency? How can I tell what is causing the dependency?
I'm not sure about the latest VC++ versions, but previously you could tell the linker to link with a static version of the MSVCRT runtime library instead of the dynamic (DLL) version. It's possible this option still exists.
According to [this MSDN page](http://msdn.microsoft.com/en-us/library/abx4dbyh.aspx), static libraries are still available. Go to project properties, configuration properties, C/C++, Code generation, Runtime Library. Select Multithreaded Debug for the debug configuration, and Multithreaded for the release config. (Not...
Is it possible to build a DLL in C++ that has no dependencies?
[ "", "c++", "dll", "" ]
I came across a c library for opening files given a Unicode filename. Before opening the file, it first converts the filename to a path by prepending "\\?\". Is there any reason to do this other than to increase the maximum number of characters allowed in the path, per [this msdn article](http://msdn.microsoft.com/en-u...
Yes, it's just for that purpose. However, you will likely see compatibility problems if you decide to creating paths over MAX\_PATH length. For example, the explorer shell and the command prompt (at least on XP, I don't know about Vista) can't handle paths over that length and will return errors.
The best use for this method is probably not to create new files, but to manage existing files, which someone else may have created. I managed a file server which routinely would get files with `path_length > MAX_PATH`. You see, the users saw the files as `H:\myfile.txt`, but on the server it was actually `H:\users\us...
On Windows, when should you use the "\\\\?\\" filename prefix?
[ "", "c++", "winapi", "unicode", "filenames", "max-path", "" ]
I was chatting to someone the other day who suggested that Rails and PHP are the most suitable platforms for web applications, and to avoid Java. My background is mainly Java, and I know that it is considered by some to be too verbose and "heavyweight", but is used occasionally (e.g. by LinkedIn). So I'm wondering whe...
there are two totally different concepts called 'Web 2.0': 1. user generated content (usually with some 'social networking') 2. dynamic AJAX-based web apps the second one somewhat dictates the technologies that you have to use (at least some JS, and machine-readable content in (some) responses). of course, there's no...
I would argue that there is no specific technology for Web 2.0. The main concept behind a Web 2.0 application is that much of the content is provided by it's users and not one specific person. If you can achieve this with Java, then that is fine. Many people are creating startup companies with technology that is free b...
Is Java suitable for "Web 2.0" applications?
[ "", "java", "web-applications", "" ]
In SQL, How we make a check to filter all row which contain a column data is null or empty ? For examile ``` Select Name,Age from MEMBERS ``` We need a check Name should not equal to null or empty.
This will work in all sane databases (*wink, wink*) and will return the rows for which name is not null nor empty ``` select name,age from members where name is not null and name <> '' ```
For DBMSs that treat '' as a value (not null), Vinko's query works: ``` select name,age from members where name is not null and name <> '' ``` For Oracle, which treats '' as a null, tha above doesn't work but this does: ``` select name,age from members where name is not null ``` I tried to think of a "DBMS-agnostic...
How can I filter out the rows which contain a particular column with null or empty data in SQL?
[ "", "sql", "" ]
I'm building a small Winform in which I can view types of food in my kitchen. My entire stock can be displayed by a datagrid view. Now, I have a filtermenu which contains a dropdownlist of items that can be checked and unchecked. Based on which items in that list are checked, the display in the datagridview is chang...
You could use the IndexOfKey property to find the ToolStripMenuItem back. That requires setting the Name property when you add them: ``` ToolStripMenuItem it = (ToolStripMenuItem)item.DropDownItems.Add(element); it.Name = element; // etc.. ```
You are reference checking when you do filterMenu.DropDownItems[s[0]]. You don't match the value of s[0] with the items in DropDownItems but you match their references, and those don't match. You either need to loop through all items and do a manual check if their **value** is the same, or you find a way to insert y...
Dropdown items on a ToolstripmenuItem and seeing if their items are checked
[ "", "c#", "winforms", "visual-studio-2008", "" ]
What is the C# optimised version of the following, without using .Net's Timespan or DateTime. How would I NUnit test it? ``` TimeSpan ts = Date1 - Date2; int numberOfDays = ts.Days; ```
You could convert the dates to ticks, substract, then convert the ticks back to days. Though exactly why can't you use TimeSpan? It's likely doing just that. Something like this: ``` DateTime a = DateTime.Now; DateTime b = a.AddDays(2); // ticks are in hns long ticks = b.Ticks - a.Ticks; ...
Date1 and Date2 are what type? In your exameple it looks to be DateTime. You want your Date in what variable if it's not DateTime? You can always have your Date1 and Date2 in String and play with SubString() to get Year, Month and days but that would be a real pain to work with. The optimized way to do your problem of...
NUnit test DateTime without .Net Timespan or DateTime function
[ "", "c#", "timespan", "" ]
I'm hopeless at Javascript. This is what I have: ``` <script type="text/javascript"> function beginrefresh(){ //set the id of the target object var marquee = document.getElementById("marquee_text"); if(marquee.scrollLeft >= marquee.scrollWidth - parseInt(marquee.style.width)) { ...
Here is a jQuery plugin with a lot of features: <http://jscroller2.markusbordihn.de/example/image-scroller-windiv/> And this one is "silky smooth" <http://remysharp.com/2008/09/10/the-silky-smooth-marquee/>
Simple javascript solution: ``` window.addEventListener('load', function () { function go() { i = i < width ? i + step : 1; m.style.marginLeft = -i + 'px'; } var i = 0, step = 3, space = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; var m = document.getElementById('marquee'); var t = m.innerHTML; //text m....
Javascript Marquee to replace <marquee> tags
[ "", "javascript", "html", "marquee", "" ]
The list `sort()` method is a modifier function that returns `None`. So if I want to iterate through all of the keys in a dictionary I cannot do: ``` for k in somedictionary.keys().sort(): dosomething() ``` Instead, I must: ``` keys = somedictionary.keys() keys.sort() for k in keys: dosomething() ``` Is th...
``` for k in sorted(somedictionary.keys()): doSomething(k) ``` Note that you can also get all of the keys and values sorted by keys like this: ``` for k, v in sorted(somedictionary.iteritems()): doSomething(k, v) ```
Can I answer my own question? I have just discovered the handy function "sorted" which does exactly what I was looking for. ``` for k in sorted(somedictionary.keys()): dosomething() ``` It shows up in [Python 2.5 dictionary 2 key sort](https://stackoverflow.com/questions/157424/python-25-dictionary-2-key-sort)
Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?
[ "", "python", "iterator", "syntactic-sugar", "" ]
I would like to use `[Authorize]` for every action in my admin controller except the `Login` action. ``` [Authorize (Roles = "Administrator")] public class AdminController : Controller { // what can I place here to disable authorize? public ActionResult Login() { return View(); } } ```
I don't think you can do this with the standard Authorize attribute, but you could derive your own attribute from AuthorizeAttribute that takes a list of actions to allow and allows access to just those actions. You can look at the source for the AuthorizeAttribute at [www.codeplex.com](http://www.codeplex.com/aspnet) ...
You can decorate your controller with [Authorize] and then you can just decorate the method that you want to exempt with [AllowAnonymous]
Can you enable [Authorize] for controller but disable it for a single action?
[ "", "c#", "asp.net-mvc", "authorization", "" ]
I have a form that tries to modify a JComponent's graphics context. I use, for example, ``` ((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5)); ``` Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else ...
There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level tha...
Nobody to answer? I have let some time to see if there is any good answer before mine: I am not a specialist of such question... First, I don't fully understand your question: you change a setting then close the form? Anyway, I am not too sure, but somewhere in the process, the graphics context might be recomputed or...
Modifying graphics context in Java
[ "", "java", "swing", "" ]
Is there a generic container implementing the 'set' behaviour in .NET? I know I could just use a `Dictionary<T, Object>` (and possibly add `nulls` as values), because its keys act as a set, but I was curious if there's something ready-made.
`HashSet<T>` in .NET 3.5
I use the Iesi.Collections. namespace that comes with NHibernate (docs [here](http://monogis.org/monogis_doc/html/Iesi.Collections.html)) - maybe worth considering if you are in .NET < 3.5
.NET Generic Set?
[ "", "c#", ".net", "generics", "collections", "set", "" ]
Now I have a stack of free time on my hands, I wanna get into iphone dev fo real. But Objective C scares me (a bit). It feels I'm going a bit back in time. I say this because I've spent the last 8 months coding in C++. [JSCocoa](http://inexdo.com/JSCocoa) looks awesome, but does this actually work on the iphone? Wha...
(Hi, I'm the JSCocoa dev) JSCocoa works on the iPhone simulator. Check out the latest version from Google svn and compile iPhoneTest2. To work on the iPhone, it needs libffi. I've seen <http://code.google.com/p/iphone-dev/source/browse/trunk/llvm-gcc-4.0-iphone/> and some libffi posts regarding Python for iPhone, but ...
a bit of off topic, but: You shouldn't be scared of Objective-C. Of course the syntax looks ugly at first (it did to me), but after a while you get hooked to it. And since you've spent 8 months in C++ i presume you have a good grasp of C which already lightens your weight on learning objective-c!
JSCocoa and the iPhone
[ "", "javascript", "iphone", "" ]
Anyone know what the C# "M" syntax means? ``` var1 = Math.Ceiling(hours / (40.00M * 4.3M)); ```
M is the suffix for Decimal. Stands for "money" I assume. <http://msdn.microsoft.com/en-us/library/364x0z75(VS.71).aspx>
it means that the number is a `decimal` type.
What is this " var1 = Math.Ceiling(hours / (40.00M * 4.3M));"
[ "", "c#", "" ]
If you're running Apache Geronimo in production why did you choose it over other application servers and what are your experiences with running Geronimo in production? Can you also please share what servlet engine you decided to use (Tomcat/Jetty) and why you made this decision? ***UPDATE***: So far this question got...
We definitely use Geronimo in production! We have used the Tomcat version since 1.0, about four years ago as I recall. We are currently running mostly 2.1.1.4. One of our apps gets about 1 million page views per day. The others are nowhere near that, but they are important apps that need to work well. Our choice was...
WebSphere community edition is Geronimo. So IBM chose it as a platform of choice. When choosing an application server, you're really choosing the APIs you want to use in your application and maybe the administration interface (but you only use that once in a while).
Running Apache Geronimo in production
[ "", "java", "jakarta-ee", "geronimo", "" ]
Data table structure is: id1,id2,id3,id4,... (some other fields). I want to create summary query to find out how many times some ID value is used in every column. Data 1,2,3,4,2008 2,3,5,1,2008 1,3,2,5,2007 1,2,3,6,2007 3,1,2,5,2007 For value 1, the result should be 1,0,0,1,2008 2,1,0,0,2007 How to...
This seems like the best solution (from [Wiki](http://en.wikibooks.org/wiki/Programming:MySQL/Pivot_table)): ``` select years, sum(1*(1-abs(sign(id1-56)))) as id1, sum(1*(1-abs(sign(id2-56)))) as id2, sum(1*(1-abs(sign(id3-56)))) as id3, sum(1*(1-abs(sign(id4-56)))) as id4, from mytable group by years ```
Use a characteristic or delta function: ``` DECLARE @look_for AS int SET @look_for = 1 SELECT SUM(CASE WHEN id1 = @look_for THEN 1 ELSE 0 END) AS id1_count ,SUM(CASE WHEN id2 = @look_for THEN 1 ELSE 0 END) AS id2_count ,SUM(CASE WHEN id3 = @look_for THEN 1 ELSE 0 END) AS id3_count ,SUM(CASE WHEN id4 = @lo...
Summary query from several fields in SQL
[ "", "sql", "mysql", "count", "" ]
Does anyone know of a library or set of classes for splines - specifically b-splines and NURBS (optional). A fast, efficient b-spline library would be so useful for me at the moment.
1.) For B Splines - You should check Numerical Recipes in C (there is book for that and it is also available online for reference) 2.) Also check: [sourceforge.net/projects/einspline/](http://sourceforge.net/projects/einspline/) & [this](https://www.gnu.org/software/gsl/doc/html/bspline.html) -AD
I know I'm answering months after this question was asked, but for others who might be searching for a similar answer, I'll point out [openNURBS](http://www.opennurbs.org/). OpenNURBS also happens to be the library used in the modeling package [Rhinoceros](http://www.rhino3d.com/). It's a very complete library and it'...
Spline, B-Spline and NURBS C++ library
[ "", "c++", "graphics", "" ]
I asked [how to render a UserControl's HTML](https://stackoverflow.com/questions/288409/how-do-i-get-the-html-output-of-a-usercontrol-in-net-c) and got the code working for a dynamically generated UserControl. Now I'm trying to use LoadControl to load a previously generated Control and spit out its HTML, but it's givi...
Alternatively you could disable the ServerForm/Event-validation on the page that is rendering the control to a string. The following example illustrates how to do this. ``` public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string rawHtml = Rend...
This is a dirty solution I used for the moment (get it working then get it right, right?). I had already created a new class that inherits the UserControl class and from which all other "UserControls" I created were derived. I called it formPartial (nod to Rails), and this is going inside the public string renderMyHTM...
UserControl's RenderControl is asking for a form tag in (C# .NET)
[ "", "c#", "html", ".net", "user-controls", "" ]
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, `topDict[word1][word2][word3]` returns the number of times these words appear in the text, `topDict[word1][word2]` returns...
Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record: ...
Use tuples. Tuples can be keys to dictionaries, so you don't need to nest dictionaries. ``` d = {} d[ word1, word2, word3 ] = 1 ``` Also as a plus, you could use defaultdict * so that elements that don't have entries always return 0 * and so that u can say `d[w1,w2,w3] += 1` without checking if the key already exi...
Memory Efficient Alternatives to Python Dictionaries
[ "", "python", "memory", "data-structures", "" ]
In javascript, I've got a block of HTML like this: ``` <h2>{title}</h2> <p><a href="{url}">{content}</a></p> ``` And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like: ``` ['title', 'url', 'content'] ``` I've gotten as far as: ``` var pattern = new RegExp("\{[a-zA...
You need to create a pattern with the global flag: ``` var pattern = new RegExp("\{[a-zA-Z]+\}", "g"); ``` or: ``` var pattern = /\{[a-zA-Z]+\}/g; ``` Then you can call the match() method on your string to get a list of matches: ``` var matches = "{Sample} bob {text}".match(pattern); ```
I think you want: ``` var pattern = new RegExp("\{[a-zA-Z]+\}+", "g"); ``` The second option is a flag telling it to search the entire string and return all matches. See: <http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/> for more details.
RegExp to match words wrapped in braces
[ "", "javascript", "regex", "arrays", "templates", "match", "" ]
I am trying to add a "title" element but am getting a NO\_MODIFICATION\_ALLOWED\_ERR error... ``` private static void saveDoc(String f) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); // c...
Not sure if that's the reason, but check if your DOM implementation validates all the changes to the DOM. Because in you code, ``` nextNode.appendChild(doc.createTextNode("title")); ``` will attempt to create a text node as the child of `map` element and DITA Map doesn't allow that. Instead, try ``` Element title = ...
Where is the original document coming from? That's the cause of the issue - the code that's reading in the document is constructing a read-only document. Without knowing how you're reading it in, it's pretty hard to work out how to change that. I just did a quick test on Windows with JDK 1.4.2-11, and I can confirm t...
How to add an xml element in Java 1.4
[ "", "java", "jdk1.4", "" ]
I know it's probably not the right way to structure a database but does the database perform faster if the data is put in one huge table instead of breaking it up logically in other tables? I want to design and create the database properly using keys to create relational integrity across tables but when quering, is JO...
So many other facets affect the answer to your question. What is the size of the table? width? how many rows? What is usage pattern? Are there different usage patterns for different subsets of the columns in the table? (i.e., are two columns hit 1000 times per second, and the other 50 columns only hit once or twice a d...
It depends on the dbms flavor and your actual data, of course. But *generally* more smaller (narrower) tables are faster than fewer larger (wider) tables.
Is it better for faster access to split tables and JOIN in a SQL database or leave a few monolithic tables?
[ "", "sql", "database-design", "optimization", "" ]
thanks in advance for your help. I am wondering if there is a (design) pattern that can be applied to this problem. **I am looking to parse, process, and extract out values from text files with similar, but differing formats.** More specifically, I am building a processing engine that accepts Online Poker Hand Histor...
This sounds like a candidate for the Strategy pattern. An example in C# can be found [here](http://www.dofactory.com/Patterns/PatternStrategy.aspx) and another one [here](http://www.c-sharpcorner.com/UploadFile/rmcochran/strategyPattern08072006095804AM/strategyPattern.aspx). A brief description is available on [Wikiped...
The "Provider" pattern is the one you're looking for... it is what is used in ADO.Net. Each database vendor has a separate data "Provider" that "knows" how to read the data from it's specific DB vendors product, but delivers it in a standard format (interface) to downstream systems... You will write a small "Provider" ...
Design Pattern: Parsing similar, but differing schemas in text files
[ "", "c#", ".net", "design-patterns", "architecture", "poker", "" ]
You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal? If so, how?
No, there isn't. You have to use the L prefix (or a macro such as \_T() with VC++ that expands to L anyway when compiled for Unicode).
The new C++0x Standard defines another way of doing this: <http://en.wikipedia.org/wiki/C%2B%2B0x#New_string_literals>
How to use wide string literals in c++ without putting L in front of each one
[ "", "c++", "string", "literals", "" ]
I found several controlsets for that nice looking ribbons (DotNetBar, DivElements, ...), but all require a license for at least 100 USD. Is there a free controlset that looks quite as nice as the commericial ones?
You can download the Microsoft WPF Ribbon Control through the Office Developer UI Licence. It was meant to be released last week. <http://windowsclient.net/wpf/wpf35/wpf-35sp1-ribbon-walkthrough.aspx> I'll see if i can dig out a download link. Edit: Think this is what your looking for [Office Fluent User Interface...
Might want to take a look at <http://arstechnica.com/journals/linux.ars/2007/08/30/mono-developer-brings-the-ribbon-interface-to-linux> It's for mono, but might be worth a look.
Is there a way to create an desktop application with that office2007 toolbar for free?
[ "", "c#", ".net", "ribbon", "" ]
I've long toyed with the idea of some kind of auto-cleanup page that performs routine maintenence tasks and is called out of scope of the current page execution by means of calling a 1x1 pixel gif with the asp.net page as the src parameter. One thing I've never really decided on, however, is how to handle the timing of...
I have come across this situation many times and I generally just end up using task scheduler to just call the page, that way it is consistent and reliable. The problem with relying on a page to be called is that you have to be sure that there will always be requests to your page. If you can guarantee that, then just s...
It sounds like you might want to use the global.asax file instead - assuming you want something to happen every Nth time. For example, if you wanted to do something for every 5th visitor to your site, you could do something along the lines of, ``` void Application_Start(object sender, EventArgs e) { // Code that ...
ASP.NET auto-executing page
[ "", "c#", "asp.net", "" ]
Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions? I.e. I want to set a timeout on blocking socket in boost asio? socket.read\_some(boost::asio::buffer(pData, maxSize), error\_); Example: I want to read some from the socket, but I want to throw an erro...
Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via `setsocktopt()`. I don't know if `boost::asio` provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable. ...
TL;DR ``` socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); ``` FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I'll add this info right here in one of the first occurrences of this question. Everybody t...
How to set a timeout on blocking sockets in boost asio?
[ "", "c++", "sockets", "boost", "boost-asio", "" ]
I am calling an executable in C#. When the executable runs, it writes out to the console so the C# code is getting the console output and writing it to a text file. When the crash happens a couple of things occur. 1) The output of the text file is not completely written out. 2) The executable process seems to run comp...
Try adding a flush after the tw.Write. That should cause the complete output up to the point of failure to be produced, which may include error messages from the executable (if that's what is crashing?)
What is the crash that you are getting? A .Net exception? That the file is not written completely could be because you do not flush the stream into the file and then close it. I think it might be a problem that you use the same stream for both standard out and error out messages. This might lead to concurrency proble...
Calling executable using Process crashes intermittently
[ "", "c#", "executable", "" ]
``` SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value FROM prodtree_element pe LEFT JOIN prodtree_link pl ON pe.prodtree_element_id = pl.to_prodtree_node_id LEFT JOIN line li ON pe.line_code = li.line_code INNER JOIN attribute_values av ON ...
``` INNER JOIN attribute_values av ON av.attribute_definition_id = #statusCode# LEFT JOIN attribute_values av2 ON pe.prodtree_element_id = av.prodtree_element_id ``` This is the problem. There is a cross join between pe and av, followed by an outer join onto the cross join. You're lucky it only takes 30 mins ...
Without knowing the DDL its very hard to test. 30-50K rows should still take only a few seconds. Try switching the where clause ordering. You should probably have this implemented ``` INNER JOIN attribute_values av ON av.attribute_definition_id = #statusCode# ``` in the where clause.
Need to speed up this query in SQL Server
[ "", "sql", "sql-server", "performance", "t-sql", "outer-join", "" ]
I am doing some calculations that require a large array to be initialized. The maximum size of the array determines the maximum size of the problem I can solve. Is there a way to programmatically determine how much memory is available for say, the biggest array of bytes possible? Thanks
Well, relying on a single huge array has a range of associated issues - memory fragmentation, contiguous blocks, the limit on the maximum object size, etc. If you need a lot of data, I would recommend creating a class that simulates a large array using lots of smaller (but still large) arrays, each of fixed size - i.e....
In order to ensure you have enough free memory you could use a [MemoryFailPoint](http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx). If the memory cannot be allocated, then an [InsufficientMemoryException](http://msdn.microsoft.com/en-us/library/system.insufficientmemoryexception.aspx) will be...
Finding how much memory I can allocate for an array in C#
[ "", "c#", "memory", "" ]
In my quest to learn javascript (which seems to be my latest source of questions for SO these days) i've found this API for drawing <http://www.c-point.com/javascript_vector_draw.htm> Meanwhile I've been making some experiments with graphics, which tend to be heavy on the amount of stuff to draw. This guy is drawing w...
for vector drawing, libraries like [Raphael](http://raphaeljs.com/) provide a consistent API over SVG and VML. for raster drawing, you can use <canvas> for browsers that support canvas. for IE, you would default to DIVS or have your drawing API use silverlight if it's available. Note that for efficiency, divs should ...
Not, it is the worst method, elaborated before there was SVG or canvas elements... It would be very heavy on memory and very slow. An amusing, interesting hack, but not really usable in the real world. Beside the libraries mentioned in the other thread, relying on canvas/SVG/VML, I saw games made with sprites, ie. som...
Drawing in javascript with divs
[ "", "javascript", "drawing", "html", "" ]
I have got this error when using Enterprise Library 3.1 May 2007 version. We are developing a product and have a common lib directory beneath the Subversion Trunk directory <>\Trunk\Lib\ into which we put all the third party DLLs. Inside this we have Microsoft\EnterpriseLibrary\v3.1 in which we have copied all the dll...
I used to get that when I developed against the signed version of the dll and deployed where only the unsigned version was available. Also, [fuslogvw.exe](http://msdn.microsoft.com/en-us/library/e74a18c4(VS.71).aspx). EVERY. TIME.
I assume the error lies in the developer having compiled the code against the unsigned source code compilation he has. Make sure he adds the reference to the signed DLLs before compiling his code. Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, **PublicKeyToken=null** should be somethin...
System.IO.FileLoadException
[ "", "c#", ".net", "enterprise-library", "fileloadexception", "" ]
Edit: How to return/serve a file from a python controller (back end) over a web server, with the file\_name? as suggested by @JV
Fully supported in CherryPy using ``` from cherrypy.lib.static import serve_file ``` As documented in the [CherryPy docs - FileDownload](http://www.cherrypy.org/wiki/FileDownload): ``` import glob import os.path import cherrypy from cherrypy.lib.static import serve_file class Root: def index(self, directory="...
You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it. Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle. It is not recommended to pass the actual data as file...
Return file from python module
[ "", "python", "file", "mime-types", "download", "" ]
I often find myself using Integers to represent values in different "spaces". For example... ``` int arrayIndex; int usersAge; int daysToChristmas; ``` Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a hel...
You could try BOOST\_STRONG\_TYPEDEF. From `boost/strong_typedef.hpp`: ``` // macro used to implement a strong typedef. strong typedef // guarentees that two types are distinguised even though the // share the same underlying implementation. typedef does not create // a new type. BOOST_STRONG_TYPEDEF(T, D) creates ...
Boost does in fact have a library specifically for this type of thing! Check out the [Boost.Units library](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_units.html).
Multiple Integer-type classes in C++
[ "", "c++", "class", "boost", "templates", "" ]
Seeing as C# can't `switch` on a Type (which I gather wasn't added as a special case because `is` relationships mean that more than one distinct `case` might apply), is there a better way to simulate switching on type other than this? ``` void Foo(object o) { if (o is A) { ((A)o).Hop(); } else ...
Switching on types is definitely lacking in C# (**UPDATE: in C#7 / VS 2017 switching on types is supported - [see Zachary Yates's answer](https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type/299001#299001)**). In order to do this without a large if/else if/else statement,...
[With C# 7](https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/), which shipped with Visual Studio 2017 (Release 15.\*), you are able to use Types in `case` statements (pattern matching): ``` switch(shape) { case Circle c: WriteLine($"circle with radius {c.Radius}"); break; ...
Is there a better alternative than this to 'switch on type'?
[ "", "c#", "switch-statement", "system.type", "" ]
I am having a lot of trouble finding good information on how to call a standard SOAP/WSDL web service with Android. All I've been able to find are either very convoluted documents and references to "kSoap2" and then some bit about parsing it all manually with [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML). OK, ...
Android does not provide any sort of SOAP library. You can either write your own, or use something like [kSOAP 2](http://ksoap2.sourceforge.net/). As you note, others have been able to compile and use kSOAP2 in their own projects, but I haven't had to. Google has shown, to date, little interest in adding a SOAP librar...
`org.apache.http.impl.client.DefaultHttpClient` comes in the Android SDK by default. That'll get you connected to the WSDL. ``` HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet("http://www.example.com/" + URL); HttpResponse response = htt...
How to call a SOAP web service on Android
[ "", "java", "android", "web-services", "soap", "wsdl", "" ]
I am trying to merge several XML files in a single XDocument object. Merge does not exist in XDocument object. I miss this. Has anyone already implemented a Merge extension method for XDocument, or something similar ?
I tried a bit myself : ``` var MyDoc = XDocument.Load("File1.xml"); MyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements()); ``` I dont know whether it is good or bad, but it works fine to me :-)
Being pragmatic, `XDocument` vs `XmLDocument` isn't all-or-nothing (unless you are on Silverlight) - so if `XmlDoucument` does something you need, and `XDocument` doesn't, then perhaps use `XmlDocument` (with `ImportNode` etc). That said, even with `XDocument`, you could presumably use `XNode.ReadFrom` to import each,...
Merge XML files in a XDocument
[ "", "c#", "xml", "linq-to-xml", "" ]
What would be the benefit of using decimal.compare vs. just using a > or < to compare to variables?
In the CLI, decimal is not a native type like Int32, String, and others are. I am guessing that C# uses Compare behind the scenes to implement the comparison operators. Also, you can pass Compare as a parameter to a sort routine without creating a delegate, reducing the method-nesting levels inside the sort. That’s a...
For one thing it makes it really easier to build a [`Comparison<decimal>`](http://msdn.microsoft.com/en-us/library/tfakywbh.aspx) delegate instance: ``` Comparison<decimal> foo = decimal.Compare; ``` This is handy to pass into things which take arbitrary comparison delegates. It may also be useful if you're using a ...
C# decimal.compare vs. > or <
[ "", "c#", "comparison", "" ]
The documentation of the Python [`readline`](http://www.python.org/doc/2.5.2/lib/module-readline.html) module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using: ``` $ uname -a Darwin greg.local 8.11.1 Darwin Kernel...
Have you tried to install the `py-readline` (or `py25-readline` for Python 2.5) port? Also, in the snippet above, you are NOT using the MacPort python, but rather the Apple Python. The MacPort version should be located in the `/opt/local` directory structure. You should check your path.
Try `rlwrap`. It should work with any version of python and in general any shell. Install via `brew install rlwrap` on Mac OS X usage as `rlwrap python`. It stores history as well.
Why is the Python readline module not available on OS X?
[ "", "python", "macos", "readline", "" ]
Having recently introduced an overload of a method the application started to fail. Finally tracking it down, the new method is being called where I did not expect it to be. We had ``` setValue( const std::wstring& name, const std::wstring& value ); std::wstring avalue( func() ); setValue( L"string", avalue ); std::...
First, the cause of this issue: C++ Standard [`[over.ics.rank]/2.1`](http://eel.is/c++draft/over.ics.rank#2.1)1 defines an order for conversion sequences. It says that a user defined conversion sequence is worse than a standard conversion sequence. What happens in your case is that the string literal undergoes a boolea...
L"" is a pointer to a wide character string. The compiler believes that the conversion to a bool takes precedence over a conversion to a std::wstring. To fix the problem, introduce a new setValue: ``` void setValue(std::wstring const& name, const wchar_t * value); ```
Why does the compiler choose bool over string for implicit typecast of L""?
[ "", "c++", "visual-c++", "implicit", "explicit", "" ]
I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts....
The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path. You can also extend the search path by adding .pth files somewhere in your path. See <https://docs.python.org/2/install/#modifying-python-s-search-path> for more details Oh, and python 2.6/3.0 adds support for P...
If your reusable files are packaged (that is, they include an `__init__.py` file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just ``` import Foo ``` [This question](https://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder#279287) provides a...
In Python, how can I efficiently manage references between script files?
[ "", "python", "scripting", "metadata", "" ]
I have **CustomForm** inherited from **Form** which implements a boolean property named **Prop**. The forms I'll be using will inherit from **CustomForm**. This property will do some painting and changes (if it's enabled) to the form. However, this is not working as it should, the VS IDE designed is not being refresh t...
Someone else helped me out and to fix the problem. I just call **ReCreateHandle()** when the user sets **EnableSkin** to false. Problem solved :) Thanks everyone though :)
All you need to do is add this Attribute to your property: ``` [Description("Description of your property."), NotifyParentProperty(true), RefreshProperties(RefreshProperties.Repaint)] ``` That will cause the IDE to repaint when the value is changed.
Question How to invalidate/refresh the VS IDE designer for C#?
[ "", "c#", "visual-studio-2008", "ide", "refresh", "designer", "" ]
I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php. Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else)
I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for. You can check it out and read more at the [wt homepage](http://www.webtoolkit.eu/wt...
Another option is the Cgicc library which appears to be mature (currently at version 3.x): <http://www.gnu.org/software/cgicc/>
Which C++ Library for CGI Programming?
[ "", "c++", "cgi", "" ]
Is there an API to access Subversion from C#?
[**Svn.NET**](http://www.pumacode.org/projects/svndotnet/) is a continuation (fork) of [SubversionSharp](http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html) mentioned in [CMS](https://stackoverflow.com/users/5445/cms)'s [answer](https://stackoverflow.com/questions/287862/subversion-acce...
[SharpSvn](http://sharpsvn.net/) is a new Subversion wrapper library for .Net/C# that hides all interopand memory management for you and includes a staticly compiled Subversion library for easy integration. It is probably the only Subversion binding designed to perform well in a multithreaded environment. SharpSvn is ...
Is there a Subversion API that can be used to program against in .NET
[ "", "c#", ".net", "svn", "" ]
How do I check if a string represents a numeric value in Python? ``` def is_number(s): try: float(s) return True except ValueError: return False ``` The above works, but it seems clunky. --- If what you are testing comes from user input, it is *still* a string *even if it represents*...
> Which, not only is ugly and slow I'd dispute both. A regex or other string parsing method would be uglier and slower. I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an e...
For non-negative (unsigned) integers only, use [`isdigit()`](https://docs.python.org/3/library/stdtypes.html#str.isdigit "str.isdigit"): ``` >>> a = "03523" >>> a.isdigit() True >>> b = "963spam" >>> b.isdigit() False ``` --- Documentation for `isdigit()`: [Python2](https://docs.python.org/2/library/stdtypes.html#st...
How do I check if a string represents a number (float or int)?
[ "", "python", "casting", "floating-point", "type-conversion", "" ]
I have a huge dictionary of blank values in a variable called current like so: ``` struct movieuser {blah blah blah} Dictionary<movieuser, float> questions = new Dictionary<movieuser, float>(); ``` So I am looping through this dictionary and need to fill in the "answers", like so: ``` for(var k = questions.Keys.GetE...
Matt's answer, getting the keys first, separately is the right way to go. Yes, there'll be some redundancy - but it will work. I'd take a working program which is easy to debug and maintain over an efficient program which either won't work or is hard to maintain any day. Don't forget that if you make `MovieUser` a ref...
Is there any reason you can't just populate the dictionary with both keys and values at the same time? ``` foreach(var key in someListOfKeys) { questions.Add(key, retrieveGuess(key.userID, key.movieID); } ```
Hopefully simple question about modifying dictionaries in C#
[ "", "c#", ".net", "dictionary", "" ]
In Visual c# Express Edition, is it possible to make some (but not all) items in a ListBox bold? I can't find any sort of option for this in the API.
You need to change listbox's DrawMode to DrawMode.OwnerDrawFixed. Check out these articles on msdn: [DrawMode Enumeration](http://msdn.microsoft.com/en-us/library/system.windows.forms.drawmode.aspx) [ListBox.DrawItem Event](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.drawitem.aspx) [Graph...
To add to Mindaugas Mozūras's solution, I had a problem where my `e.Bounds` wasn't large enough and text was getting cut off. To solve this problem (thanks to a post [here](http://arstechnica.com/civis/viewtopic.php?f=20&t=314206)), you override the `OnMeasureItem` event and changes your DrawMode to `DrawMode.OwnerDraw...
How can I make some items in a ListBox bold?
[ "", "c#", ".net", "visual-studio", "listbox", "" ]
I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another. I've seen a model of testing for ``` $b.parents('nodename').length>0 ``` Which is fantastic when you only need to check if an element is a child of any node by that name. But what ab...
In [jQuery ancestors using jQuery objects](https://stackoverflow.com/questions/245241/jquery-ancestors-using-jquery-objects#245266) I suggested ``` if ($(obj1).parents().index($(obj2)) >= 0) { // obj1 is a descendant of obj2 } ```
``` a.contains(b) ``` This is a pure JavaScript solution using [Node.contains](https://developer.mozilla.org/en-US/docs/DOM/Node.contains). The function is inclusive, `a.contains(a)` evaluates to true. There's an edge case in IE9: if `b` is a text node, `contains` will always return false.
Testing objects for ancestor/descendent relationship in JavaScript or Jquery
[ "", "javascript", "jquery", "dom", "" ]
I've got an `RSA` private key in `PEM` format, is there a straight forward way to read that from .NET and instantiate an `RSACryptoServiceProvider` to decrypt data encrypted with the corresponding public key?
### Update 03/03/2021 .NET 5 now supports this out of the box. To try the code snippet below, generate a keypair and encrypt some text at <http://travistidwell.com/jsencrypt/demo/> ``` var privateKey = @"-----BEGIN RSA PRIVATE KEY----- { the full PEM private key } -----END RSA PRIVATE KEY-----"; var rsa = RSA.Crea...
With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone." However, as alluded to above by Simone, you can simply combine the PEM of the private key (\*.key) and the certificate file using that key (\*.cr...
How to read a PEM RSA private key from .NET
[ "", "c#", ".net", "cryptography", "rsa", "" ]
I have an application that is using Windows Authentication and a SqlRoleProvider for user authentication and role management respectively. It is working fine with my test users that I have added to the database as defaults. The application requires users to login (using Windows credentials) and then be able to use this...
I was able to locate the solution after digging and playing around a bit more. I added the following code to my Global.asax file and it is accomplishing what I am hoping for. ``` protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e) { if (!Roles.IsUserInRole(e.Identit...
I would add the default role to the user directly after the user was fetched. Something like such: ``` user = Membership.GetUser() if (user != null) { // default role string[] defaultRoles = {"MyRole"}; AddUsersToRoles(user, defaultRoles); } ```
How do I set a default role for a new user using Windows Authentication with the SqlRoleProvider?
[ "", "c#", "asp.net", "security", "windows-authentication", "" ]
What is the difference and what should go in each? If I understand the theory correctly, the query optimizer should be able to use both interchangeably. (Note: this question is *not* a duplicate of [Explicit vs Implicit SQL Joins](https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins). The answer m...
They are not the same thing. Consider these queries: ``` SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID WHERE Orders.ID = 12345 ``` and ``` SELECT * FROM Orders LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID AND Orders.ID = 12345 ``` The first will return an order and its line...
* Does **not** matter for **inner** joins * **Does** matter for **outer** joins a. **`WHERE` clause**: Records will be ***filtered after join*** has taken place. b. **`ON` clause**: Records, from the right table, will be ***filtered before joining***. This may end up as null in the result (since OUTER join). **E...
SQL JOIN: what is the difference between WHERE clause and ON clause?
[ "", "sql", "join", "where-clause", "on-clause", "" ]
I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after `32`. For example: ``` for(var j = 0; j < 64; j++) { mask = mask << 1; console.log(mask); } ``` This prints value from `0` to `1073741824` but then rounds of and starts printing `0`.
"In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardwa...
JavaScript stores all its numbers as 64 bit initally, but as soon as you start using bitwise operators the interpreter converts the number to a 32 bit representation.. Bitwise operators are a bit hacky in JS and so annoyingly you will probably have to do something a bit more clever, like write your own 64 bit function...
JavaScript: Bitwise shift of long long number
[ "", "javascript", "" ]
How can I use a database and PHP sessions to store a user's shopping cart? I am using CodeIgniter, if that helps. Example code would also be nice.
I would write an add to basket function like this: ``` function AddToBasket(){ if(is_numeric($_GET["ID"])){ $ProductID=(int)$_GET["ID"]; $_SESSION["Basket"][]=$ProductID; $sOut.=ShowBasketDetail(); return $sOut; } } ``` In this shopping basket function we save Product IDs in a...
I would recommend that you look at [the CodeIgnitor Session Class](http://codeigniter.com/user_guide/libraries/sessions.html). Additionally, you could look at [Chris Shiflett's discussion](http://shiflett.org/articles/storing-sessions-in-a-database) on this topic.
How can I use a database and PHP sessions to store a user's shopping cart?
[ "", "php", "codeigniter", "" ]
I'm trying to get information like OS version, hard disk space, disk space available, and installed RAM on a Linux system in C++. I know I can use `system()` to run different Linux commands and capture their output (which is what I'm currently doing) but I was wondering if there's a better way? Is there something in th...
If you are using \*nix commands via system. Then do man scroll to the bottom of the man page and it will usually show you what relevant C system calls are related. ``` Example: man uname: SEE ALSO uname(2), getdomainname(2), gethostname(2) Explanation of numbers: (1): User UNIX Command (2): Unix and C syst...
There is nothing in the C++ Standard library for these purposes. The library you could use is `libhal`, which abstracts the view of programs to the hardware, collecting various informations from `/proc`, `/sys` and others. [HAL](http://www.freedesktop.org/wiki/Software/hal), scroll down, there seems to be an unofficial...
How do I read system information in C++?
[ "", "c++", "linux", "operating-system", "system", "" ]
In answering this question (<https://stackoverflow.com/questions/352317/c-coding-question#352327>), it got me wondering... Is there any danger in regarding a static class as being equivalent to a non-static class instatiation that implements the singleton pattern?
The only thing that seems immediately apparent to me is that a static class is basically just a collection of scoped functions (explicitly avoiding "methods" here) and a singleton is still something you can instantiate, even if you can only have 1. 1 > 0. You can pass a singleton as an argument to something that expec...
In many ways, a static class and a singleton are similar. One big difference is that a singleton might implement some interfaces, which isn't possible with a static class. For example, `Comparer<T>.Default` / `EqualityComparer<T>.Default` provide (via the interface) the ability to use the item in sorting / dictionary u...
Static classes in c#
[ "", "c#", "design-patterns", "static", "singleton", "" ]
Good day, We just converted our web application .NET 1.1 to .NET 2.0. We have a major problem sending emails. We are using distribution group (eg: WebDeveloppersGroup) to send emails to all the developpers in the company. These groups don't end with '@ something.com'. These groups are created in Lotus Notes, and we c...
I believe you can interact with Lotus Notes from .net and query it to get you the xyz@xyz.xyz addresses in the group. I'm not very familiar with it but you could start here: * <http://www.codeproject.com/KB/cs/lotusnoteintegrator.aspx> * [IBM Lotus Notes and .NET](http://www.ibm.com/developerworks/lotus/library/domino...
You can give the groups a full internet e-mail address. Ask your admin if you don't know how.
.NET 2.0: Sending email to a distribution group
[ "", "c#", "email", ".net-2.0", "" ]
I need to use a datetime.strptime on the text which looks like follows. "Some Random text of undetermined length Jan 28, 1986" how do i do this?
Using the ending 3 words, no need for regexps (using the `time` module): ``` >>> import time >>> a="Some Random text of undetermined length Jan 28, 1986" >>> datetuple = a.rsplit(" ",3)[-3:] >>> datetuple ['Jan', '28,', '1986'] >>> time.strptime(' '.join(datetuple),"%b %d, %Y") time.struct_time(tm_year=1986, tm_mon=1,...
You may find [this](https://stackoverflow.com/questions/285408/python-module-to-extract-probable-dates-from-strings) question useful. I'll give the answer I gave there, which is to use the [dateutil](http://labix.org/python-dateutil) module. This accepts a fuzzy parameter which will ignore any text that doesn't look li...
How do I strptime from a pattern like this?
[ "", "python", "regex", "datetime", "" ]
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as man...
### Python <2.7 ``` "%.15g" % f ``` Or in Python 3.0: ``` format(f, ".15g") ``` ### Python 2.7+, 3.2+ Just pass the float to `Decimal` constructor directly, like this: ``` from decimal import Decimal Decimal(f) ```
I suggest this ``` >>> a = 2.111111 >>> a 2.1111110000000002 >>> str(a) '2.111111' >>> decimal.Decimal(str(a)) Decimal('2.111111') ```
Python float to Decimal conversion
[ "", "python", "decimal", "" ]
I'm using .NET 2.0, and a recent code change has invalidated my previous Assert.AreEqual call (which compared two strings of XML). Only one element of the XML is actually different in the new codebase, so my hope is that a comparison of all the other elements will give me the result I want. The comparison needs to be d...
It really depends on what you want to check as "differences". Right now, we're using Microsoft XmlDiff: <http://msdn.microsoft.com/en-us/library/aa302294.aspx>
You might find it's less fragile to parse the XML into an XmlDocument and base your Assert calls on XPath Query. Here are some helper assertion methods that I use frequently. Each one takes a XPathNavigator, which you can obtain by calling CreateNavigator() on the XmlDocument or on any node retrieved from the document....
What is the best way to compare XML files for equality?
[ "", "c#", ".net", "xml", "unit-testing", "comparison", "" ]
I am using a JSP bean and when I do an assignment to a new object, it gets over-written on a submit to the previous object. ``` <jsp:useBean id="base" class="com.example.StandardBase" scope="session" /> ... //base object id = 396 base = new Base() //base object id = 1000 ``` and on a resubmit of the page I get ``` ...
I'm not completely sure, but I think `base = new Base()` does not update the reference stored in the session scope. Therefore, the bean you created with the initial `<jsp:useBean/>` is still around while the one you create manually, and then updated, isn't. Get rid of `base = new Base()` and you should be fine. If yo...
You're not supposed to new the bean yourself. Let JSP do that for you
Using a jsp bean in a session
[ "", "java", "jsp", "javabeans", "" ]
When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it. For example, when writing this in vim ``` for i in range(10): # ``` the # does not stay there where I entered ...
I found an answer here <http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash> It seems that the vim smartindent option is the cause of the problem. The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of ...
@PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent. I wo...
How to configure vim to not put comments at the beginning of lines while editing python files
[ "", "python", "vim", "" ]
Being fairly new to JavaScript, I'm unable to discern when to use each of these. Can anyone help clarify this for me?
If your situation requires the use of a regular expression, use the `search()` method, otherwise; the `indexOf()` method is more performant.
[`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) is for plain substrings, [`search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) is for regular expressions.
What is the difference between indexOf() and search()?
[ "", "javascript", "string", "" ]
We have recently been faced with the problem of porting our C++ framework to an ARM platform running uClinux where the only vendor supported compiler is GCC 2.95.3. The problem we have run into is that exceptions are extremely unreliable causing everything from not being caught at all to being caught by an unrelated th...
Generally you end up with code like this for objects on the stack: ``` MyClassWithNoThrowConstructor foo; if (foo.init(bar, baz, etc) != 0) { // error-handling code } else { // phew, we got away with it. Now for the next object... } ``` And this for objects on the heap. I assume you override global operator n...
You could use a flag to keep track of whether the constructor failed. You might already have a member variable that's only valid if the constructor succeeds, e.g. ``` class MyClass { public: MyClass() : m_resource(NULL) { m_resource = GetResource(); } bool IsValid() const { return m...
Exception elimination in C++ constructors
[ "", "c++", "exception", "" ]
Hiya - been pointed at you guys by a friend of mine. I have an MDI application (C#, Winforms, .NET 2.0, VS2005, DevExpress 8.2) and one of my forms is behaving very strangely - not repainting itself properly where it overlaps with another instance of the same form class. The forms contain a custom control (which cont...
Ah ha! I was changing the FormBorderStyle in code before showing the form. I removed that line and the problem went away... That'll do for me. :-)
Yes, that would do it. Changing the FormBorderStyle requires Windows Forms to recreate the window from scratch, now using different style flags in the CreateWindowEx() call. That would make it completely forget about the parent you set with the SetParent() P/Invoke. There are lots of other properties that causes this t...
MDI Child refresh/repaint problems (C#, Winforms, .NET 2.0, VS2005, DevExpress 8.2)
[ "", "c#", "winforms", "visual-studio-2005", ".net-2.0", "" ]
I need to match a string holiding html using a regex to pull out all the nested spans, I assume I assume there is a way to do this using a regex but have had no success all morning. So for a sample input string of ``` <DIV id=c445c9c2-a02e-4cec-b254-c134adfa4192 style="BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #00...
Try this: ``` @"(?is)<SPAN\b[^>]*>\s*(<SPAN\b[^>]*>.*?</SPAN>)\s*</SPAN>" ``` This is basically the same as PhiLho's regex, except it permits whitespace between the tags at either end. I also had to add the SingleLine/DOTALL modifier to accomodate line separators within the matched text. I don't know if either of tho...
Once again [use an HTML parser](http://www.developer.com/net/csharp/article.php/2230091) to walk the DOM: regexs will never be robust enough to do this.
Using Lookahead to match a string using a regular expression
[ "", "c#", "html", "regex", "" ]
I'm using reflection to loop through a `Type`'s properties and set certain types to their default. Now, I could do a switch on the type and set the `default(Type)` explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?
* In case of a value type use [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) and it should work fine. * When using reference type just return null ``` public static object GetDefault(Type type) { if(type.IsValueType) { return Activator.CreateInstanc...
Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with: ``` public object GetDefault(Type t) { return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null); } public T GetDefaultGeneric<T>() { return...
Programmatic equivalent of default(Type)
[ "", "c#", "reflection", "default", "" ]
I want a single number that represents the current date and time, like a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
### Timestamp in milliseconds To get the number of milliseconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time), call [`Date.now`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now): ``` Date.now() ``` Alternatively, use the unary operator `+` to call [`Date.protot...
I like this, because it is small: ``` +new Date ``` I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better: ``` Date.now() ```
How do I get a timestamp in JavaScript?
[ "", "javascript", "datetime", "timestamp", "date-arithmetic", "" ]
I'm wondering if this is a good design. I have a number of tables that require address information (e.g. street, post code/zip, country, fax, email). Sometimes the same address will be repeated multiple times. For example, an address may be stored against a supplier, and then on each purchase order sent to them. The su...
I actually use this as one of my interview questions. The following is a good place to start: ``` Addresses --------- AddressId (PK) Street1 ... (etc) ``` and ``` AddressTypes ------------ AddressTypeId AddressTypeName ``` and ``` UserAddresses (substitute "Company", "Account", whatever for Users) ------------- Us...
Option 2, without a doubt. Some important things to keep in mind: it's an important aspect of design to indicate to the users when addresses are linked to one another. I.e. corporate address being the same as shipping address; if they want to change the shipping address, do they want to change the corporate address to...
Is this a good way to model address information in a relational database?
[ "", "sql", "database-design", "rdbms", "" ]
I've been scanning through all the popular js libraries, but I can't find one that has a width function for a DOM element that actually accounts for quirks mode in Internet Explorer. The issue is that padding and borders don't get counted in the the width when quirks mode is engaged. As far as I can tell this happens w...
@1 ``` document.compatMode ``` "CSS1Compat" means "*standards mode*" and "BackCompat" means "*quirks mode*". @2 offsetWidth property of a HTML elements gives its width on screen, in pixels. ``` <div id="mydiv" style="width: 250px; padding-left: 1px; border: 2px black solid">hello</div> document.getElementById('my...
``` javascript:(function(){ var mode=document.compatmode,m;if(mode){ if(mode=='BackCompat')m='quirks'; else if(mode=='CSS1Compat')m='Standard'; else m='Almost Standard'; alert('The page is rendering in '+m+' mode.'); } })(); ``` that code will detect the mode for you. IE will a...
Width of an element accounting for quirks mode in javascript?
[ "", "javascript", "html", "css", "" ]
If I'm using `Long uuid = UUID.randomUUID().getMostSignificantBits()` how likely is it to get a collision. It cuts off the least significant bits, so there is a possibility that you run into a collision, right?
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html), the static method `UUID.randomUUID()` generates a type 4 UUID. This means that six bits are used for some type information and the remaining 122 bits are assigned randomly. The six non-random bits are distributed with four...
Raymond Chen has a really excellent blog post on this: [GUIDs are globally unique, but substrings of GUIDs aren't](https://devblogs.microsoft.com/oldnewthing/20080627-00/?p=21823)
Likelihood of collision using most significant bits of a UUID in Java
[ "", "java", "collision", "uuid", "" ]
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo. However, I'm looking through the *wxPython in Action* book and notice that "self" isn't used all the time. For example: ``` import wx class TextFrame(wx.Frame): def __init__(self): ...
You use `self.attribute` to reference an attribute of your current instance. You use `wx.Frame.__init__()` to reference a method of the parent class. You don't use `self` if you only reference a local name (variable) of the method (function) you are in. These are not "rules of thumb," because there are no exceptions...
In those instances, if you do not use `self` then you will create only a local variable of that name. In the first example, `panel` is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing `self` to the wx.Panel constructor associated ...
When is "self" required?
[ "", "python", "wxpython", "" ]
Can anyone think of a good solution for getting IOC into a console application? At the moment we are just using a static class with the following method: ``` public static T Resolve<T>() { return dependencyResolver.Resolve<T>(); } ``` I would like the experience to be seamless but cannot think of a way of achiev...
You will have to make a service locater call (`Resolve<T>()`) somewhere. The trick is to get it as out-of-the-way as possible. For console applications this bootstrapping happens in the `Main()` method. Do it there and minimize those Resolve calls elsewhere and you'll be great. For most dependencies, use constructor in...
Console applications do not have any limitation over a web or form application for IoC. You can use any of your choice (Spring, Ninject, Unity, etc.). Most of them are configurable with XML file outside your console application and some like Ninjector require a configuration inside your application.
IOC for a Console Application?
[ "", "c#", "dependency-injection", "inversion-of-control", "console-application", "" ]
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like: ``` my.namespace.ColorEnum = { RED : 0, GREEN : 1, BLUE : 2 } // later on if(currentColor == my.namespace.ColorEnum.RED) { // whatever } ``` Or is there some other way I can do this?
Since 1.8.5 it's possible to [seal and freeze the object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), so define the above as: ``` const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...}) ``` or ``` const DaysEnum = {"monday":1, "tuesday":2, "w...
This isn't much of an answer, but I'd say that works just fine, personally Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.
How can I guarantee that my enums definition doesn't change in JavaScript?
[ "", "javascript", "" ]
I have a set of classes, each one is a different [strategy](http://en.wikipedia.org/wiki/Strategy_pattern) to do the same work. ``` namespace BigCorp.SuperApp { public class BaseClass { } public class ClassA : BaseClass { } public class ClassB : BaseClass { } } ``` The choice of which strategy to use is c...
Since you know all classes will be coming from the same namespace, configure it once and use that: ``` <appConfig> <SuperAppConfig handlerNamespace="BigCorp.SuperApp"> <Handler class="ClassB" /> </SuperAppConfig> </appConfig> ``` **Edit:** I changed *name* to *class* to better denote the meaning of that a...
Either use the assembly-qualified-name, or get hold of the Assembly and use `Assembly.GetType(name)`. In this case, since you want the types in the config file, assembly-qualified is a valid way to go - but since you know all your types are in the same assembly: ``` Assembly assembly = typeof(SomeKnownType).Assembly; ...
Create an object knowing only the class name?
[ "", "c#", ".net", "reflection", "configuration", "" ]
How do I create the default for a generic in VB? in C# I can call: ``` T variable = default(T); ``` 1. How do I do this in VB? 2. If this just returns null (C#) or nothing (vb) then what happens to value types? 3. Is there a way to specify for a custom type what the default value is? For instance what if I want the d...
## Question 1: ``` Dim variable As T ' or ' Dim variable As T = Nothing ' or ' Dim variable As New T() ``` Notice that the latter only works if you specify the `Structure` constraint for the generic type (for reference types, `New T()` in VB does something else than `default(T)` in C#). ## Question 2: For value typ...
Actually folks the correct way of doing this is to cast the `null` (`Nothing`) type as your generic type as follows: ``` Dim tmpObj As T = CType(Nothing, T) ``` If you want to return the default value for the generic you simply return `CType(Nothing, T)`
Default value for generics
[ "", "c#", ".net", "vb.net", "generics", "" ]
[PySmell](http://github.com/orestis/pysmell/tree/master) seems like a good starting point. I think it should be possible, PySmell's `idehelper.py` does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing t...
EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose. You can grab it here: <http://github.com/orestis/pysmell/tree/master> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <http://code.goo...
This isn't exactly what you're looking for but it might be able to get you started: [Using TextMate with Django](http://code.djangoproject.com/wiki/TextMate) They appear to be somewhat Django specific but some snippets may assist with your needs. You also may be able to build on top of that with PySmells.
Is it possible to implement Python code-completion in TextMate?
[ "", "python", "autocomplete", "text-editor", "textmate", "" ]
MathWorks currently doesn't allow you to use `cout` from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, [mexPrintf, that they request you use instead](http://www.mathworks.com/support/tech-notes/1600/1605.html). After googling around a b...
You don't really want to overload `std::stringbuf`, you want to overload `std::streambuf` or `std::basic_streambuf` (if you want to support multiple character types), also you need to override the overflow method as well. But I also think you need to rethink your solution to your problem. `cout` is just an `ostream`,...
Shane, thanks very much for your help. Here's my final working implementation. ``` class mstream : public std::streambuf { public: protected: virtual std::streamsize xsputn(const char *s, std::streamsize n); virtual int overflow(int c = EOF); }; ``` ... ``` std::streamsize mstream::xsputn(const char *s, std::s...
Correctly over-loading a stringbuf to replace cout in a MATLAB mex file
[ "", "c++", "matlab", "cout", "mex", "stringbuffer", "" ]
When using Google Reader and browsing RSS entries in the "Expanded" view, entries will automatically be marked as 'read' once a certain percentage of the div is visible on the screen (difficult to tell what percentage has to be visible in the case of Google Reader). So, as I scroll down line-by-line, the javascript cod...
The real trick is to keep track of where the scrollbar is in the element containing your items. Here's some code I once whipped up to do it: <http://pastebin.com/f4a329cd9> You can see that as you scroll it changes focus. You just need to add more handler code to the function that handles each focus change. It works s...
I just came across this as I need the same thing, and it looks super useful: <http://www.appelsiini.net/projects/viewport>
Detecting divs as rendered in the window to implement Google-Reader-like auto-mark-as-read?
[ "", "javascript", "jquery", "scroll", "" ]
I see there are [a few](http://codeigniter.com/wiki/Category:Libraries::Authentication/). Which ones are maintained and easy to use? What are their pros and cons?
## Update (May 14, 2010): **It turns out, the russian developer Ilya Konyukhov picked up the gauntlet after reading this and created a new auth library for CI based on DX Auth, following the recommendations and requirements below.** **And the resulting [Tank Auth](http://konyukhov.com/soft/tank_auth/) is looking like...
Note that the "comprehensive listing" by Jens Roland doesn't include user roles. If you're interested in assigning different user roles (like admin/user or admin/editor/user), these libraries allow it: * Ion\_Auth (rewrite of Redux) * Redux * Backend Pro Tank\_Auth (#1 above in Jens's list) doesn't have user roles. I...
How should I choose an authentication library for CodeIgniter?
[ "", "php", "codeigniter", "authentication", "" ]
I have the string ``` a.b.c.d ``` I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner. (Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).
My 'idiomatic one-liner' for this is: ``` int count = StringUtils.countMatches("a.b.c.d", "."); ``` Why write it yourself when it's already in [commons lang](http://commons.apache.org/lang/)? Spring Framework's oneliner for this is: ``` int occurance = StringUtils.countOccurrencesOf("a.b.c.d", "."); ```
How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop. ``` int count = line.length() - line.replace(".", "").length(); ```
How do I count the number of occurrences of a char in a String?
[ "", "java", "string", "" ]
Say I have the following in my `models.py`: ``` class Company(models.Model): name = ... class Rate(models.Model): company = models.ForeignKey(Company) name = ... class Client(models.Model): name = ... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate) ``` I.e. there are multi...
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for [ModelChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield). So, provide a QuerySet to the field's `queryset` attribute. Depends on how your form ...
In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the `ModelForm.__init__` function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy. ``` class ClientForm(forms.ModelForm): def __init__...
How do I filter ForeignKey choices in a Django ModelForm?
[ "", "python", "django", "django-forms", "" ]
I'd like to check a few queries generated by ActiveRecord, but I don't need to actually run them. Is there a way to get at the query before it returns its result?
Both of these articles should help you do what you want. <http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing> <http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord>
i think it's buried in: ``` construct_finder_sql, ``` <http://groups.google.com/group/rubyonrails-talk/browse_frm/thread/38c492e3939dd9bf/?pli=1>
How can I see the SQL ActiveRecord generates?
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "" ]
I have a python script that has to launch a shell command for every file in a dir: ``` import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) ``` This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the pytho...
> subprocess: The `subprocess` module > allows you to spawn new processes, > connect to their input/output/error > pipes, and obtain their return codes. <http://docs.python.org/library/subprocess.html> Usage: ``` import subprocess process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) process.wait()...
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it: ``` import subprocess cmd = ['/run/myscript', '--arg', 'value'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: print line p.wait() print p.returncode ``` Or, if you don't care wh...
Launch a shell command with in a python script, wait for the termination and return to the script
[ "", "python", "subprocess", "popen", "os.execl", "" ]
I want a way to list files in a directory and putting a check box beside each one of them so I can select some of them and perform operations with each selected file, what's the best way to do this?
Drop a CheckedListBox control onto the form, then populate the contents using the DirectoryInfo and FileSystemInfo classes, like this: ``` System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("c:\\"); System.IO.FileSystemInfo[] files = di.GetFileSystemInfos(); checkedListBox1.Items.AddRange(files); ```
You can use checked list box control which is built-in winforms control (see links below): <http://www.functionx.com/vcsharp/controls/checkedlistbox1.htm> <http://msdn.microsoft.com/en-us/library/3ss05xx6.aspx>
Listing Files With CheckBoxes (C# / WinForms)
[ "", "c#", "winforms", "file", "list", "" ]
I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data... ``` System.Drawing.Image image = System.Drawing.Image.FromFile("filePath"); ``` Im quite new to image manipula...
If you get your image directly from file, you can use the following code to get size of original file in bytes. ``` var fileLength = new FileInfo(filePath).Length; ``` If you get your image from other source, like getting one bitmap and composing it with other image, like adding watermark you will have to calculate ...
If you don't have the original file, the file size is not clear as it depends on the image format and quality. So what you'd have to do is write the image to a stream (e.g. MemoryStream) and then use the stream's size.
How to get the file size of a "System.Drawing.Image"
[ "", "c#", "image", "image-processing", "image-manipulation", "" ]
What is the arrow operator (`->`) a synonym for?
The following two expressions are equivalent: ``` a->b (*a).b ``` (subject to operator overloading, as Konrad mentions, but that's unusual).
`a->b` is generally a synonym for `(*a).b`. The parenthesises here are necessary because of the binding strength of the operators `*` and `.`: `*a.b` wouldn't work because `.` binds stronger and is executed first. This is thus equivalent to `*(a.b)`. Beware of overloading, though: Since both `->` and `*` can be overlo...
What can I use instead of the arrow operator, `->`?
[ "", "c++", "pointers", "" ]
DataGridView, for example, lets you do this: ``` DataGridView dgv = ...; DataGridViewCell cell = dgv[1,5]; ``` but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes? ETA: T...
you can find how to do it [here](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx). In short it is: ``` public object this[int i] { get { return InnerList[i]; } set { InnerList[i] = value; } } ``` If you only need a getter the syntax in [answer below](https://stackoverflow.com/a/34098286/21733) can be us...
That would be the item property: <http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx> Maybe something like this would work: ``` public T Item[int index, int y] { //Then do whatever you need to return/set here. get; set; } ```
How do I overload the square-bracket operator in C#?
[ "", "c#", "collections", "operators", "operator-overloading", "" ]
I was wondering what people thought about the decision to support Entity Framework over LINQ-to-SQL? I have an application I'm developing originally in LINQ-to-SQL. I found it the perfect solution for our application. While attempting to port to Entity Framework I was surprised how rough it was. IMHO, not even close t...
That is pretty much my view. See my previous reply [here](https://stackoverflow.com/questions/276433/do-you-think-its-advantageous-to-switch-to-entity-framework#276439). This other question wasn't specifically about the problems in EF, but yes: it has a fair few glitches. For example (in addition to your existing optio...
I think it depends on the application platform. When my team set out to create a new ASP.net app, we wanted to go with EF... but after playing around with it for a bit, we went with Linq-To-SQL. In a web environment, managing the L2S datacontext was a lot easier. Also, we liked that L2S entities expose the original Id ...
Thoughts on Entity Framework
[ "", "sql", ".net", "entity-framework", "linq-to-sql", "" ]
I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run. So far I have: ``` SELECT startTime, endTime, cast(datediff(hh,starttime,endtime) as varchar) +':' +cast(datediff(mi,starttime,endtime)-60*datediff(h...
Try these Assuming 2 declared dates. ``` declare @start datetime set @start = '2008-11-02 15:59:59.790' declare @end datetime set @end = '2008-11-02 19:05:41.857' ``` This will return the hours / mins / seconds ``` select (datediff(ss, @start, @end) / 3600), (datediff(ss, @start, @end) / 60) % 60, (d...
[Here's](http://www.sqlservercurry.com/2008/04/find-hours-minutes-and-seconds-in.html) a way to do it: ``` -- Find Hours, Minutes and Seconds in between two datetime DECLARE @First datetime DECLARE @Second datetime SET @First = '04/02/2008 05:23:22' SET @Second = getdate() SELECT DATEDIFF(day,@First,@Second)*24 as To...
SQL: get DATEDIFF to not return negative values
[ "", "sql", "sql-server-2005", "t-sql", "datediff", "" ]
I'm finding that hitting the "Refresh" button on my browser will temporarily screw up the ViewState for controls inside an UpdatePanel. Here's my situation : I made a custom WebControl that stores values in the ViewState. I put this control inside an UpdatePanel. When I hit the "refresh" button on my browser, it will ...
I just re-read your question and realised I missed something... **You are hitting the *browsers* refresh button!** Is this a problem? **YES!** What happens when you hit the refresh button on the browser? It refreshes the current page. If there was a postback, it will resend the post data. The AJAX callback may upda...
Try the following... ``` protected override void LoadViewState(object savedState) { if (savedState != null) { object[] myState = (object[])savedState; if (myState[0] != null) base.LoadViewState(myState[0]); if (myState[1] != null) _clickCount = ((int)myState...
Inconsistent behavior with AJAX and ViewState in .NET
[ "", "c#", ".net", "ajax", "updatepanel", "viewstate", "" ]
I apologize in advance if this question seems remedial. Which would be considered more efficient in Python: **Standard import** ``` import logging try: ...some code... exception Exception, e: logging.error(e) ``` ...or... **Contextual import** ``` try: ...some code... exception Exception, e: import loggi...
Contextual imports are technically more efficient, but I think they can create other problems. Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unfo...
It depends on how often you execute the contextual import. An `import` statement requires checking to see if the module exists, which has a non-zero cost. Lots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import wi...
Which is more efficient in Python: standard imports or contextual imports?
[ "", "python", "" ]
I am implementing an asynchronous command pattern for the "client" class in a client/server application. I have done some socket coding in the past and I like the new Async pattern that they used in the Socket / SocketAsyncEventArgs classes. My async method looks like this: `public bool ExecuteAsync(Command cmd);` It ...
throwing an exception from the dispatch point may or may not be useful calling the callback passing an exception argument requires the completion callback to do 2 distinct things a second callback for exception reporting might make sense instead
One general pattern for asynchronous operations in .NET (at least for the `BackgroundWorker` and the `BeginInvoke()/EndInvoke()` method pairs is to have a result object that separates the callback from the actual return value or any exceptions that occurred. It's the responsibility of the callback to handle the excepti...
Async command pattern - exception handling
[ "", "c#", ".net", "exception", "design-patterns", "" ]
I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link. ``` <ul id="targetedArea"> <li></li> <li></li> <li></li> <li></li> </ul> <div id="clickedItems"> <a></a> <a></a> <a></a> <a></a> </div> ``` I can target them individually, but I know there must be a faster way b...
how about something like this: ``` $('#clickedItems a').click(function() { // figure out what position this element is in var n = $('#clickedItems a').index($(this) ); // update the targetedArea $('#targetedArea li:eq('+n+')').html('updated!'); return false; }); ``` assuming a 1:1 relationship between your `...
I know this is not directly answering your question, but maybe you're making it more difficult than it is. Give each of the A and LI elements an ID, and make the IDs so you can infer them from each other. As soon as an A is clicked, you immediately know the LI's ID and can refer to it directly. As a side effect, this...
After clicking the nth item, how do I manipulate another nth element?
[ "", "javascript", "jquery", "" ]
Hey! I was looking at this code at <http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html> I noticed that in some situations they used hex numbers, like in line 134: ``` for (j = 1; val && j <= 0x80; j <<= 1, q++) ``` Now why would they use the 0x80? I am not that good with hex but I found an online hex...
In both cases you cite, the bit pattern of the number is important, not the actual number. For example, In the first case, `j` is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses. In binary, that is, `0000:0001`, `0000:0010`, `0000:0100`, `0000:1000`, `0001:0000`, `0010:0000`, `0100:000...
There's a direct mapping between hex (or octal for that matter) digits and the underlying bit patterns, which is not the case with decimal. A decimal '9' represents something different with respect to bit patterns depending on what column it is in and what numbers surround it - it doesn't have a direct relationship to ...
Why use hex?
[ "", "c++", "c", "hex", "" ]
Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under `WEB-INF/classes` and restart the app. Is that okay?
I'd say that probably isn't a best practice, because of versioning: how do you know which version of the application you've got deployed? If you deploy a .war file your build process can take care of updating a build number (from source control, or separately, whatever - as long as each build has a different number it'...
You can solve your deployment tasks using maven. Every time you change anything, just type ``` svn update mvn clean compile war:exploded tomcat:inplace -P deployment ``` you have 'deployment' profile in your pom.xml file, containing all the configuraiton needed for deployment environment. this way you can event aut...
Is it okay to update a Java web application by replacing just single class files?
[ "", "java", "web-applications", "" ]