Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm developing an MFC application and I've recently been searching for a good method to remove the icon from a Windows title bar, but retain the close button. The two obvious candidate solutions are turning off the system menu style or using the tool window style, but I would prefer not to disable the system menu or us...
You can use `WM_NCRBUTTONDOWN` to detect if the user has right-clicked on your caption and then bring up the system menu.
Set `WS_EX_DLGMODALFRAME` extended style.
Removing icon from Windows title bars without ditching close button or system menu?
[ "", "c++", "windows", "user-interface", "mfc", "" ]
I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is [what the FSF has to say](http://www.gnu.org/licenses/gpl-faq.html) on the issue: > **If a program released under the GPL uses plug-ins, what are the requirements for the licenses of ...
> he distinction between fork/exec and dynamic linking, besides being kind of artificial, I don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has "plugins" which are essentially fire and forget with no API level integration, then the resu...
@Daniel > The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile? I'm not sure that the distinction **is** artificial. After a dynamic load the plugin code share...
Proprietary plug-ins for GPL programs: what about interpreted languages?
[ "", "python", "plugins", "open-source", "licensing", "interpreted-language", "" ]
Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter): ``` <html> <head> [snip] <meta name="generator" value="thevalue i'm looking for" /> [snip] ```
Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past. ``` StringBuilder html = new StringBuilder(); java.net.URL url = new URL("http://www.google.com/"); BufferedReader input = null; try { input new BufferedReader( new Inp...
Its amazing how noone, when addressing the problem of using RegEx with HTML, confronts the problem of HTML often **NOT** being well-formed, thus rendering a lot of HTML-parsers completely useless. If you are developing tools to analyze webpages and its a fact that these are not well-formed HTML, the statement "Regex s...
Quick way to find a value in HTML (Java)
[ "", "java", "html", "regex", "" ]
What code analysis tools do you use on your Java projects? I am interested in all kinds * static code analysis tools (FindBugs, PMD, and any others) * code coverage tools (Cobertura, Emma, and any others) * any other instrumentation-based tools * anything else, if I'm missing something If applicable, also state what...
For static analysis tools I often use CPD, [PMD](http://pmd.sourceforge.net), [FindBugs](http://findbugs.sourceforge.net), and [Checkstyle](http://checkstyle.sourceforge.net). CPD is the PMD "Copy/Paste Detector" tool. I was using PMD for a little while before I noticed the ["Finding Duplicated Code" link](http://pmd....
I use a combination of Cobertura, Checkstyle, (Ecl)Emma and Findbugs. [EclEmma](http://www.eclemma.org/) is an *awesome* Eclipse plugin that shows the code coverage by coloring the java source in the editor ([screenshot](http://www.eclemma.org/images/screen.png)) - the coverage is generated by running a JUnit test. Th...
What code analysis tools do you use for your Java projects?
[ "", "java", "code-coverage", "static-analysis", "" ]
With .Net what is the best way to interact with a service (i.e. how do most tray-apps communicate with their servers). It would be preferred if this method would be cross-platform as well (working in Mono, so I guess remoting is out?) --- ### Edit: Forgot to mention, we still have to support Windows 2000 machines in...
Be aware that if you are planning to eventually deploy on Windows Vista or Windows Server 2008, many ways that this can be done today will not work. This is because of the introduction of a new security feature called "Session 0 Isolation". Most windows services have been moved to run in Session 0 now in order to prop...
If this is a tray app, and not a true service, be wary of how you set up your communications if using pipes or TCP/IP. If multiple users are logged into a machine (Citrix, Remote Desktop), and each user launches a tray app "service", then you can run into a situation where you have multiple processes trying to use the ...
How to communicate with a windows service from an application that interacts with the desktop?
[ "", "c#", ".net", "windows-services", "service", "mono", "" ]
I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... For those who have used reflection in applications, have you measured performance hits and, is it really so bad?
It is. But that depends on what you're trying to do. I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application. However, if you're reflecting inside a series of nested loops with reflection calls on...
In his talk [The Performance of Everyday Things](http://weblogs.asp.net/craigshoemaker/archive/2008/06/17/the-performance-of-everyday-things.aspx), Jeff Richter shows that calling a method by reflection is about **1000 times slower** than calling it normally. Jeff's tip: if you need to call the method multiple times, ...
How costly is .NET reflection?
[ "", "c#", ".net", "performance", "reflection", "" ]
Is it possible to call a stored procedure from another stored procedure asynchronously? **Edit:** Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Executive summary: Yes, if your database has a message queue service. You can push a message onto a queue and the queue processor will consume it asynchronously. * Oracle: queues * Sql Server: service broker * DB2: event broker For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works ...
With MS Sql Server 2005, try the Service Broker and/or CLR stored procedures. I don't think there's anything built directly into TSQL.
Asynchronous Stored Procedure Calls
[ "", "sql", "stored-procedures", "db2", "" ]
In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such. ``` #ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if !defined(__cplusplus) #if !defined(__GNUC_...
I found the answer to my own question by finding a more compatible implementation of `stdbool.h` that is compliant with the C99 standard. ``` #ifndef _STDBOOL_H #define _STDBOOL_H #include <stdint.h> /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/s...
Size is not the only thing that will be inconsistent here. In C++ bool is a keyword, and C++ guarantees that a bool can hold a value of either 1 or 0 and nothing else. C doesn't give you this guarantee. That said, if interoperability between C and C++ is important you can emulate C's custom-made boolean by defining an...
interfacing with stdbool.h C++
[ "", "c++", "c", "boolean", "standards", "" ]
I want to do something like: ``` MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); ``` And then make changes to the new object that are not reflected in the original object. I don't often need this functionality, so when it's been necessary, I've resorted to creating a new...
Whereas one approach is to implement the [`ICloneable`](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) interface (described [here](https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568), so I won't regurgitate), here's a nice deep clone object copier I found on [The Code Project](h...
I wanted a cloner for very simple objects of mostly primitives and lists. If your object is out of the box JSON serializable then this method will do the trick. This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET. ``` public static T Clone<T>(T source...
Deep cloning objects
[ "", "c#", ".net", "clone", "deep-copy", "" ]
The Python docs say: > re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? ...
Look at the definition of [`re.sub`](http://docs.python.org/library/re.html#re.sub): ``` re.sub(pattern, repl, string[, count, flags]) ``` The 4th argument is the count, you are using `re.MULTILINE` (which is 8) as the count, not as a flag. Either use a named argument: ``` re.sub('^//', '', s, flags=re.MULTILINE) `...
``` re.sub('(?m)^//', '', s) ```
Python re.sub with a flag does not replace all occurrences
[ "", "python", "regex", "" ]
I've been tasked (by my wife) with creating a program to allow her to track the family trees on both sides of our family. Does anyone know of a cost-effective (free) control to represent this type of information? What I'm looking for is a modified org-chart type chart/tree. The modification is that any node should ha...
[Geni](http://www.geni.com/) is probably what your looking for.
I actually spotted [GRAMPS](http://gramps-project.org/wiki/index.php?title=Main_Page) just the other day.
Genealogy Tree Control
[ "", "c#", "controls", "tree", "genealogy", "" ]
I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process: * Clicks button * Method checks for updates, count is returned. * If greater than 0, then ask the user if they want to install using MessageBox.Show(). * If yes,...
Your UI isn't updating because all the work is happening in the user interface thread. Your call to: ``` this.BeginInvoke((MethodInvoker)delegate() {update.Action.Run(); }) ``` is saying invoke update.Action.Run() on the thread that created "this" (your form), which is the user interface thread. ``` Application.DoEv...
@ John Sibly [You can get away with *not* calling EndInvoke when dealing with WinForms without any negative consequences.](http://www.interact-sw.co.uk/iangblog/2005/05/16/endinvokerequired) > The only documented exception to the rule that I'm aware of is in Windows Forms, where you are officially allowed to call Con...
Compact Framework/Threading - MessageBox displays over other controls after option is chosen
[ "", "c#", "winforms", "multithreading", "compact-framework", "" ]
What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules? Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.
If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more *correct* but this is a nice balance between design and practicality IMHO. The master page takes a strongly typed view data class containing only information relevant to it: ``` public class Ma...
I prefer breaking off the data-driven pieces of the master view into partials and rendering them using **Html.RenderAction**. This has several distinct advantages over the popular view model inheritance approach: 1. Master view data is completely decoupled from "regular" view models. This is composition over inheritan...
Passing data to Master Page in ASP.NET MVC
[ "", "c#", ".net", "asp.net", "asp.net-mvc", "" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download...
I have reproduced what you are seeing: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "...
Using the returned-urllib-object method `info()`, you can get various information on the retrieved document. Example of grabbing the current Google logo: ``` >>> import urllib >>> d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif") >>> print d.info() Content-Type: image/gif Last-Modified: Thu, ...
Get size of a file before downloading in Python
[ "", "python", "urllib", "" ]
I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the `asp:`-style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my `...
Personally, I think the standard ASP.NET controls are fine for inhouse stuff - quick and dirty is good in that scenario. But, I once worked with a web developer who was also a designer and he refused to use the ASP.NET controls and only code in HTML and add runat="server" tags when needed. This was more because he wan...
I'm actually quite relieved to see some opinions here agreeing with my own: ASP.NET as a template language is very poor. I'd just like to rebut a couple of the pro points made here (flamesuit on!): Dave Ward mentions ID collisions - this is true, but my how badly handled. I would have preferred to see nodes reference...
Controls versus standard HTML
[ "", "c#", "asp.net", "controls", "" ]
I just get the beach ball all day long (it's been doing nothing for hours). It's not taking CPU, not reading from disk, not using the network. I'm using **Java 1.6** on **Mac OS X 10.5.4**. It worked once, now even restarts of the computer won't help. Activity Monitor says it's "(Not Responding)". Only thing that I ca...
I get the same problem after there's been an active connection sitting idle for a while. I solve it by restarting sql developer every once in a while. I also have Toad for Oracle running on a vmware XP session, and it works great. If you don't mind the money, try that.
The company [Navicat](http://www.navicat.com/) has released an Oracle client for Mac (and they do a Windows version too). It's not free, but I think you can get a 30 day demo.
Oracle SQL Developer not responsive when trying to view tables (or suggest an Oracle Mac client)
[ "", "java", "oracle", "macos", "" ]
What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'? The reason why I want to do this is becuase I want to modify the data within the be...
Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR. EntityManager.clear() will disconnect *all* the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected. So your best bet...
(may be too late to answer, but can be useful for others) I'm developing my first system with JPA right now. Unfortunately I'm faced with this problem when this system is almost complete. Simply put. Use Hibernate, or wait for JPA 2.0. In Hibernate, you can use 'session.evict(object)' to remove one object from sessi...
Detach an entity from JPA/EJB3 persistence context
[ "", "java", "orm", "jpa", "" ]
This gets the value of whatever is selected in my dropdown menu. ``` document.getElementById('newSkill').value ``` I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at [W3Schools](http://w3schools.com/) but that didn't have th...
Based on your example HTML code, here's one way to get the displayed text of the currently selected option: ``` var skillsSelect = document.getElementById("newSkill"); var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text; ```
Simply You can use jQuery instead of JavaScript ``` $("#yourdropdownid option:selected").text(); ``` Try This.
Getting the text from a drop-down box
[ "", "javascript", "dom", "browser", "client-side", "" ]
In MS SQL Server, I create my scripts to use customizable variables: ``` DECLARE @somevariable int SELECT @somevariable = -1 INSERT INTO foo VALUES ( @somevariable ) ``` I'll then change the value of `@somevariable` at runtime, depending on the value that I want in the particular situation. Since it's at the top o...
Postgres variables are created through the \set command, for example ... ``` \set myvariable value ``` ... and can then be substituted, for example, as ... ``` SELECT * FROM :myvariable.table1; ``` ... or ... ``` SELECT * FROM table1 WHERE :myvariable IS NULL; ``` *edit: As of psql 9.1, variables can be expanded ...
One final word on PSQL variables: 1. They don't expand if you enclose them in single quotes in the SQL statement. Thus this doesn't work: ``` SELECT * FROM foo WHERE bar = ':myvariable' ``` 2. To expand to a string literal in a SQL statement, you have to include the quotes in the variable set. However, th...
How do you use script variables in psql?
[ "", "sql", "postgresql", "variables", "psql", "" ]
I think this is specific to IE 6.0 but... In JavaScript I add a `div` to the DOM. I assign an `id` attribute. When I later try to pick up the `div` by the `id` all I get is `null`. Any suggestions? Example: ``` var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(n...
In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via `getElementById()`), you also need to use a lower-case attribute name in order for IE6 to recognize it as the `id`: ``` var newDiv = document.createElement("DIV"); newDiv.setAttribute("id", ...
The div needs to be added to an element for it to be part of the document. ``` document.appendChild(newDiv); alert( document.getElementById("obj_1000") ); ```
How do I add a div to DOM and pick it up later
[ "", "javascript", "css", "dhtml", "" ]
I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's `text`, `value`, and `selected` properties, but I don't think that javascript's built in `Array.sort()` would work correctly.
Extract options into a temporary array, sort, then rebuild the list: ``` var my_options = $("#my_select option"); var selected = $("#my_select").val(); my_options.sort(function(a,b) { if (a.text > b.text) return 1; if (a.text < b.text) return -1; return 0 }) $("#my_select").empty().append( my_options ); ...
Modified Tom's answer above slightly so that it actually modifies the contents of the select box to be sorted, rather than just returning the sorted elements. ``` $('#your_select_box').sort_select_box(); ``` jQuery function: ``` $.fn.sort_select_box = function(){ // Get options from select box var my_options...
What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?
[ "", "javascript", "jquery", "arrays", "sorting", "html-select", "" ]
I'm getting into more of a TDD workflow, and have a mix of MVC and asp.net Web Forms apps. MOQ is recommended for MVC. I've used Rhino for Web Forms. Does anyone have a best practice for having 1 framework mock for both?
Rhino's latest release includes much of the sweet sweet 3.5 love that MoQ has. I'm a fan of MoQ, so that's what I'm using. But I also have Rhino, in case it does something that MoQ doesn't do. TL;DR: MoQ it baby.
This is sort of a silly question, but I prefer Rhino Mocks as it represents a more complete understanding of [mocks vs. stubs](http://martinfowler.com/articles/mocksArentStubs.html). Look deep into TypeMock before committing to the price. Also, there is no recommended mocking framework for ASP.NET MVC. Finally - I'd...
Best mock framework that can do both WebForms and MVC?
[ "", "c#", "asp.net", "asp.net-mvc", "testing", "" ]
I need a JavaScript library that supports Ajax as well as help me in making simple and neat animation effects [in a website](http://www.voidy.com/) I am working on. Which library do you recommend?
I would definitely recommend JQuery as the easiest to use and the one which requires you to write the least code. <http://jquery.com/>
<http://script.aculo.us/> I think it fits your 'neat animation effects' requirement.
Which JavaScript library is recommended for neat UI effects?
[ "", "html", "javascript", "" ]
This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object? And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface: ``` private IWebBase FindWebBase() { if (H...
No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request." In other words it is an HttpContext object, not a Page. You can get to the Page object via HttpContext using: ``` Page page = HttpContext.Current.Handler as Page; if (page != null) { // Use page instance. ...
You're looking for `HttpContext.Handler`. Since Page implements IHttpHandler, you'll obtain a reference to the currently executing page.You'll have to cast it, or at least try to cast it to the particular type you're looking for. `HttpContext.Current` simply returns the singleton instance of HttpContext. Therefore, it...
Get current System.Web.UI.Page from HttpContext?
[ "", "c#", "asp.net", "httpcontext", "" ]
Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of ...
**Note**: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0> **Original answer:** I've defined the following property as we use this often in unit testing. ``` public static string AssemblyDirectory { get { ...
It's as simple as this: ``` var dir = AppDomain.CurrentDomain.BaseDirectory; ```
How do I get the path of the assembly the code is in?
[ "", "c#", ".net", "reflection", "mbunit", "" ]
Can someone tell me how to get path geometry from a WPF FlowDocument object? Please note that I do **not** want to use `FormattedText`. Thanks.
A `FlowDocument` can be viewed in any number of ways, but a `Path` is a fixed shape. I think maybe you really want some simplified, visual-only form of a `FlowDocument`'s contents. In that case you might try converting the `FlowDocument` to an XPS `FixedDocument` - the `FixedPage`s have `Canvas`es containing a bunch o...
Get the **Text** property of a **TextRange** object *initialized over the entire **FlowDocument***: ``` FlowDocument myFlowDocument = new FlowDocument(); //get your FlowDocument //put in some (or it already has) text string inText = "Hello, WPF World!"; TextRange tr = new TextRange(FlowDocument.ContentStart, FlowDoc...
Get path geometry from FlowDocument object
[ "", "c#", "wpf", "" ]
I'm trying to do a simple rotation in OpenGL but must be missing the point. I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally. At the moment I have code like this: ``` glPushMatrix(); glRotatef(90.0, 0.0, 1.0, 0.0); glBegin(GL_TRIANGLES); ...
Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth. You should try rotating around the Z axis instead and see if you get something that makes more sense. OpenGL has two matrices related to the display of geometry, the ModelView and...
Ensure that you're modifying the modelview matrix by putting the following before the glRotatef call: ``` glMatrixMode(GL_MODELVIEW); ``` Otherwise, you may be modifying either the projection or a texture matrix instead.
OpenGL Rotation
[ "", "c++", "opengl", "glut", "" ]
I've been tasked with redesigning part of a ms-sql database structure which currently involves a lot of views, some of which contain joins to other views. Anyway, I wonder if anyone here could recommend a utility to automatically generate diagrams to help me visualise the whole structure. What's the best program you'...
I am a big fan of Embarcadero's [ER/Studio](http://www.embarcadero.com/products/er-studio). It is very powerful and produces excellent on-screen as well as printed results. They have a free trial as well, so you should be able to get in and give it a shot without too much strife. Good luck!
Toad Data Modeller from Quest does a nice job on this and is reasonably priced. Embarcadero E/R studio is good too, as Bruce mentioned.
What program can I use to generate diagrams of SQL view/table structure?
[ "", "sql", "sql-server", "database", "diagram", "" ]
As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments. An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with th...
Heh, I was just about to come back with essentially the same answer (using Cake's Model::find): ``` $this->loadModel('Comment'); $this->Comment->find( 'all', array( 'fields' => array('COUNT(Comment.id) AS popularCount'), 'conditions' => array( 'Comment.created >' => strtotime('-1 month') ), 'g...
Shouldn't be too bad, you just need a group by (this is off the type of my head, so forgive syntax errors): ``` SELECT entry-id, count(id) AS c FROM comment WHERE comment.createdate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY entry-id ORDER BY c DESC ```
construct a complex SQL query (or queries)
[ "", "php", "cakephp", "" ]
I can easily set breakpoints in embedded JS functions, but I don't see any way of accessing external JS scripts via Firebug unless I happen to enter them during a debug session. Is there a way to do this without having to 'explore' my way into the script? @Jason: This is a good point, but in my case I do not have easy...
To view and access external JavaScript files (\*.js) from within Firebug: 1. Click on the 'Script' tab. 2. Click on the 'all' drop down in the upper left hand corner above the script code content window. 3. Select 'Show Static Scripts'. 4. Click on the dropdown button just to the right of what now says 'stati...
Place `debugger;` in your external script file on the line you want to break on.
How can I set breakpoints in an external JS script in Firebug
[ "", "javascript", "debugging", "firebug", "" ]
I am consuming the Twitter API and want to convert all URLs to hyperlinks. What is the most effective way you've come up with to do this? from ``` string myString = "This is my tweet check it out http://tinyurl.com/blah"; ``` to ``` This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com...
Regular expressions are probably your friend for this kind of task: ``` Regex r = new Regex(@"(https?://[^\s]+)"); myString = r.Replace(myString, "<a href=\"$1\">$1</a>"); ``` The regular expression for matching URLs might need a bit of work.
I did this exact same thing with [jquery consuming the JSON API](http://ralphwhitbeck.com/2007/11/20/PullingTwitterUpdatesWithJSONAndJQuery.aspx) here is the linkify function: ``` String.prototype.linkify = function() { return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) { ...
Easiest way to convert a URL to a hyperlink in a C# string?
[ "", "c#", "regex", "string", "hyperlink", "" ]
I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample <http://msdn.microsoft.com/en-us/library/ms7878...
Currently these are the most popular video frameworks available on Win32 platforms: 1. Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed. 2. DirectShow:...
I have used [OpenCV](http://sourceforge.net/projects/opencvlibrary/) to load video files and process them. It's also handy for many types of video processing including those useful for computer vision.
C++ : What's the easiest library to open video file
[ "", "c++", "windows", "video", "" ]
I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?
In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this: ``` static string Truncate(string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) return s; var cs = s.ToCharArray(); int length = 0; int i = 0; while (i < cs.Le...
You should be using the Encoding class to do your conversion to byte array correct? All Encoding objects have an overridden method GetMaxCharCount, which will give you "The maximum number of characters produced by decoding the specified number of bytes." You should be able to use this value to trim your string and prop...
How do I truncate a string while converting to bytes in C#?
[ "", "c#", ".net", "arrays", "string", "truncate", "" ]
If I open a file in Design View (web form), I get intellisense for my display code, but not my script code.. If I open with source code editor I, occasionally, get intellisense within the script tags. Anyone know how to get intellisense working all of the time for all of my code? Been living with this one for a long ...
VS2008. So far doing a re-install seems to be the best advice. I am using the `<%@ Page Language="C#" MasterPageFile="~/common/masterpages/MasterPage.master" %>`. When I say design-view I mean that I right+click on the file and choose "view designer" - this gives me access to the toolbox and tabs for designer,split, an...
What version are you using? Design view is for human-readable elements, you wouldn't be editing code there and therefore wouldn't need intellisense. If you are not using code-behind, you should only have one `<script runat="server">` tag on the page, and you would edit this in Source view. To enable intellisense, add t...
Visual Studio Intellisense, c#, no code behind
[ "", "c#", "visual-studio", "intellisense", "" ]
When making changes using `SubmitChanges()`, LINQ sometimes dies with a `ChangeConflictException` exception with the error message `Row not found or changed`, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that r...
Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize): ``` try { db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLi...
These (which you could add in a partial class to your datacontext might help you understand how this works: ``` public void SubmitKeepChanges() { try { this.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { foreach (ObjectChangeConflict occ in thi...
Data Conflict in LINQ
[ "", "c#", "linq", "linq-to-sql", "" ]
In a web-app I'm writing, the user is supposed to enter the path in the Perforce repository for the node they're entering. The application is supposed to validate that the entered directory exists in the repo. I've got the P4Package (p4.jar) lib, and I'm configuring it correctly enough that it works for almost everyth...
So, the code I was using did have a bug requiring me to make a change and check the code into my repository. However, since then, Perforce has come up with their own Java wrapper for the P4 client which works much better. I'd give that one a shot.
Sounds like the sync command has a bug in relation to dir entries and the command. My suggestion would be to just roll the command yourself, using the perforce command line as that has to be set up anyway in order to use the java library. ``` Process p = Runtime.getRuntime().exec("p4 dirs " + directory_argument); Buff...
Using P4Package (Java) from Java app to validate Perforce directory
[ "", "java", "perforce", "" ]
Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?
I'm currently using this: ``` String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception e...
This has worked well for me: ``` URL url = new URL(theURL); InputStream is = url.openStream(); int ptr = 0; StringBuffer buffer = new StringBuffer(); while ((ptr = is.read()) != -1) { buffer.append((char)ptr); } ``` Not sure at to whether the other solution(s) provided are any more efficient or not.
How to fetch HTML in Java
[ "", "java", "html", "screen-scraping", "" ]
Can anyone tell me if there is a way with generics to limit a generic type argument `T` to only: * `Int16` * `Int32` * `Int64` * `UInt16` * `UInt32` * `UInt64` I'm aware of the `where` keyword, but can't find an interface for **only** these types, Something like: ``` static bool IntegerFunction<T>(T value) where T ...
This constraint exists in .Net 7. Check out this [.NET Blog post](https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/) and the [actual documentation](https://learn.microsoft.com/en-us/dotnet/standard/generics/math). Starting in .NET 7, you can make use of interfaces such as `INumber` and `IFloatingPoint` to ...
More than a decade later, this feature finally exists in [.NET 7](https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/). The most generic interface is `INumber<TSelf>` (in the `System.Numerics` namespace), and it encompasses all numbers. To accept just integer types, consider using [`IBinaryInteger<TSelf>`](htt...
Is there a constraint that restricts my generic method to numeric types?
[ "", "c#", "generics", "constraints", "" ]
I always tend to forget these built-in **Symfony** functions for making links.
If your goal is to have user-friendly URLs throughout your application, use the following approach: 1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (...
This advice is for symfony 1.0. It probably will work for later versions. **Within your sfAction class**: string genUrl($parameters = array(), $absolute = false) eg. $this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true); **In a template**: This will generate a normal link. string link...
How do I generate a friendly URL in Symfony PHP?
[ "", "php", "url", "seo", "symfony1", "" ]
I am getting a `NoClassDefFoundError` when I run my Java application. What is typically the cause of this?
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true. It is important to keep two or three different exceptions straight in our head in this case: 1. **`java.lang.ClassNotFoundException`** This exception indicates that the class was not found on the...
Why am I getting a NoClassDefFoundError in Java?
[ "", "java", "noclassdeffounderror", "" ]
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time. I assume it is possible to do this, b...
Could not get the example to work using `FileChannel.read(ByteBuffer)` because it isn't a blocking read. Did however get the code below to work: ``` boolean running = true; BufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) ); public void run() { while( running ) { if( r...
If you want to read a file while it is being written and only read the new content then following will help you achieve the same. To run this program you will launch it from command prompt/terminal window and pass the file name to read. It will read the file unless you kill the program. java FileReader c:\myfile.txt ...
How do I use Java to read from a file that is actively being written to?
[ "", "java", "file", "file-io", "" ]
I plan to be storing all my config settings in my application's app.config section (using the `ConfigurationManager.AppSettings` class). As the user changes settings using the app's UI (clicking checkboxes, choosing radio buttons, etc.), I plan to be writing those changes out to the `AppSettings`. At the same time, whi...
since you're using a winforms app, if it's in .net 2.0 there's actually a user settings system (called Properties) that is designed for this purpose. [This article on MSDN](https://learn.microsoft.com/en-us/previous-versions/aa730869%28v=vs.80%29) has a pretty good introduction into this If you're still worried about ...
Check out SQLite, it seems like a good option for this particular scenario.
ConfigurationManager.AppSettings Performance Concerns
[ "", "c#", ".net", "performance", "configuration", "properties", "" ]
I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a `List<string>`.
Iterate through and for each element make the probability of selection = (number needed)/(number left) So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often...
Using linq: ``` YourList.OrderBy(x => rnd.Next()).Take(5) ```
Select N random elements from a List<T> in C#
[ "", "c#", "algorithm", "collections", "random", "element", "" ]
I was surprised recently to find that it's possible to have a return statement in a finally block in Java. It seems like lots of people think it's a bad thing to do as described in '[Don't return in a finally clause](https://web.archive.org/web/20070922061412/http://weblogs.java.net/blog/staufferjames/archive/2007/06/...
The examples you provided are reason enough to *not* use flow-control from finally. Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....
I had a REALLY hard time to track down a bug years ago that was caused by this. The code was something like: ``` Object problemMethod() { Object rtn = null; try { rtn = somethingThatThrewAnException(); } finally { doSomeCleanup(); return rtn; } } ``` What happened is that t...
Returning from a finally block in Java
[ "", "java", "exception", "return", "try-catch-finally", "" ]
How do you iterate through every file/directory recursively in standard C++?
In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using [Boost.FileSystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm). This has been accepted for inclusion in TR2, s...
From C++17 onward, the [`<filesystem>`](https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator) header, and range-`for`, you can simply do this: ``` #include <filesystem> using recursive_directory_iterator = std::filesystem::recursive_directory_iterator; ... for (const auto& dirEntry : recursive_di...
How do you iterate through every file/directory recursively in standard C++?
[ "", "c++", "filesystems", "" ]
I am trying to read a single file from a `java.util.zip.ZipInputStream`, and copy it into a `java.io.ByteArrayOutputStream` (so that I can then create a `java.io.ByteArrayInputStream` and hand that to a 3rd party library that will end up closing the stream, and I don't want my `ZipInputStream` getting closed). I'm pro...
Your loop looks valid - what does the following code (just on it's own) return? ``` zipStream.read(tempBuffer) ``` if it's returning -1, then the zipStream is closed before you get it, and all bets are off. It's time to use your debugger and make sure what's being passed to you is actually valid. When you call getNe...
You probably tried reading from a `FileInputStream` like this: ``` ZipInputStream in = new ZipInputStream(new FileInputStream(...)); ``` This **won’t** work since a zip archive can contain multiple files and you need to specify which file to read. You could use [java.util.zip.ZipFile](https://docs.oracle.com/javase/...
Reading from a ZipInputStream into a ByteArrayOutputStream
[ "", "java", "zipinputstream", "zipoutputstream", "" ]
I've seen a few fixes for allowing PNG images to have transparency in Internet Explorer 6, but I've yet to find one that also allows you to set the background position in CSS. If you use sprites, it's a deal-breaker. I've resorted to using GIF's (which are not as high quality), not using transparent images at all, or s...
Yes. Convert your images to use indexed pallets (png256). You can support transparency (just like gif), but not an alpha channel. You can do this using [Irfanview](http://www.irfanview.com/) and the pngout plugin, [pngquant](http://www.libpng.org/pub/png/apps/pngquant.html) or [pngnq](http://pngnq.sourceforge.net/). ...
[This](http://www.micahtischler.com/#mtjs_iepnghandler.js) is a new technique that has popped up in the last month or so. From the page: > In this script image tags are supported, both with and without a blank spacer GIF, and background image PNGs may be positioned, as well as repeated, even if they're smaller than th...
Is there a JavaScript PNG fix for IE6 that allows CSS background positioning?
[ "", "javascript", "css", "internet-explorer-6", "png", "transparency", "" ]
I have heard/read the term but don't quite understand what it means. When should I use this technique and how would I use it? Can anyone provide a good code sample?
The visitor pattern is a way of doing double-dispatch in an object-oriented way. It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time. Double dispatch is a special case of **multiple dispatch**. When you call a virtual method on an obj...
The code posted by Mark isn't complete and what ever is there isn't working. So tweaked and complete. ``` class DoubleDispatch { public T Foo<T>(object arg) { var method = from m in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection...
Double dispatch in C#?
[ "", "c#", "design-patterns", "language-features", "double-dispatch", "" ]
Are there any good books or website that go over creating a `JTable`? I want to make one column editable. I would like to actually put a inherited `JCheckBox` component (that we created here) into one of the table columns instead of just having the table put `JCheckBox` in based on it being an editable `boolean` field....
To make a column editable you have to override the `isCellEditable` method in the `TableModel`. Creating a `TableModel` is fairly easy if you inherit `AbstractTableModel` and I'd recommend it for all but the most simple `JTable`s. However, adapting the `TableModel` is only part of what you need to do. To actually get ...
The class you want to look into extending to create your own behavior is DefaultTableModel. That will allow you to define your own behavior. A decent tutorial can be found [on sun's site](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data).
Editable JTable Tutorial
[ "", "java", "swing", "jtable", "" ]
I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?
Another option is to consider looking at the [JSch library](http://www.jcraft.com/jsch/ "JSch library"). JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others. It supports both user/pass and certificate-based logins nicely, as ...
Here is the complete source code of an example using [JSch](http://www.jcraft.com/jsch/) without having to worry about the ssh key checking. ``` import com.jcraft.jsch.*; public class TestJSch { public static void main(String args[]) { JSch jsch = new JSch(); Session session = null; try { ...
How to retrieve a file from a server via SFTP?
[ "", "java", "ftp", "sftp", "security", "" ]
So I have a pointer to an array of pointers. If I delete it like this: ``` delete [] PointerToPointers; ``` Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any goo...
Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have ...
I agree with Jason Cohen though we can be a bit clearer on the reason for needing to delete your pointers with the loop. For every "new" or dynamic memory allocation there needs to be a "delete" a memory de-allocation. Some times the "delete" can be hidden, as with smartpointers but it is still there. ``` int main() {...
C++ deleting a pointer to a pointer
[ "", "c++", "pointers", "" ]
I am writing a Java utility that helps me to generate loads of data for performance testing. It would be *really* cool to be able to specify a regex for Strings so that my generator spits out things that match this. Is something out there already baked that I can use to do this? Or is there a library that gets me most...
Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps. If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern c...
It's too late to help the original poster, but it could help a newcomer. [Generex](https://github.com/mifmif/Generex) is a useful java library that provides many features for using regexes to generate strings (random generation, generating a string based on its index, generating all strings...). Example : ``` Generex...
Using Regex to generate Strings rather than match them
[ "", "java", "regex", "" ]
I've got an RMI call defined as: ``` public void remoteGetCustomerNameNumbers(ArrayList<String> customerNumberList, ArrayList<String> customerNameList) throws java.rmi.RemoteException; ``` The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works wit...
As Tom mentions, you can pass remote objects. You'd have to create a class to hold your list that implements Remote. Anytime you pass something that implements Remote as an argument, whenever the receiving side uses it, it turns around and makes a remote call *back* to the caller to work with that object.
Arguments in RMI calls a serialised. Deserialisation on the server creates a copy of the lists. If the lists remained on the client side, then the number of network calls would be quite high. You can pass remote objects, but beware of the performance implications.
Pass by reference not returning in RMI for ArrayList
[ "", "java", "arraylist", "rmi", "" ]
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using `default(T)`. When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call `default(T)` on an object, it returns null. For various reasons we...
Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code: ``` if (typeof(T) == typeof(String)) return (T)(object)String.Empty; ```
``` if (typeof(T).IsValueType || typeof(T) == typeof(String)) { return default(T); } else { return Activator.CreateInstance<T>(); } ``` Untested, but the first thing that came to mind.
Best way to test if a generic type is a string? (C#)
[ "", "c#", "generics", "" ]
I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets. Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C...
The unix tool `xxd` is distributed as part of [`vim`](http://www.vim.org/download.php), and according to <http://www.vmunix.com/vim/util.html#xxd>, the source for xxd is <ftp://ftp.uni-erlangen.de:21/pub/utilities/etc/xxd-1.10.tar.gz>. It was written in C and is about 721 lines. The only licensing information given for...
I often use this little snippet I've written long time ago. It's short and easy to add anywhere when debugging etc... ``` #include <ctype.h> #include <stdio.h> void hexdump(void *ptr, int buflen) { unsigned char *buf = (unsigned char*)ptr; int i, j; for (i=0; i<buflen; i+=16) { printf("%06x: ", i); for ...
Off-the-Shelf C++ Hex Dump Code
[ "", "c++", "logging", "hex", "hexdump", "" ]
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: > a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the...
This will do what you want: ``` signum = status & 0xff exitstatus = (status & 0xff00) >> 8 ```
To answer your general question, you can use [bit manipulation](https://en.wikipedia.org/wiki/Bit_manipulation) ``` pid, status = os.wait() exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8 ``` However, there are also [built-in functions](https://docs.python.org/3/library/functions.html) for interpreting exi...
How do I treat an integer as an array of bytes in Python?
[ "", "python", "" ]
I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone. Bonus if I can output in the user's locale date format.
Seems the most foolproof way to start with a UTC date is to create a new `Date` object and use the `setUTC…` methods to set it to the date/time you want. Then the various `toLocale…String` methods will provide localized output. ### Example: ``` // This would come from the server. // Also, this whole block could pro...
## You can do it with [moment.js](http://momentjs.com/) (deprecated in 2021) It's best to [parse](http://momentjs.com/docs/#/parsing/) your date string from UTC as follows (create an [ISO-8601](http://en.wikipedia.org/wiki/ISO_8601) compatible string on the server to get consistent results across all browsers): ``` v...
Display date/time in user's locale format and time offset
[ "", "javascript", "datetime", "timezone", "" ]
I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish `if` and `elif` statements for every site as shown in the following code, which I would like to avoid. ``` if site == 'site1': ... elif site == 'site2: ... ``` What...
Django has this built in. See [the sites framework](http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites). As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the `Host` HTTP header in the query when you are retrie...
Using Django on apache with mod\_python, I host multiple (unrelated) django sites simply with the following apache config: ``` <VirtualHost 1.2.3.4> DocumentRoot /www/site1 ServerName site1.com <Location /> SetHandler python-program SetEnv DJANGO_SETTINGS_MODULE ...
Running multiple sites from a single Python web framework
[ "", "python", "frameworks", "" ]
On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only *Sleep* with millisecond granularity. On Unix, I can use the us...
On Windows the use of `select` forces you to include the [Winsock](https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx) library which has to be initialized like this in your application: ``` WORD wVersionRequested = MAKEWORD(1,0); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); ``...
This indicates a mis-understanding of sleep functions. The parameter you pass is a *minimum* time for sleeping. There's no guarantee that the thread will wake up after exactly the time specified. In fact, threads don't "wake up" at all, but are rather chosen for execution by the OS scheduler. The scheduler might choose...
How to make thread sleep less than a millisecond on Windows
[ "", "c++", "windows", "winapi", "sleep", "" ]
I'm looking for good/working/simple to use PHP code for parsing raw email into parts. I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart. And before I get pointed at PEAR/PECL, I need actual code. My...
What are you hoping to end up with at the end? The body, the subject, the sender, an attachment? You should spend some time with [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) to understand the format of the mail, but here's the simplest rules for well formed email: ``` HEADERS\n \n BODY ``` That is, the first blan...
Try the Plancake PHP Email parser: <https://github.com/plancake/official-library-php-email-parser> I have used it for my projects. It works great, it is just one class and it is open source.
parsing raw email in php
[ "", "php", "email", "" ]
MonoDevelop 1.0 doesn't appear to have a code-formatter like Eclipse does for Java. Is there a preferred shell script (or MonoDevelop add-in?) that you've found to work well?
At the moment, source code formatting in MonoDevelop is marked as a future enhancement: <https://bugzilla.novell.com/show_bug.cgi?id=321946> In the meantime, you may want to check out Artistic Style for C# formatting: <http://astyle.sourceforge.net/> I'm planning to see how this might be wired up as an external tool ...
Thanks, Brandon. I submitted a patch to MonoDevelop. The issue with MonoDevelop add-ins is that there is a mono compiler bug that doesn't handle anonymous delegates correctly. (bug report: <https://bugzilla.novell.com/show_bug.cgi?id=394347>) The patch/workaround is to just cast the anonymous delegate to the proper de...
C# Code Formatter for Linux and/or MonoDevelop
[ "", "c#", "formatting", "mono", "" ]
I've never used any of the .NET generics in my work, but I understand that they are fairly popular. Does anyone have any good links or book suggestions for learning them? As a bonus; I only vaguely understand what .NET generic collections are and what they do...does anyone have any practical examples of how they might ...
* <http://www.informit.com/articles/article.aspx?p=605369> * <http://www.codeproject.com/KB/cs/genericcache.aspx>
The obvious choice.. [MSDN C# Generics](http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx)
Best resource for learning .NET generics?
[ "", "c#", ".net", "generics", "" ]
Does any know of a good calendar (not datepicker, but a BIG browsable calendar) plugin for one of the major javascript frameworks. I'd prefer jQuery.
just published a new open source project (jQuery plugin). sounds exactly like what you want: [FullCalendar](http://arshaw.com/fullcalendar/) Hope it works well for you!
I prefer [Eyecon Calendar.](http://eyecon.ro/datepicker/) Maybe the best.
Javascript framework calendar plugin
[ "", "javascript", "jquery", "calendar", "" ]
This is pretty weird. I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x' Is SQL Server 2005 mapping the SP name to a different one for security pu...
In general, when you know an object exists because it's been used in a query, and you can't find it in the object tree in Management Studio, you can do this to find it. ``` select * from sys.objects where name = 'THE_NAME_YOU_WANT' ``` I just checked, and it works with Synonyms.
Possibly silly questions, but just in case... have you refreshed the SP list? Have you checked for a stored procedure of that name under a different owner? If you created the stored procedure without specifying the owner then it could be in the list under your ownership (or not at all if the list is filtered to only "d...
I traced a Stored Procedure as shown in the SQL Server 2005 Profiler. It's not found but works. Why?
[ "", "sql", "sql-server", "sql-server-2005", "stored-procedures", "" ]
I have a 'foreach' macro I use frequently in C++ that works for most STL containers: ``` #define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) ``` (Note that 'typeof' is a gcc extension.) It is used like this: ``` std::vector< ...
You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable. ``` #define ci(container) container ## iter #define foreach_value(var,...
You would be looking for [BOOST\_FOREACH](http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html) - they have done all the work for you already! If you do want to roll your own, you can declare a block anywhere in C++, which resolves your scope issue with your intermediate storage of itr->second ... ``` // Valid ...
"foreach values" macro in gcc & cpp
[ "", "c++", "gcc", "" ]
Is there any difference to the following code: ``` class Foo { inline int SomeFunc() { return 42; } int AnotherFunc() { return 42; } }; ``` Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the `AnotherFunc` s...
Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.
The `inline` keyword is essentially a hint to the compiler. Using `inline` doesn't guarantee that your function *will* be inlined, nor does omitting it guarantee that it *won't*. You are just letting the compiler know that it might be a good idea to try harder to inline that particular function.
Inlining C++ code
[ "", "c++", "inline-functions", "" ]
Considering such code: ``` class ToBeTested { public: void doForEach() { for (vector<Contained>::iterator it = m_contained.begin(); it != m_contained.end(); it++) { doOnce(*it); doTwice(*it); doTwice(*it); } } void doOnce(Contained & c) { // do something } void doTwice(Contai...
If you're interested in performance, I recommend that you write a test that measures performance. Check the current time, run the method you're concerned about, then check the time again. Assert that the total time taken is less than some value. The problem with check that methods are called in a certain order is tha...
You should be able to use any good mocking framework to verify that calls to a collaborating object are done in a specific order. However, you don't generally test that one method makes some calls to other methods on the same class... why would you? Generally, when you're testing a class, you only care about testing ...
How to test function call order
[ "", "c++", "unit-testing", "tdd", "" ]
I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by `GO` statements, but `SqlCommand.ExecuteNonQuery()` does not like `GO` statements. My solution, which I suppose I'll post for reference, was to sp...
Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: [http://weblogs.asp.net/jongalloway/Handling-\_2200\_GO\_2200\_-Separators-in-SQL-Scripts-*2D00*-the-easy-way](http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-...
This is what I knocked together to solve my immediate problem. ``` private void ExecuteBatchNonQuery(string sql, SqlConnection conn) { string sqlBatch = string.Empty; SqlCommand cmd = new SqlCommand(string.Empty, conn); conn.Open(); sql += "\nGO"; // make sure last batch is executed. try { ...
Execute a large SQL script (with GO commands)
[ "", "c#", "sql-server", "" ]
If one Googles for "difference between `notify()` and `notifyAll()`" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in `notify()` and all in `notifyAll()`. However (if I do understand the difference between these met...
> However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition. That is not correct. `o.notifyAll()` wakes *all* of the threads that are blocked in `o.wait()` calls. The threads are only allowed to return from `o.wait()` one-by-one, but the...
Clearly, `notify` wakes (any) one thread in the wait set, `notifyAll` wakes all threads in the waiting set. The following discussion should clear up any doubts. `notifyAll` should be used most of the time. If you are not sure which to use, then use `notifyAll`.Please see explanation that follows. Read very carefully a...
Java: notify() vs. notifyAll() all over again
[ "", "java", "multithreading", "" ]
I am looking for either a FireFox extension, or a similar program, that allows you to craft GET and POST requests. The user would put in a form action, and as many form key/value pairs as desired. It would also send any cookie information (or send the current cookies from any domain the user chooses.) The Web Developer...
Actually I think [Poster](https://addons.mozilla.org/en-US/firefox/addon/2691) is what you're looking for. [A Screen shot of an older Poster version](https://addons.mozilla.org/img/uploads/previews/full/19/19951.png)
If you're a windows user, use [Fiddler](http://www.fiddler2.com/fiddler2/version.asp). It is invaluable for looking at the raw Http requests and responses. It also has the ability to create requests with the request builder and it has an auto responder also, so you can intercept requests. It even lets you inspect HTTPS...
Looking for a specific FireFox extension / program for Form posting
[ "", "javascript", "html", "" ]
I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform?
The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a [javax.xml.validation.Validator](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html). ``` import javax.xml.XMLConstants; import javax.xml.transform.So...
Here's how to do it using [Xerces2](http://xerces.apache.org/xerces2-j/). A tutorial for this, [here](http://www.ibm.com/developerworks/edu/x-dw-xvalid-i.html) (req. signup). Original attribution: blatantly copied from [here](http://forums.sun.com/thread.jspa?messageID=3411478): ``` import org.apache.xerces.parsers.D...
How to validate an XML file against an XSD file?
[ "", "java", "xml", "validation", "xsd", "" ]
I know that there is no official API for Google Analytics but is there a way to access Google Analytics Reports with C#?
**Update**: Google launched a Google Analytics API today. [Google Analytics Blog - API Launched](http://analytics.blogspot.com/2009/04/attention-developers-google-analytics.html)
I wrote a small project that lets you generate pretty much any Analytics report. It's listed on Google's Analytics API page - <http://code.google.com/apis/analytics/docs/gdata/gdataArticlesCode.html> You can read about it here and get the source code - <http://www.reimers.dk/blogs/jacob_reimers_weblog/archive/2009/05/...
Google Analytics Access with C#
[ "", "c#", "google-analytics", "google-analytics-api", "" ]
I once worked with an architect who banned the use of SQL views. His main reason was that views made it too easy for a thoughtless coder to needlessly involve joined tables which, if that coder tried harder, could be avoided altogether. Implicitly he was encouraging code reuse via copy-and-paste instead of encapsulatio...
There are some very good uses for views; I have used them a lot for tuning and for exposing less normalized sets of information, or for UNION-ing results from multiple selects into a single result set. Obviously any programming tool can be used incorrectly, but I can't think of any times in my experience where a poorl...
You've answered your own question: > he was encouraging code reuse via copy-and-paste Reuse the code by creating a view. If the view performs poorly, it will be much easier to track down than if you have the same poorly performing code in several places.
SQL Server Views, blessing or curse?
[ "", "sql", "sql-server", "" ]
I am looking to write some C# code for linux/windows/mac/any other platform, and am looking for best practices for portable code. Project [mono](http://go-mono.org) has some great [porting](http://www.mono-project.com/Category:Porting) resources. What are the best practices for portable C#?
I've actually used winforms and it was fine. It was BUTT UGLY, but it worked. Obviously, don't use P/Invoke, or any win32 stuff like the registry. Also be aware of any third party DLL's. For example, we use a third party SQLite dll which actually contains native code in it which we have to swap out if we want to run o...
I hate the term "Best practice" because it seems that some practices can be the best in any context, which is a risky thing, but I'll tell what I consider a "Good practice" for multi-platform code (and for most other type of development): Use a continuous integration engine and **build for all the target platforms all...
Best practices for portable C#
[ "", "c#", "mono", "cross-platform", "" ]
Consider: ``` List<String> someList = new ArrayList<>(); // add "monkey", "donkey", "skeleton key" to someList ``` ``` for (String item : someList) { System.out.println(item); } ``` What would the equivalent `for` loop look like without using the *for each* syntax? --- People new to Java commonly encounter iss...
``` for (Iterator<String> i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); } ``` Note that if you need to use `i.remove();` in your loop, or access the actual iterator in some way, you cannot use the `for ( : )` idiom, since the actual iterator is merely inferred. ...
The construct *for each* is also valid for arrays. e.g. ``` String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" }; for (String fruit : fruits) { // fruit is an element of the `fruits` array. } ``` which is essentially equivalent of ``` for (int i = 0; i < fruits.length; i++) { String fr...
In detail, how does the 'for each' loop work in Java?
[ "", "java", "foreach", "syntactic-sugar", "" ]
I'm creating a custom drop down list with AJAX dropdownextender. Inside my drop panel I have linkbuttons for my options. ``` <asp:Label ID="ddl_Remit" runat="server" Text="Select remit address." Style="display: block; width: 300px; padding:2px; padding-right: 50px; font-family: Tahoma; font-size: 11px;" /> <asp:Pa...
I'm not sure what your setDDL method does in your script but it should fire if one of the link buttons is clicked. I think you might be better off just inserting a generic html anchor though instead of a .net linkbutton as you will have no reference to the control on the server side. Then you can handle the data excahn...
Ok, I used Literals to create anchor tags with onclicks on them and that seems to be working great. Thanks alot.
Linkbutton click event not running handler
[ "", "c#", "events", "asp.net-ajax", "webforms", "" ]
I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once ag...
You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped. See below: ``` void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * ...
> Heh, this isnt homework. If thats the case then consider using the STL to manage arrays and sort. Its easier to develop and maintain and the std::sort algorithm is asymptotically faster than bubble sort.
How can I sort an array of double pointers based on the values they point to?
[ "", "c++", "c", "arrays", "pointers", "reference", "" ]
How would you find the fractional part of a floating point number in PHP? For example, if I have the value `1.25`, I want to return `0.25`.
``` $x = $x - floor($x) ```
``` $x = fmod($x, 1); ``` Here's a demo: ``` <?php $x = 25.3333; $x = fmod($x, 1); var_dump($x); ``` Should ouptut ``` double(0.3333) ``` [Credit.](https://stackoverflow.com/questions/50801/whats-the-best-way-to-get-the-fractional-part-of-a-float-in-php/41626638#comment17394709_50806)
What's the best way to get the fractional part of a float in PHP?
[ "", "php", "" ]
Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: [More info about singletons here:](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289) So I have read the thread [Singletons: good design or a crutch?](https://stackoverfl...
Answer: Use a Singleton if: * You need to have one and only one object of a type in system Do not use a Singleton if: * You want to save memory * You want to try something new * You want to show off how much you know * Because everyone else is doing it (See [cargo cult programmer](http://en.wikipedia.org/wiki/Cargo...
Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way. A singleton gives you: 1. Global access to an object, and 2. A guarantee that no more than one object of this type *can ever be created* Number one is straightforward. Globals are generally bad. We should n...
Singleton: How should it be used
[ "", "c++", "design-patterns", "singleton", "" ]
I've seen news of [John Resig's fast new selector engine named Sizzle](http://github.com/jeresig/sizzle/tree/master) pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is someth...
A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). For example, this jQuery: ``` $('div') ``` Would search for and return all of the <div> elements on the page. It uses jQuery's selector engine to do that. Optimizing the selector eng...
A selector engine is a JavaScript library that lets you select elements in the DOM tree using some kind of string for identifying them (think regular expressions for DOM elements). Most selector engines use some variation of the CSS3 selectors syntax so, for example, you can write something like: ``` var paragraphs = ...
What is a selector engine?
[ "", "javascript", "jquery", "glossary", "resig", "" ]
I stumbled over this passage in the [Django tutorial](http://www.djangoproject.com/documentation/tutorial01/): > Django models have a default **str**() method that calls **unicode**() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal...
> what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux...
Meanwhile, I did a refined research to verify what the internal representation in Python is, and also what its limits are. "[The Truth About Unicode In Python](http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python "The truth about Unicode in Python")" is a very good article which cites directly from ...
Unicode vs UTF-8 confusion in Python / Django?
[ "", "python", "django", "unicode", "" ]
I've run on a little problem today: I have a JS drop down menu and when I inserted a GoogleMap... the Menu is rendered behind the Google Map... Any ideas on how to chance the z Index of the Google Map? Thanks!
If your problem happens in Internet Explorer, but it renders the way you'd expect in FireFox or Safari, [this link](http://aplus.rs/lab/z-pos/) was extraordinarily helpful for me with a [similar problem](https://stackoverflow.com/questions/88883/yui-autocomplete-renders-under-other-page-elements-in-ie7). It appears to...
Note that dropdown menus in some browsers (*ahem*IE\*ahem) cannot be zPositioned at all. You'll need to use an "iframe shim" to obscure it or hide the dropdown entirely if you want to position something above it. See: <http://clientside.cnet.com/wiki/cnet-libraries/02-browser/02-iframeshim>
Google Maps, Z Index and Drop Down Javascript menus
[ "", "javascript", "html", "css", "google-maps", "z-index", "" ]
I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first. This is so I can have non-identical instances with the same name. ``` Class A { public static package1.Foo foo; } Class B { public static package2.Foo fo...
I agree with others that you're probably thinking about this the wrong way. With that out of the way, this may work for you if you are only accessing static members: ``` public class A { public static class Foo extends package1.Foo {} } public class B { public static class Foo extends package2.Foo {} } ```
You should use: ``` Foo.bar ``` And not: ``` A.foo.bar ``` That's what the warning means. The reason is that `bar` isn't a member of an *instance* of `Foo`. Rather, `bar` is global, on the class `Foo`. The compiler wants you to reference it globally rather than pretending it's a member of the instance.
How do I correctly access static member classes?
[ "", "java", "static", "" ]
I've recently inherited an application that makes very heavy use of session, including storing a lot of custom data objects in session. One of my first points of business with this application was to at least move the session data away from InProc, and off load it to either a stateserver or SQL Server. After I made al...
When you write > does a lot of object comparisons using GetHashCode() i sense there is something horribly wrong with this code. The GetHashCode method does not guarantee, that the returned hash values should be in any way unique given two different objects. As far as GetHashCode is concerned, it can return 0 for all ...
Override the GetHashCode method in classes that get called this method and calculate the hash code based on unique object properties (like ID or all object fields).
Different values of GetHashCode for inproc and stateserver session variables
[ "", "c#", "asp.net", "session", "" ]
If I have a query like: ``` Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) ``` and I have an index on the `EmployeeTypeId` field, does SQL server still use that index?
Yeah, that's right. If your `Employee` table has 10,000 records, and only 5 records have `EmployeeTypeId` in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the `EmployeeTypeId` in (1,2,3), then it would most likely just do a table scan to get the corre...
Usually it would, unless the IN clause covers too much of the table, and then it will do a table scan. Best way to find out in your specific case would be to run it in the query analyzer, and check out the execution plan.
Do indexes work with "IN" clause
[ "", "sql", "indexing", "" ]
How can I get the `IDENTITY` of an inserted row? I know about `@@IDENTITY` and `IDENT_CURRENT` and `SCOPE_IDENTITY`, but don't understand the implications or impacts attached to each. How do these differ, and when would each be used?
* [`@@IDENTITY`](http://msdn.microsoft.com/en-us/library/ms187342.aspx) returns the last identity value generated for any table in the current session, across all scopes. **You need to be careful here**, since it's across scopes. You could get a value from a trigger, instead of your current statement. * [`SCOPE_IDENTIT...
I believe the safest and most accurate method of retrieving the inserted id would be using the output clause. for example (taken from the following [MSDN](http://msdn.microsoft.com/en-us/library/ms177564.aspx) article) > ``` > USE AdventureWorks2008R2; > GO > DECLARE @MyTableVar table( NewScrapReasonID smallint, > ...
How to get the identity of an inserted row?
[ "", "sql", "sql-server", "t-sql", "" ]
It is generally accepted that the use of cursors in stored procedures should be avoided where possible (replaced with set based logic etc). If you take the cases where you need to iterate over some data, and can do in a read only manner, are fast forward (read only forward) cursor more or less inefficient than say whil...
The 'Best Practice' of avoiding cursors in SQL Server dates back to SQL Server 2000 and earlier versions. The rewrite of the engine in SQL 2005 addressed most of the issues related to the problems of cursors, particularly with the introduction of the fast forward option. Cursors are not neccessarily worse than set-base...
While a fast forward cursor does have some optimizations in Sql Server 2005, it is *not* true that they are anywhere close to a set based query in terms of performance. There are very few situations where cursor logic cannot be replaced by a set-based query. Cursors will always be inherently slower, due in part to the ...
SQL Server Fast Forward Cursors
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: ``` using...
Is there any reason that you have to do it through the registry? If not, you can use Environment.SetEnvironmentVariable() since .NET 2.0. It allows you to set on a machine, process or user basis.
What OS is this? Is it on a 64-bit system? What is the nature of the failure: silent or is an exception thrown? You could try running [ProcessMonitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) and seeing if it sees the attempt to set the value.
Cannot create an environment variable in the registry
[ "", "c#", "registry", "environment", "" ]
Is there another way to render graphics in C# beyond [GDI+](https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP) and [XNA](http://en.wikipedia.org/wiki/Microsoft_XNA)? (For the development of a tile map editor.)
[SDL.NET](http://cs-sdl.sourceforge.net/) is the solution I've come to love. If you need 3D on top of it, you can use Tao.OpenGL to render inside it. It's fast, industry standard ([SDL](http://en.wikipedia.org/wiki/Simple_DirectMedia_Layer), that is), and cross-platform.
Yes, I have written a Windows Forms control that wraps DirectX 9.0 and provides direct pixel level manipulation of the video surface. I actually wrote another post on Stack Overflow asking if there are other better approaches: *[Unsafe C# and pointers for 2D rendering, good or bad?](https://stackoverflow.com/questions...
Rendering graphics in C#
[ "", "c#", "gdi+", "xna", "rendering", "" ]
In C# you can make a block inside of a method that is not attached to any other statement. ``` public void TestMethod() { { string x = "test"; string y = x; { int z = 42; int zz = z; } } } ``` This code compil...
Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects. [Ray Hayes](https://stackoverflow.com/users/7093/ray-hayes) points out that the .NET garbage collector will not immediately collect the out-of-scope o...
An example would be if you wanted to reuse a variable name, normally you can't reuse variable names This is not valid ``` int a = 10; Console.WriteLine(a); int a = 20; Console.WriteLine(a); ``` but this is: ``` { int a = 10; Console.WriteLine(a); } { ...
What is the value of an anonymous unattached block in C#?
[ "", "c#", "" ]
I'm writting a financial C# application which receive messages from the network, translate them into different object according to the message type and finaly apply the application business logic on them. The point is that after the business logic is applied, I'm very sure I will never need this instance again. Rather...
Don't delete them right away. Calling the garbage collector for each object is a bad idea. Normally you *really* don't want to mess with the garbage collector at all, and even time critical processes are just race conditions waiting to happen if they're that sensitive. But if you know you'll have busy vs light load pe...
Look here: <http://msdn.microsoft.com/en-us/library/bb384202.aspx> You can tell the garbage collector that you're doing something critical at the moment, and it will try to be nice to you.
How to avoid garbage collection in real time .NET application?
[ "", "c#", ".net", "garbage-collection", "real-time", "finance", "" ]
Basically, I've written an API to www.thetvdb.com in Python. The current code can be found [here](http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py). It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: ``` print tvdbinstance[1][23]['episodename'] # get the ...
OK, what you need is `classobj` from new module. That would allow you to construct exception classes dynamically (`classobj` takes a string as an argument for the class name). ``` import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i ``` this gives you: ``` Traceback (most ...
Why not use SQLite? There is good support in Python and you can write SQL queries to get the data out. Here is the Python docs for [sqlite3](http://docs.python.org/lib/module-sqlite3.html) --- If you don't want to use SQLite you could do an array of dicts. ``` episodes = [] episodes.append({'season':1, 'episode': 2,...
Best way to abstract season/show/episode data
[ "", "python", "data-structures", "" ]
Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions. The simple solution would seem to be just to catch any `IOE...
> ...but is it possible to get a bit more fine-grained error messages. Yes. Go ahead and catch `IOException`, and use the `Exception.ToString()` method to get a relatively relevant error message to display. Note that the exceptions generated by the .NET Framework will supply these useful strings, but if you are going ...
The first thing you should change are your calls to StreamWriter and StreamReader to wrap them in a using statement, like this: ``` using (StreamReader reader = file.OpenText()) { List<string> text = new List<string>(); while (!reader.EndOfStream) { text.Add(reader.ReadLine()); } } ``` This will tak...
How to properly handle exceptions when performing file io
[ "", "c#", ".net", "exception", "file-io", "" ]
Is there a way to fall through multiple case statements without stating `case value:` repeatedly? I know this works: ``` switch (value) { case 1: case 2: case 3: // Do some stuff break; case 4: case 5: case 6: // Do some different stuff break; default: // Default st...
There is no syntax in C++ nor C# for the second method you mentioned. There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.
I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing: ``` switch (value) { case 1: case 2: case 3: // Do Something break; case 4: case 5: case 6: // Do Something break; default: ...
Multiple cases in switch statement
[ "", "c#", "switch-statement", "" ]
I have the following code snippet. ``` $items['A'] = "Test"; $items['B'] = "Test"; $items['C'] = "Test"; $items['D'] = "Test"; $index = 0; foreach($items as $key => $value) { echo "$index is a $key containing $value\n"; $index++; } ``` Expected output: ``` 0 is a A containing Test 1 is a B containing Test 2...
Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data: ``` $items[] = array("A", "T...
You can do this: ``` $items[A] = "Test"; $items[B] = "Test"; $items[C] = "Test"; $items[D] = "Test"; for($i=0;$i<count($items);$i++) { list($key,$value) = each($items[$i]); echo "$i $key contains $value"; } ``` I haven't done that before, but in theory it should work.
foreach access the index or an associative array
[ "", "php", "foreach", "" ]
I'm having problems deciding on what is the best way is to handle and store time measurements. I have an app that has a textbox that allows the users to input time in either hh:mm:ss or mm:ss format. So I was planning on parsing this string, tokenizing it on the colons and creating TimeSpan (or using TimeSpan.Parse()...
TimeSpan has an Int64 [Ticks](https://learn.microsoft.com/en-us/dotnet/api/system.timespan.ticks) property that you can store instead, and a [constructor](https://learn.microsoft.com/en-us/dotnet/api/system.timespan.-ctor#System_TimeSpan__ctor_System_Int64_) that takes a Ticks value.
I think the simplest is to just convert user input into a integer number of seconds. So 54:12 == 3252 seconds, so store the 3252 in your database or wherever. Then when you need to display it to the user, you can convert it back again.
Handling and storing elapsed time
[ "", "c#", "database", "datetime", "timespan", "" ]
One of the problems I have come across having complex tasks on the browser is with automatic timeouts. Currently our site has a sliding expiration of 30 minutes. Normally, this isn't a problem because we use asp.net and most of the time the users update one or two fields and then submit the form. This obviously keeps ...
We recently went through this in my organization. Although it is not the best solution, and hitting the right session across multiple browser windows is rough, we put a countdown timer on our page, included a button that just went back and hit the server to restart the session, and also provided the user with a JavaScr...
Have the browser ping the server via Ajax periodically to keep the session alive. Most sites do something useful in this ping, like save a draft of the user's submission.
Automatic Timeout Web Client Use
[ "", "c#", "asp.net", "" ]
I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm jus...
I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will **have** to dig into GTK internals (which are not that complicated). Personal...
Use GtkBuilder instead of Glade, it's integrated into Gtk itself instead of a separate library. The main benefit of Glade is that it's much, much easier to create the interface. It's a bit more work to connect signal handlers, but I've never felt that matters much.
Glade or no glade: What is the best way to use PyGtk?
[ "", "python", "gtk", "pygtk", "glade", "gtk2", "" ]
How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters: ``` $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; ``` You could also use [range()](http://php.net/range) to do this more quickly. Then, in a loop, choose a random number and use it as the index to the `$characters` string to get a random character, and ...
I like this function for the job ``` function randomKey($length) { $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z')); for($i=0; $i < $length; $i++) { $key .= $pool[mt_rand(0, count($pool) - 1)]; } return $key; } echo randomKey(20); ```
Generating (pseudo)random alpha-numeric strings
[ "", "php", "random", "" ]
I have a question on the best way of exposing an asynchronous remote interface. The conditions are as follows: * The protocol is asynchronous * A third party can modify the data at any time * The command round-trip can be significant * The model should be well suited for UI interaction * The protocol supports queries...
For the asynchronous bit, I would suggest checking into `java.util.concurrent`, and especially the `Future<T>` interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would ...
@[Staale](https://stackoverflow.com/questions/37041/exposing-a-remote-interface-or-object-model#37175) It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can't use it to update the UI directly. I could use the iterator to cre...
Exposing a remote interface or object model
[ "", "java", "eclipse", "osgi", "oop", "" ]