Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases: * the thread is holding a critical resource that must be closed properly * the thread has created several other threads that must be killed as well. The nice way of handling this, if you can afford i...
A [`multiprocessing.Process`](https://docs.python.org/library/multiprocessing.html#multiprocessing.Process) can [`p.terminate()`](https://docs.python.org/library/multiprocessing.html#multiprocessing.Process.terminate) In the cases where I want to kill a thread, but do not want to use flags/locks/signals/semaphores/eve...
Is there any way to kill a Thread?
[ "", "python", "multithreading", "python-multithreading", "kill", "terminate", "" ]
I'm using .NET Regular Expressions to strip HTML code. Using something like: ``` <title>(?<Title>[\w\W]+?)</title>[\w\W]+?<div class="article">(?<Text>[\w\W]+?)</div> ``` This works for 99% of the time, but sometimes, when parsing... ``` Regex.IsMatch(HTML, Pattern) ``` The parser just blocks and it will continue ...
Your regex will work just fine when your HTML string actually contains HTML that fits the pattern. But when your HTML does not fit the pattern, e.g. if the last tag is missing, your regex will exhibit what I call "[catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html)". Click that link and s...
With some effort, you can make regex work on html - however, have you looked at the [HTML agility pack](http://www.codeplex.com/htmlagilitypack)? This makes it much easier to work with html as a DOM, with support for xpath-type queries etc (i.e. "//div[@class='article']").
.NET Regular Expressions in Infinite Cycle
[ "", "c#", "vb.net", "visual-studio", "regex", "" ]
Is it possible to do a simple count(\*) query in a PHP script while another PHP script is doing insert...select... query? The situation is that I need to create a table with ~1M or more rows from another table, and while inserting, I do not want the user feel the page is freezing, so I am trying to keep update the cou...
If you're doing a single INSERT...SELECT, then no, you won't be able to get intermediate results. In fact this would be a Bad Thing, as users should never see a database in an intermediate state showing only a partial result of a statement or transaction. For more information, read up on [ACID](http://en.wikipedia.org/...
Without reducing performance? Not likely. With a little performance loss, maybe... But why are you regularily creating tables and inserting millions of row? If you do this only very seldom, can't you just warn the admin (presumably the only one allowed to do such a thing) that this takes a long time. If you're doing t...
Is it possible to do count(*) while doing insert...select... query in mysql/php?
[ "", "php", "mysql", "insert", "" ]
I am in the process of researching/comparing CXF and Spring-WS for web services? I need to function both as a provider and a consumer of WS. In a nutshell, I have been told that Spring-WS is more configurable, but CXF is easier to get up and running. This question is subjective, but will help direct me in my research. ...
I think the biggest difference is Spring-WS is ***only*** 'contract-first' whilst I believe CXF is normally 'contract-last'. <http://static.springsource.org/spring-ws/sites/1.5/reference/html/why-contract-first.html> Contract-last starts with Java code, so it is usually easier to get started with. However, the WSDL ...
About Apache CXF: * CXF supports several standards including SOAP, the WSI Basic Profile, WSDL, WS-Addressing, WS-Policy, WS-ReliableMessaging, WS-Security, WS-SecurityPolicy, and WS-SecureConversation. * Apache CXF offers both contract-last (starting with Java) and Contract-first (starting with the WSDL) approaches. ...
Which framework is better CXF or Spring-WS?
[ "", "java", "web-services", "cxf", "spring-ws", "" ]
How can you find the number of occurrences of a particular character in a string using sql? Example: I want to find the number of times the letter ‘d’ appears in this string. ``` declare @string varchar(100) select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa' ```
Here you go: ``` declare @string varchar(100) select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa' SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count ```
If you want to make it a little more general, you should divide by the length of the thing you're looking for. Like this: ``` declare @searchstring varchar(10); set @searchstring = 'Rob'; select original_string, (len(orginal_string) - len(replace(original_string, @searchstring, '')) / len(@searchstring) from som...
How can you find the number of occurrences of a particular character in a string using sql?
[ "", "sql", "string", "search", "" ]
Is there a way of getting the websites absolute URL (<http://www.domain.com/>) using Java? because I've googled a bit but I only come across with having to make 2 or 3 classes to create that function =/ ### Update: The thing is I am trying to create a crawler that will give me some information and among that I'd like...
I'm assuming you just want the domain from a JSP, however you may find you need the entire URL including the prefix, domain, path and parameters. The easiest way to get this quickly is to use the Request object and build it. Have a look here for more info: <http://www.exforsys.com/tutorials/jsp/jsp-request-object.html...
The question is not really clear, but I'll make the assumption that you are trying to get the path from within a Servlet. ``` String realPath = getServletConfig().getServletContext().getRealPath(relativePath); ```
getUrl using Java
[ "", "java", "url", "geturl", "" ]
I have a form with a `<textarea>` and I want to capture any line breaks in that textarea on the server-side, and replace them with a `<br/>`. Is that possible? I tried setting `white-space:pre` on the `textarea`'s CSS, but it's still not enough.
Have a look at the [`nl2br()`](https://www.php.net/manual/en/function.nl2br.php) function. It should do exactly what you want.
The [`nl2br()`](http://php.net/nl2br) function exists to do exactly this: However, this function adds br tags but does not actually remove the new lines - this usually isn't an issue, but if you want to completely strip them and catch carriage returns as well, you should use a [`str_replace`](http://php.net/str_replac...
Capturing linebreaks (newline,linefeed) characters in a textarea
[ "", "php", "html", "textarea", "line-breaks", "" ]
What are some *common*, *real world examples* of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within o...
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in *Design Patterns*. The reasons you would use it in Java are also applicable to other programming languages as well. As Joshua Bloch states in [Effective ...
When would you use the Builder Pattern?
[ "", "java", "design-patterns", "builder", "" ]
When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.
A famous quote come to mind: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.) But maybe you should not pass large data st...
The number #1 performance tip is to profile your code early and often. There are a lot of general "don't do this" tips but it's really hard to guarantee this will impact the performance of your application. Why? Every application is different. It's easy to say that passing a vector by value is bad if you have a lot of ...
C++ performance tips and rules of thumb anyone?
[ "", "c++", "performance", "cross-platform", "" ]
I have the following very simple Javascript-compatible regular expression: ``` <script type="text/javascript" id="(.+)" src="([^"]+)"> ``` I am trying to match on script tags and gather both the ID and src attributes. I'd like to make the order of the attributes irrelevant, so that the following will still match: ``...
Disclaimer: Be careful with regular expressions and HTML source code. It's brittle and therefore easily broken or circumvented, you should not even think of using it to validate user input. If you are sincere of the source data and know it conforms to the rules of well-formed HTML, you can use this: ``` var html = "v...
That sounds like a nasty regex. IMO, you might be better off using xpath to query the DOM. Or, you could also use the jquery javascript library to select the elements you need.
How to write regex so that patterns can appear in any order?
[ "", "javascript", "regex", "" ]
I want to, from JavaScript, access as a variable the file that is loaded as an image in an img tag. ## I don't want to access its name, but the actual data. The reason for this is that I want to be able to copy it to and from variables so that I can , among other things, change the image without reloading it. Can th...
``` // Download the image data using AJAX, I'm using jQuery var imageData = $.ajax({ url: "MyImage.gif", async: false }).responseText; // Image data updating magic imageDataChanged = ChangeImage(imageData); // Encode to base64, maybe try the webtoolkit.base64.js library imageDataEncoded = Base64Encode(imageDataChange...
If you are using Firefox (and I think Opera and maybe Safari; I can't check right now), you can draw the image on a canvas element and use getImageData. It would work kind of like this: ``` var img = document.getElementById("img_id"); var canvas = document.getElementById("canvas_id"); var context = canvas.getContext(...
Can I access the datafile of an img tag from JavaScript
[ "", "javascript", "html", "image", "" ]
I'm aware of the Substance look and feels and that they have a Office 2007 look-a-like look and feel. But this look and feel doesn't look like the Office 2007 design at all, the colors are a lot different for example. Are there other look and feels which mimic the Office 2007 more accurately?
Look! <http://www.pushing-pixels.org/?p=1010>
I suggest looking at jide software conponents at <http://www.jidesoft.com/>
Is there any (real) Office 2007 look and feel for Java/Swing?
[ "", "java", "swing", "office-2007", "look-and-feel", "" ]
I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An e...
This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish: ``` import re import os r = re.compile(r'\d{2}.+gif$') for root, dirs, files in os.walk('/home/vinko'): l = [os.path.join(root,x) for x in files if r.match(x)] if l: print l #Or append to a g...
1. Read about the [RE](http://www.python.org/doc/2.5.2/lib/module-re.html) pattern's `match` method. 2. Read all answers to [How do I copy files with specific file extension to a folder in my python (version 2.5) script](https://stackoverflow.com/questions/296173/how-do-i-copy-files-with-specific-file-extension-to-a-fo...
How do I search through a folder for the filename that matches a regular expression using Python?
[ "", "python", "regex", "" ]
I am currently faced with a difficult sorting problem. I have a collection of events that need to be sorted against each other (a [comparison sort](http://en.wikipedia.org/wiki/Comparison_sort)) and against their relative position in the list. In the simplest terms I have list of events that each have a priority (inte...
This is actually more than a sorting problem. It's a single-machine scheduling problem with release dates. Depending on what you are trying to do, the problem might be NP-Hard. For example, if you are trying to mimimize the weighted-sum of the completion times (the weight being inversely proportional to the priority), ...
I think: 1. Sort tasks by priority 2. Fit tasks into a time-line, taking the first available slot after their earliestTime, that has a hole big enough for the task. Convert the time-line into a list a tasks, and waits (for the gaps). Questions: 1. Are gaps allowed? 2. Can tasks be split? 3. Given the tasks as in th...
Sorting algorithm for a non-comparison based sort problem?
[ "", "c#", "algorithm", "sorting", "comparison", "mathematical-optimization", "" ]
What is the standard encoding of C++ source code? Does the C++ standard even say something about this? Can I write C++ source in Unicode? For example, can I use non-ASCII characters such as Chinese characters in comments? If so, is full Unicode allowed or just a subset of Unicode? (e.g., that 16-bit first page or what...
Encoding in C++ is quite a bit complicated. Here is my understanding of it. Every implementation has to support characters from the *basic source character set*. These include common characters listed in §2.2/1 (§2.3/1 in C++11). These characters should all fit into one `char`. In addition implementations have to supp...
In addition to litb's post, MSVC++ supports Unicode too. I understand it gets the Unicode encoding from the BOM. It definitely supports code like `int (*♫)();` or `const std::set<int> ∅;` If you're really into code obfuscuation: ``` typedef void ‼; // Also known as \u203C class ooɟ { operator ‼() {} }; ```
Using Unicode in C++ source code
[ "", "c++", "unicode", "character-encoding", "standards", "" ]
Most of my PHP apps have an ob\_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done. ``` ob_start() //Business Logic, etc header->output(); echo apply_post_filter(ob_get_clean()); footer->output(); ``` This ensures that PHP error...
Can't you raise the memory limit? Sounds like the best solution to me. Edit: Obviously, raising the memory limit just because a script tops out should raise some red flags, but it sounds to me like this is a legitimate case - eg. the script is actually producing rather large chunks of output. As such, you have to stor...
You should raise the memory limit before anything, especially if your only other solution is to go through a temporary file. There's all kinds of downsides to using temporary files (mainly, it's slower), and if you really need a way to store the buffer before outputing it, Go look for [memcached](https://www.php.net/m...
How to stop a PHP output buffer from going over the memory limit?
[ "", "php", "memory", "" ]
In my master pages I have `<form ... action="" ...>`, in pre SP1, if I viewed the source the action attribute would be an empty string. In SP1 the action attribute is overridden "MyPage.aspx?MyParams", unfortunately, this causes my postbacks to fail as I have additional pathinfo in the URL (ie. MyPage.aspx\CustomerData...
Great solution from MrJavaGuy but there is a typo in the code because pasting code in the box here doesn't always work correctly. There is a duplication on the WriteAttribute method, corrected code is as follows - ``` public class HtmlFormAdapter : ControlAdapter { protected override void Render(HtmlTextWriter wr...
Maybe you can find the solution here in [this ASP.NET Forum post](http://forums.asp.net/t/1305800.aspx) (Known Issues / Breaking Changes for ASP.NET in .NET 3.5 Service Pack 1). ## Issue The HtmlForm action attribute is now honored when defined in declarative markup. ## Reason 3.5 SP1 added a settable Action proper...
How to prevent ASP.NET 3.5 SP1 from overriding my action?
[ "", "c#", ".net", "asp.net", ".net-3.5", "" ]
What is the best way to change the height and width of an ASP.NET control from a client-side Javascript function? Thanks, Jeff
Because of the name mangling introduced by ASP.NET, I use the function at the bottom to find ASP controls. Once you have the control, you can set the height/width as needed. ``` example usage: <input type='button' value='Expand' onclick='setSize("myDiv", 500, 500);' /> ... function setSize(ctlName, height, width ) ...
You can use the controls .ClientID and some javascript and change it that way. You can do it through CSS height/width or on some controls directly on the control itself.
Can you change the height/width of an ASP.NET control from a Javascript function?
[ "", "asp.net", "javascript", "" ]
I've written an image processing script in php which is run as a cron scheduled task (in OSX). To avoid overloading the system, the script checks the system load (using 'uptime') and only runs when load is below a predefined threshold. I've now ported this over to Windows (2003 Server) and am looking for a similar com...
You can try this at a windows command line. This works in XP, get a lot of other info too. wmic CPU
## Don't use load... The system load is not a good indicator in this case. On Unix it essentially tells you, how many processes are ready and waiting to be executed at the moment. But since there are numerous reasons for why a process might have to wait, your script may actually be able to run without costing another ...
Putting a value on the load of a windows system
[ "", "php", "windows", "macos", "load", "uptime", "" ]
I've seen some posts where jQuery has been favored vs ExtJS. I haven't looked at jQuery in detail, but from what I read so far, jQuery doesn't provide the kind of UI which comes with ExtJS. Am I correct? Why would some of you prefer jQuery in ASP.NET? Thanks
There are two schools of javascript frameworks, ones that focus on widgets (Yui, ext, etc) , and ones that focus on behavior (jquery, prototype, moo, etc) JQuery just makes life easier to build dynamic, sexy sites. If you are just doing system.draggy.droppy asp development, you can ignore both, since you probably aren...
Why not use both? ExtJS does allow you to use jQuery as well. In fact, you can easily configure ExtJS to use jQuery for its core functionality. I've done this before and it works quite well. This way you can happily use the best of both worlds. <http://extjs.com/forum/showthread.php?t=29702&highlight=jquery>
ExtJS and jQuery in ASP.NET
[ "", "javascript", "jquery", "asp.net", "user-interface", "extjs", "" ]
Assuming a largish template library with around 100 files containing around 100 templates with overall more than 200,000 lines of code. Some of the templates use multiple inheritance to make the usage of the library itself rather simple (i.e. inherit from some base templates and only having to implement certain busines...
I'm not sure I see how/why templates are the problem, and why plain non-templated classes would be an improvement. Wouldn't that just mean even *more* classes, less type safety and so larger potential for bugs? I can understand simplifying the architecture, refactoring and removing dependencies between the various cla...
You need automated tests, that way in ten years time when your succesor has the same problem he can refactor the code (probably to add more templates because he thinks it will simplify usage of the library) and know it still meets all test cases. Similarly the side effects of any minor bug fixes will be immediately vis...
How best to switch from template mess to clean classes architecture (C++)?
[ "", "c++", "templates", "simplify", "" ]
1. In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop. 2. I press the red X to close the form. 3. the form closes, but files continue to be created ... I think its on the buttons thread, but shouldnt it be a background one ? t...
The fact that you're using `Application.DoEvents` is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have litt...
Add this form-level variable to your form's code: ``` private bool _StillOpen = true; ``` Then wrap the endless-loop code in your button click like this: ``` while (_StillOpen) { // do whatever your method does Application.DoEvents(); } ``` Finally, add this code to your form's FormClosing event: ``` _Stil...
stopping a function executed on a winform button click
[ "", "c#", "winforms", "multithreading", "" ]
Is it possible for a JPA entity class to contain two embedded (`@Embedded`) fields? An example would be: ``` @Entity public class Person { @Embedded public Address home; @Embedded public Address work; } public class Address { public String street; ... } ``` In this case a `Person` can contai...
If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNamingStrat...
The generic JPA way to do it is with @AttributeOverride. This should work in both EclipseLink and Hibernate. ``` @Entity public class Person { @AttributeOverrides({ @AttributeOverride(name="street",column=@Column(name="homeStreet")), ... }) @Embedded public Address home; @AttributeOverrides({ @At...
JPA Multiple Embedded fields
[ "", "java", "hibernate", "jpa", "jakarta-ee", "" ]
What functionality does the [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield) keyword in Python provide? For example, I'm trying to understand this code**1**: ``` def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: ...
To understand what [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield) does, you must understand what *[generators](https://docs.python.org/3/glossary.html#term-generator)* are. And before you can understand generators, you must understand *[iterables](https://docs.python.org/3/glossary.html#term-ite...
## Shortcut to understanding `yield` When you see a function with `yield` statements, apply this easy trick to understand what will happen: 1. Insert a line `result = []` at the start of the function. 2. Replace each `yield expr` with `result.append(expr)`. 3. Insert a line `return result` at the bottom of the functi...
What does the "yield" keyword do in Python?
[ "", "python", "iterator", "generator", "yield", "" ]
I'm writing C# code that needs to connect to COM events. I implemented the use of IConnectionPointContainer and IConnectionPoint thus: ``` IConnectionPointContainer connectionPointContainer = internalGenerator as IConnectionPointContainer; if (connectionPointContainer == null) { Debug.Fail("T...
I didn't find a way to do this. Eventually I will define another interface in .Net and will write 2 code paths, one for .Net objects and one for real COM objects.
IConnectionPointContainer is implemented on the CCW (COM callable wrapper) that .NET automatically generates when exposing your .NET object as a COM object externally. Try calling [Marshal.GetComInterfaceForObject](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getcominterfaceforobject....
Connect to COM events in C# - support both managed and unmanaged servers
[ "", "c#", "com", "interop", "iconnectionpoint", "" ]
I've created a small python script to toggle between two files I'm using for testing. My question is, what is a good Python format style for the following code: ``` import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(lo...
For the conditional statement, I would probably go with: ``` if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) ``` There's little need to use the inline `y if x else z` in this case, since the surrounding code is simple enough.
The most common naming I've seen is underscode separated words, to\_copy. As for the format style, I've seen no such agreement. I find ``` source = remote if filecmp.cmp(local, config_file) else local shutil.copyfile(source, config_file) ``` to be the clearest among your options. And seeing that everyone prefers t...
What is a good Python format style
[ "", "python", "coding-style", "" ]
Why is it called a single in VB.net? I'm sure there is a good reason but it doesn't seem intuitive to a non formally trained programmer like me.
BPAndrew's question seems to be really "why float in C# and Single in VB.NET", which noone actually answered, so here's my 2p... The use of "float" in C# seems to be a throwback to its C/C++ heritage. "float" still maps to the System.Single type in C#, so the keyword just exists for convenience. You could just as well...
As others have said, they map to "single" and "double" precision binary floating point types. Personally I think it was a sideways step to just name `System.Single` and `System.Double` - why not `System.Float32` and `System.Float64` to match the integer types?
C# Float vs. VB.net Single - Namin' complainin'
[ "", "c#", "vb.net", "naming-conventions", "" ]
I'm looking for a syntax highlighter cum code formatter for my blog on BlogSpot. I've tried several today, but the all want to include `<style>` tags, or reference a stylesheet. I'm looking for one that is ideal for segments of code, and includes styling inline. Any suggestions?
You can always copy the extra few bytes of styling for, say, a [Pygments](http://pygments.org/) highlighter (which really is quite excellent) into the `<head>` of your blog. You don't even need to install any software; just copy the HTML from the online service.
The project referenced above has moved: <http://alexgorbatchev.com/wiki/SyntaxHighlighter> Instructions for using it on Blogger: mlawire.blogspot.com/2009/07/blogger-syntax-highlighting.html
C# syntax highlighter for blogging on BlogSpot
[ "", "c#", "syntax-highlighting", "blogs", "blogspot", "" ]
I have a BasePage class which all other pages derive from: ``` public class BasePage ``` This BasePage has a constructor which contains code which must always run: ``` public BasePage() { // Important code here } ``` I want to force derived classes to call the base constructor, like so: ``` public MyPage :...
The base constructor will always be called at some point. If you call `this(...)` instead of `base(...)` then that calls into another constructor in the same class - which again will have to either call yet another sibling constructor or a parent constructor. Sooner or later you will always get to a constructor which e...
The base class constructor taking no arguments is automatically run if you don't call any other base class constructor taking arguments explicitly.
How can I force the base constructor to be called in C#?
[ "", "c#", "asp.net", "oop", "constructor", "c#-2.0", "" ]
What are my options for running Java 6 on OS X? I have an MacBook Pro Intel Core Duo running Mac OS X 10.4. Do I have any options for running Java 6 on this hardware and OS? Related questions: Which Macs (either current or forthcoming) support 64-bit computing? Are there any Apple laptops (either current or forthcomi...
Since the Core **2** Duo all available Intel macs are 64-bit capable. If your are an early adopter and have just like me a Core Duo-based Intel mac (note the missing 2), your computer is not 64-bit capable (see <http://en.wikipedia.org/wiki/Core_duo>). The first Macbook (Pro) and Mac mini are examples for that. Howev...
People out there are working on getting [OpenJDK](http://openjdk.java.net/) 6 to work on 10.4. I've never tried myself but [soy latte](http://landonf.bikemonkey.org/static/soylatte/), a Mac Os port of the [BSD openjdk port](http://openjdk.java.net/projects/bsd-port/), looks promising. The 10.4 version appears to be 32-...
What are my options for running Java 6 on OS X?
[ "", "java", "macos", "" ]
If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those objects and free the memory they occupied. Since this is the case why then do some objects need to have a destructor or dispose method? Won’t the ...
Finalizers are needed to guarantee the release of scarce resources back into the system like file handles, sockets, kernel objects, etc. Since the finalizer always runs at the end of the objects life, it’s the designated place to release those handles. The `Dispose` pattern is used to provide deterministic destruction...
The previous answers are good but let me emphasize the important point here once again. In particular, you said that > If I understand correctly the .net runtime will always clean up after me. This is only partly correct. In fact, **.NET *only* offers automatic management for one particular resource**: main memory. A...
Since .NET has a garbage collector why do we need finalizers/destructors/dispose-pattern?
[ "", "c#", ".net", "memory", "memory-management", "garbage-collection", "" ]
I saw something about needing to have the assembly available for the type of the first argument passed to the function. I think it is, I can't figure out what am I missing. This code is in a service. I was running the service under the 'NETWORK SERVICES' user account, when I changed the account to that of the session ...
I finally found an answer: it appears that the type given to ApplicationHost.CreateApplicationHost() must be in an assembly located in the GAC. Simple, and stupid :)
copy your binary to the bin folder of your web app will also fix this.
Why does System.Web.Hosting.ApplicationHost.CreateApplicationHost throw System.IO.FileNotFoundException?
[ "", "c#", "" ]
Imagine I have the following: ``` inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] ``` Is there any chance to simplify that doing the same job in just one expression?
You can get what you want platform independently by using [os.path.basename](http://docs.python.org/library/os.path.html#os.path.basename) to get the last part of a path and then use [os.path.splitext](http://docs.python.org/library/os.path.html#os.path.splitext) to get the filename without extension. ``` from os.path...
Answering the question in the topic rather than trying to analyze the example... You really want to use [Florians](https://stackoverflow.com/questions/324132/split-twice-in-the-same-expression#324141) solution if you want to split paths, but if you promise not to use this for path parsing... You can use [re.split()](...
split twice in the same expression?
[ "", "python", "" ]
I have a PHP web application which uses a MySQL database for object tagging, in which I've used the tag structure accepted as the answer to [this SO question](https://stackoverflow.com/questions/20856/how-do-you-recommend-implementing-tags-or-tagging). I'd like to implement a tag hierarchy, where each tag can have a u...
Ali's answer has a link to [Joe Celko's Trees and Hierarchies in SQL for Smarties](http://books.google.co.uk/books?id=6mAAFPTB-9cC), which confirms my suspicion - there isn't a simple database structure that offers the best of all worlds. The best for my purpose seems to be the "Frequent Insertion Tree" detailed in thi...
I implemented it using two columns. I simplify it here a little, because I had to keep the tag name in a separate field/table because I had to localize it for different languages: * tag * path Look at these rows for example: ``` tag path --- ---- database database/ mysql database...
Hierarchical tagging in SQL
[ "", "sql", "mysql", "database", "tags", "normalizing", "" ]
I'm having troubles with HttpWebRequest/HttpWebResponse and cookies/CookieContainer/CookieCollection. The thing is, if the web server does not send/use a "path" in the cookie, Cookie.Path equals the path-part of the request URI instead of "/" or being empty in my application. Therefore, those cookies do not work for th...
Ah, I see what you mean. Generally what browsers *really* do is take the folder containing the document as the path; for ‘/login.php’ that would be ‘/’ so it would effectively work across the whole domain. ‘/potato/login.php’ would be limited to ‘/potato/’; anything with trailing path-info parts (eg. ‘/login.php/’) wou...
Seems like I cannot go any further with the default cookie handler, so I got annoyed and I did it the hard way. Haha. So parsing response.Headers["Set-Cookie"] myself is my solution. Not my preferred one but it works. And I simply eliminated the problem with splitting at the wrong comma using regular expressions. If I...
Problems with HttpWebRequest/HttpWebResponse and cookies
[ "", "c#", ".net", "" ]
Sometimes you have strings that must fit within a certain pixel width. This function attempts to do so efficiently. Please post your suggestions or refactorings below :) ``` function fitStringToSize(str,len) { var shortStr = str; var f = document.createElement("span"); f.style.display = 'hidden'; f.sty...
There are a couple of problems with your code. * Why `/ 5` ? The width of the characters depends on `font-family` and `font-size`. * You must escape `str` in the abbr title (or else an " will make the code invalid). * `diff` is not declared and ends up in the global scope * The `substring` is not supposed to work like...
At a quick glance, it looks good to me. Here are some minor suggestions: * Use a binary search to find the optimal size instead of a linear one. * (optionally) add a mouseover so that a tooltip would give the full string.
Truncate a string nicely to fit within a given pixel width
[ "", "javascript", "text", "reference", "refactoring", "" ]
It looks like the run-time compiler doesn't support the same language as the command-line compiler so if you want to use lambda expressions, extensions methods or LINQ, well, you're stuck. There's more detail here: <http://metadatalabs.com/blog/> Is this correct or is there a work-around? (Short of spawning the comm...
This guy's blog seems to have the answer [CodeDomProviders](http://andersnoras.com/blogs/anoras/archive/2008/04/13/codedomproviders-and-compiler-magic.aspx) Looks like the factory defaults the instance it returns to 2.0. This seems like a pretty crazy technique. Somewhere Paul Graham is crying.
I've been using this, and it seems to work when compiling using .Net 3.5 ``` CodeDomProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } }); ```
Does the .Net run-time compiler support C# 3.0?
[ "", "c#", ".net", "" ]
What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.
Shuffle any `(I)List` with an extension method based on the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle): ``` private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = ...
If we only need to shuffle items in a completely random order (just to mix the items in a list), I prefer this simple yet effective code that orders items by guid... ``` var shuffledcards = cards.OrderBy(_ => Guid.NewGuid()).ToList(); ``` --- As people have pointed out in the comments, GUIDs are not guaranteed to be...
Randomize a List<T>
[ "", "c#", "generic-list", "" ]
I've been using MVC frameworks for a short while now and I really like how the concerns are separated out. I've got into a bad habit of letting the controllers do quite a bit of work. So I'm really looking for some advice. When I first started using MVC I quite often had the controller doing manipulation on the models...
First, there is no set of rules that's going to work in every situation. How you model you're application depends a lot on the type and complexity of the project. Having said that, here are some ideas: 1. Nothing wrong with calling the repository from a controller. Just make sure the controller does not contain busine...
[This](http://channel9.msdn.com/Events/aspConf/aspConf/ASP-NET-MVC-Solution-Best-Practices) video gives great insight into how to organize your asp.net MVC solution and addressing separation of concerns, and better testability. Hopefully it will help someone else also. I learned some good stuff from it.
Service Layers and Repositories
[ "", "c#", "model-view-controller", "repository-pattern", "castle-monorail", "" ]
I've accidentally removed Win2K compatibility from an application by using [GetProcessID](http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx). I use it like this, to get the main HWND for the launched application. ``` ShellExecuteEx(&info); // Launch application HANDLE han = info.hProcess; // Get process c...
There is an 'sort-of-unsupported' function: ZwQueryInformationProcess(): see <http://msdn.microsoft.com/en-us/library/ms687420.aspx> This will give you the process id (amongst other things), given the handle. This isn't guaranteed to work with future Windows versions, so I'd suggest having a helper function that test...
DavidK's right. Please see the comment in the ZwQueryInformationProcess documentation: > [ZwQueryInformationProcess may be > altered or unavailable in future > versions of Windows. Applications > should use the alternate functions > listed in this topic.] That means that Microsoft can choose to remove this at any tim...
Alternative to GetProcessID for Windows 2000
[ "", "c++", "windows", "winapi", "" ]
I have been learning C++ for three months now and in that time created a number of applications for my company. I consider myself fairly comfortable with C++ / MFC and STL, however I don't just want to be an OK programmer, I want to be a good programmer. I have a few books on best practices but I was wondering if anyon...
For C++, [Scott Meyers books](http://www.aristeia.com/books.html) are very good, and will help take you to the next level. If you don't already have it [C++ by Bjarne Stroustrup, 3rd Edition](https://rads.stackoverflow.com/amzn/click/com/0201700735)
I would start with the [Pragmatic Programmer](http://www.pragprog.com/the-pragmatic-programmer), [Code Complete](http://cc2e.com/), [Refactoring](http://www.refactoring.com/) and [Design Patterns](http://www.dofactory.com/Patterns/Patterns.aspx).
Developing as a programmer
[ "", "c++", "mfc", "stl", "" ]
This is kind of a brainteaser question, since the code works perfectly fine as-is, it just irritates my aesthetic sense ever so slightly. I'm turning to Stack Overflow because my own brain is failing me right now. Here's a snippet of code that looks up an address using the Google Maps JS API and places a marker on a m...
The other answers are good, but here's one more option. This allows you to keep the same form you started with but uses the trick of naming your lambda function so that you can refer to it recursively: ``` mapstrings = ['mapstring1', 'mapstring2', 'mapstring3']; geocoder.getLatLng(mapstrings.shift(), function lambda(...
There is an exceedingly nice method for performing recursion in language constructs that don't explicitly support recursion called a *fixed point combinator*. The most well known is the [Y-Combinator](http://en.wikipedia.org/wiki/Fixed_point_combinator). [Here is the Y combinator for a function of one parameter in Jav...
Javascript callback functions and recursion
[ "", "javascript", "recursion", "callback", "" ]
I have two tables A and B. I would like to delete all the records from table A that are returned in the following query: ``` SELECT A.* FROM A , B WHERE A.id = B.a_id AND b.date < '2008-10-10' ``` I have tried: ``` DELETE A WHERE id in ( SELECT a_id FROM B WHERE date < '2008-10-10') ``` but that ...
I think this should work (works on MySQL anyway): ``` DELETE a.* FROM A a JOIN B b ON b.id = a.id WHERE b.date < '2008-10-10'; ``` Without aliases: ``` DELETE A.* FROM A JOIN B ON B.id = A.id WHERE B.date < '2008-10-10'; ```
I'm not sure why your method is failing. If the inner query returns an empty set, then the first query should also return an empty set. I don't think @Fred's solution is right, as he seems to be joining on the wrong column.
How do I delete all the records in a table that have corresponding records in another table
[ "", "sql", "mysql", "sql-server", "" ]
I want to access a MySQL database directly from JavaScript code in an HTML page in Firefox. Does such a library exist? To be very clear, **CGI+Ajax will not work** Some background: I want to create something like a GUI front end for a MySQL database (that's not what it is, but it's close enough). I'm thinking about ...
JavaScript code lives inside the browser. It can make HTTP requests to the outside, but not really much more. So by design you won't be able to bind to a program running locally. If MySQL did expose an HTTP service, it might be possible, but that's not the case. You might be able to find a plugin for Firefox that expo...
Unfortunately you need a server. Or if you know how to and are ready to be platform/browser locked, you could write a plug-in for your browser of choice (as far as I know there is no DLL for Internet Explorer so you'll need to write one yourself). You might want to look into a small server that requires no setup. I mo...
Are there JavaScript bindings for MySQL?
[ "", "javascript", "mysql", "firefox", "" ]
Is it possible for a python script to open its own source file and overwrite it? The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.
That's certainly possible. After the script is loaded/imported, the Python interpreter won't access it anymore, except when printing source line in a exception stack trace. Any pyc file will be regenerated the next time as the source file is newer than the pyc.
If you put most of the code into a module, you could have the main file (which is the one that is run) check the update location, and automatically download the most recent version and install that, before the module is imported. That way you wouldn't have to have a restart of the application to run the most recent ve...
Is it possible for a running python program to overwrite itself?
[ "", "python", "" ]
Is it advisable to use arrays in Javascript using tens of thousands of indexes? I have a database which contains a table of static data, meaning that it will never change. In this case would it be advisable to convert this table to a javascript array and look the info up in there when needed? Is this bad practice? Th...
No. I'd keep the table, as its a single point of maintenance. You'll find that doing a XmlHTTPRequest to return a key/value pair based on a server side query, would actually perform faster, and have significantly less memory footprint than a huge JavaScript array.
In my experience, moving beyond a few thousand lines in an array cached client-side in a browser led to hellish experiences. Bloated browser memory footprints, slow load times and general sluggishness were the order of the day. You should test this scenario yourself for the experience. It's worth the few minutes it'd t...
Is it advisable to use arrays in Javascript using tens of thousands of indexes?
[ "", "javascript", "performance", "arrays", "" ]
I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. Then the ouput of the file would be the absolute path of the chosen file. Thanks in advance,
You can use the [JFileChooser](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html) class, check [this example](http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm).
I ended up using this quick piece of code that did exactly what I needed: ``` final JFileChooser fc = new JFileChooser(); fc.showOpenDialog(this); try { // Open an input stream Scanner reader = new Scanner(fc.getSelectedFile()); } ```
How to browse for a file in java swing library?
[ "", "java", "swing", "file", "" ]
I'm learning traditional Relational Databases (with [PostgreSQL](http://www.postgresql.org/)) and doing some research I've come across some new types of databases. [CouchDB](http://couchdb.apache.org/), [Drizzle](https://launchpad.net/drizzle), and [Scalaris](http://www.zib.de/CSR/Projects/scalaris/) to name a few, wha...
I would say next-gen *database*, not next-gen SQL. SQL is a language for querying and manipulating relational databases. SQL is dictated by an international standard. While the standard is revised, it seems to always work within the relational database paradigm. Here are a few new data storage technologies that are g...
I'm missing **graph databases** in the answers so far. A graph or network of objects is common in programming and can be useful in databases as well. It can handle semi-structured and interconnected information in an efficient way. Among the areas where graph databases have gained a lot of interest are semantic web and...
The Next-gen Databases
[ "", "sql", "database", "nosql", "non-relational-database", "" ]
I have got a table in MS Access 2007 with 4 fields. * Labour Cost * Labour Hours * Vat * Total How do I multiply 'Labour Hours' by 'Labour Cost' add the 'VAT' and display the answer in 'Total' Where would I put any formulas?, in a form or query or table ?
There is also the dummies (ie not SQL) way to do it: First delete your total column from your table and for this exercise pretend that the name of your table is "Labour" . Now create a new query and view it in design view, add all the fields from your Labour table (so you can check that everything is working), select ...
You don't need the "Total" column in all probability. Your queries or reports will probably resemble this: ``` SELECT [Total] = [Labour Cost] * [Labour Hours] + [VAT] ``` You can use the same sort of formula in controls on your forms or reports.
MS Access multiply fields
[ "", "sql", "ms-access", "calculated-columns", "" ]
I have an input file that I want to sort based on timestamp which is a substring of each record. I want to store multiple attributes of the The list is currently about 1000 records. But, I want it to be able to scale up a bit just in case. When I did it with a Linked List by searching the entire list for insertion it...
Sorting a linked-list will inherently be either O(N^2) or involve external random-access storage. Vectors have random access storage. So do arrays. Sorting can be O(NlogN). At 1000 elements you will begin to see a difference between O(N^2) and O(NlogN). At 1,000,000 elements you'll definitely notice the difference! ...
I'm not sure I understood your question correctly, is your problem defining the sort functor? The STL sort is generally implemented as an introspective sort which is very good for most of the cases. ``` struct sort_functor { bool operator()(const CFileInfo & a, const CFileInfo & b) const { // may be a...
C++ sorting a vector or linked list
[ "", "c++", "algorithm", "" ]
We are deciding the naming convention for tables, columns, procedures, etc. at our development team at work. The singular-plural table naming *has already been decided*, we are using singular. We are discussing whether to use a prefix for each table name or not. I would like to read suggestions about using a prefix or ...
I prefer prefixing tables and other database objects with a short name of the application or solution. This helps in two potential situations which spring to mind: 1. You are less likely to get naming conflicts if you opt to use any third-party framework components which require tables in your application database (e...
I find hungarian DB object prefixes to indicate their types rather annoying. I've worked in places where every table name had to start with "tbl". In every case, the naming convention ended up eventually causing much pain when someone needed to make an otherwise minor change. For example, if your convention is that t...
Should we use prefixes in our database table naming conventions?
[ "", "sql", "database", "naming-conventions", "" ]
All, this is my code ``` //declare string pointer BSTR markup; //initialize markup to some well formed XML <- //declare and initialize XML Document MSXML2::IXMLDOMDocument2Ptr pXMLDoc; HRESULT hr; hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40)); pXMLDoc->async = VARIANT_FALSE; pXMLDoc->validateOnParse ...
Try replacing ``` BSTR Markup; ``` with ``` bstr_t Markup; ``` BSTR is pretty much a dumb pointer, and I think that the return result of GetXML() is being converted to a temporary which is then destroyed by the time you get to see it. bstr\_t wraps that with some smart-pointer goodness... Note: Your "SuperMarkup...
Ok, I think Patrick is right. I took your code and made a quick ATL EXE project named getxmltest. I added this line after #include directives ``` #import "MSXML3.DLL" ``` removed the post-build event which registers the component because I dont want to expose any component from the exe but only have all ATL headers a...
MSXML2::IXMLDOMDocument2Ptr->GetXML() messing up my string!
[ "", "c++", "msxml", "" ]
I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images. PIL does not work, as it can't read PDFs. The two options I've found are using eithe...
[ImageMagick](https://www.imagemagick.org/script/index.php) has [Python bindings](http://www.imagemagick.org/download/python/).
Here's whats worked for me using the python ghostscript module (installed by '$ pip install ghostscript'): ``` import ghostscript def pdf2jpeg(pdf_input_path, jpeg_output_path): args = ["pdf2jpeg", # actual value doesn't matter "-dNOPAUSE", "-sDEVICE=jpeg", "-r144", ...
Converting a PDF to a series of images with Python
[ "", "python", "pdf", "imagemagick", "jpeg", "python-imaging-library", "" ]
We are looking at various options in porting our persistence layer from Oracle to another database and one that we are looking at is MS SQL. However we use Oracle sequences throughout the code and because of this it seems moving will be a headache. I understand about @identity but that would be a massive overhaul of th...
That depends on your current use of sequences in Oracle. Typically a sequence is read in the Insert trigger. From your question I guess that it is the persistence layer that generates the sequence before inserting into the database (including the new pk) In MSSQL, you can combine SQL statements with ';', so to retrie...
I did this last year on a project. Basically, I just created a table with the name of the sequence, current value, & increment amount. Then I created a 4 procs : * GetCurrentSequence( sequenceName) * GetNextSequence( sequenceName) * CreateSequence( sequenceName, startValue, incrementAmount) * DeleteSequence( sequence...
Is it possible in SQL Server to create a function which could handle a sequence?
[ "", "sql", "sql-server", "oracle", "sequence", "" ]
I'm building a GUI class for C++ and dealing a lot with pointers. An example call: ``` mainGui.activeWindow->activeWidget->init(); ``` My problem here is that I want to cast the **activeWidget** pointer to another type. **activeWidget** is of type GUI\_BASE. Derived from BASE I have other classes, such as GUI\_BUTTON...
The problem is that casts have lower precedence than the . -> () [] operators. You'll have to use a C++ style cast or add extra parentheses: ``` ((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function(); // Extra parentheses dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function(); // C++ styl...
You should not be using the C style cast. You need to use the C++ dynamic cast. This will then allow you to test that the object is actually a GUI\_TEXTBOX before you call the method on it. ``` GUI_TEXTBOX* textboxPointer = dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget); if (textboxPointer) { //...
What am I doing wrong with this pointer cast?
[ "", "c++", "pointers", "" ]
I recently came across this in some code - basically someone trying to create a large object, coping when there's not enough heap to create it: ``` try { // try to perform an operation using a huge in-memory array byte[] massiveArray = new byte[BIG_NUMBER]; } catch (OutOfMemoryError oome) { // perform the ...
freeMemory isn't quite right. You'd also have to add maxMemory()-totalMemory(). e.g. assuming you start up the VM with max-memory=100M, the JVM may at the time of your method call only be using (from the OS) 50M. Of that, let's say 30M is actually in use by the JVM. That means you'll show 20M free (roughly, because we'...
I don't believe that there's a reasonable, generic approach to this that could safely be assumed to be 100% reliable. Even the Runtime.freeMemory approach is vulnerable to the fact that you may actually have enough memory after a garbage collection, but you wouldn't know that unless you force a gc. But then there's no ...
Java: enough free heap to create an object?
[ "", "java", "" ]
I'm trying to "single source" a form page which can be in edit mode or view mode. For various reasons, this isn't using the ASP.Net FormView or DetailsView controls. Since there is no way to disable a textbox without turning its contents gray (well, we could "eat" all of the keystrokes into it, but that isn't very ele...
This may not suit your needs, but it's a possibility. `<input>` and `<textarea>` tags support the read-only property. The behavior of read-only fields is slightly different than disabled. Here's what the [HTML 4.01 Recommendation](http://www.w3.org/TR/html401/) says: > When set, the readonly attribute has the followi...
Why not use an edit in place plugin like [Jeditable](http://www.appelsiini.net/projects/jeditable). This way you can generate your view mode and have each field editable at the click of a button.
How can I switch a text box for a <label>, <div>, or <span> using jQuery?
[ "", "asp.net", "javascript", "jquery", "html", "" ]
I'm attempting to use the following code to serialize an anonymous type to JSON: ``` var serializer = new DataContractJsonSerializer(thing.GetType()); var ms = new MemoryStream(); serializer.WriteObject(ms, thing); var json = Encoding.Default.GetString(ms.ToArray()); ``` However, I get the following exception when th...
Try the JavaScriptSerializer instead of the DataContractJsonSerializer ``` JavaScriptSerializer serializer = new JavaScriptSerializer(); var output = serializer.Serialize(your_anon_object); ```
As others have mentioned, [Newtonsoft JSON.NET](http://james.newtonking.com/projects/json-net.aspx) is a good option. Here is a specific example for simple JSON serialization: ``` return JsonConvert.SerializeObject( new { DataElement1, SomethingElse }); ``` I have found it to be a very flexi...
How do I serialize a C# anonymous type to a JSON string?
[ "", "c#", "json", "anonymous-types", "datacontractjsonserializer", "json-serialization", "" ]
I am currently running the following code based on Chapter 12.5 of the Python Cookbook: ``` from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(s...
I looks to me as if you do not need any DOM capabilities from your program. I would second the use of the (c)ElementTree library. If you use the iterparse function of the cElementTree module, you can work your way through the xml and deal with the events as they occur. Note however, Fredriks advice on using cElementTr...
Have you tried the `cElementTree` module? `cElementTree` is included with Python 2.5 and later, as xml.etree.cElementTree. Refer the [benchmarks](http://effbot.org/zone/celementtree.htm). Note that since Python 3.3 `cElementTree` is used as the default implementation so this change is not needed with a Python version...
What is the fastest way to parse large XML docs in Python?
[ "", "python", "xml", "performance", "parsing", "" ]
I am developing a Java desktop application and would like to have an external configuration.xml. I am developing the application using Netbeans and tried to add the configuration.xml file in the dist directory so that it resides in the application work folder. But when Netbeans executes its clean operation it deletes...
You can add this to your build.xml : ``` <target name="-post-jar"> <copy todir="${dist.jar.dir}"> <fileset dir="resources" includes="**"/> </copy> </target> ``` You can now put your configuration.xml file in the folder 'resources' (that you need to create) in your project and all files in it will...
I was able to get this to work, but I couldn't get -post-jar to trigger without explicitly entering it as a dependency in the main build config. This is in Netbeans 7.0.1 for a Rich Client project. Instead, in build.xml for the Netbeans module where I want to have external resource files (mainly .txt files that the us...
Netbeans and external configuration files
[ "", "java", "netbeans", "external", "resources", "" ]
A while ago, I had a discussion with a colleague about how to insert values in STL [maps](http://www.sgi.com/tech/stl/Map.html). I preferred `map[key] = value;` because it feels natural and is clear to read whereas he preferred `map.insert(std::make_pair(key, value))`. I just asked him and neither of us can remember t...
When you write ``` map[key] = value; ``` there's no way to tell if you **replaced** the `value` for `key`, or if you **created** a new `key` with `value`. [`map::insert()`](http://en.cppreference.com/w/cpp/container/map/insert) will only create: ``` using std::cout; using std::endl; typedef std::map<int, std::strin...
The two have different semantics when it comes to the key already existing in the map. So they aren't really directly comparable. But the operator[] version requires default constructing the value, and then assigning, so if this is more expensive then copy construction, then it will be more expensive. Sometimes defaul...
In STL maps, is it better to use map::insert than []?
[ "", "c++", "dictionary", "stl", "insert", "stdmap", "" ]
What are the proper uses of: * [`static_cast`](https://en.cppreference.com/w/cpp/language/static_cast) * [`dynamic_cast`](https://en.cppreference.com/w/cpp/language/dynamic_cast) * [`const_cast`](https://en.cppreference.com/w/cpp/language/const_cast) * [`reinterpret_cast`](https://en.cppreference.com/w/cpp/language/re...
## `static_cast` `static_cast` is the first cast you should attempt to use. It does things like implicit conversions between types (such as `int` to `float`, or pointer to `void*`), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating `static_cast` isn't necessary, b...
* Use `dynamic_cast` for converting pointers/references within an inheritance hierarchy. * Use `static_cast` for ordinary type conversions. * Use `reinterpret_cast` for low-level reinterpreting of bit patterns. Use with extreme caution. * Use `const_cast` for casting away `const/volatile`. Avoid this unless you are stu...
When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?
[ "", "c++", "pointers", "casting", "c++-faq", "" ]
I have a List containing several keywords. I foreach through them building my linq query with them like so (boiled down to remove the code noise): ``` List<string> keys = FillKeys() foreach (string key in keys){ q = q.Where(c => c.Company.Name.Contains(key)); } ``` When I now make my keys contain 2 keys that retu...
You're reusing the same variable (`key`) in your lambda expression. See my article on [anonymous methods](http://pobox.com/~skeet/csharp/csharp2/delegates.html#anonymous.methods) for more details, and there are a number of related SO questions too: * [LINQ to SQL bug (or very strange feature)...](https://stackoverflo...
Possibly a captured variable issue; try adding: ``` List<string> keys = FillKeys() foreach (string key in keys){ string tmp = key; q = q.Where(c => c.Company.Name.Contains(tmp)); } ```
Linq query built in foreach loop always takes parameter value from last iteration
[ "", "c#", "linq", "" ]
I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?
Note: Browsers can block access to `window.top` due to [same origin policy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript). IE bugs also take place. Here's the working code: ``` function inIframe () { try { return window.self !== window.top; } catch (e) { ...
When in an iframe on the same origin as the parent, the [`window.frameElement`](https://devdocs.io/dom/window/frameelement) method returns the element (e.g. `iframe` or `object`) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, ...
How to identify if a webpage is being loaded inside an iframe or directly into the browser window?
[ "", "javascript", "facebook", "iframe", "" ]
I'm working with some example java code for making md5 hashes. One part converts the results from bytes to a string of hex digits: ``` byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0;i<messageDigest.length;i++) { hexString.append(Integer.toHexString(0xFF & ...
A simple approach would be to check how many digits are output by `Integer.toHexString()` and add a leading zero to each byte if needed. Something like this: ``` public static String toHexString(byte[] bytes) { StringBuilder hexString = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { Str...
Check out [Hex.encodeHexString](https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Hex.html#encodeHexString-byte:A-) from [Apache Commons Codec](https://commons.apache.org/proper/commons-codec/). ``` import org.apache.commons.codec.binary.Hex; String hex = Hex.encodeHexString(byte...
In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?
[ "", "java", "md5", "hex", "" ]
In relation to [another question](https://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated), how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\fo...
Simple answer: You work out the absolute path based on the environment. What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows). So,...
If your file is always in the same directory as your program then: ``` def _isInProductionMode(): """ returns True when running the exe, False when running from a script, ie development mode. """ return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe ...
Accounting for a changing path
[ "", "python", "file", "path", "" ]
I the following styles: ``` a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.buttonMouseover { background-color: darkGoldenRod; margin: .2cm; padding...
Depending on your target browsers, you could use the `hover` pseudo tag. ``` a.button { background-color: orange; margin: .2cm; padding: .2cm; color: black; font-family: sans-serif; text-decoration: none; font-weight: bold; border: solid #000000; } a.button:hover { background-color...
sblundy has the basics right. To add to that, all modern browsers will allow you to use the hover pseudo element on the <a> however IE6 won't recognise this on any other element. In IE6 you would need some sort of JavaScript to add a class name when you hover. I like using jQuery, and the way I would do it like that i...
What is the simplest way to implement mouseover background color change for HTML elements?
[ "", "javascript", "html", "" ]
I'm thinking how to arrange a deployed python application which will have a 1. Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in 2. A library installed to wherever the current site-packages directory is. Now, currently, I have the following directory structure in my sourc...
[This article](http://jcalderone.livejournal.com/39794.html) is pretty good, and shows you a good way to do it. The second item from the *Do* list answers your question. *shameless copy paste:* > # Filesystem structure of a Python project > > *by [Jp Calderone](http://jcalderone.livejournal.com/profile)* > > **Do:** ...
[Distutils](http://www.python.org/doc/2.5.2/dist/dist.html) supports installing modules, packages, and scripts. If you create a distutils `setup.py` which refers to `foo` as a package and `foo.py` as a script, then `foo.py` should get installed to `/usr/local/bin` or whatever the appropriate script install path is on t...
Deploying a python application with shared package
[ "", "python", "naming", "package", "conventions", "deploying", "" ]
* How do I utilize a ?: operator in the SELECT clause of a LINQ query? If this can't be done, how can I emulate one? The goal is to get a CASE block in my select clause. As you might suspect, I'm getting an error: *Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignmen...
When creating an anonymous type (what you're doing with the "new" without specifying a type) you have to specify the member name for each property. From your example, it would look something like this: (also fixed your joins) ``` var query = from a in db.tblActivities join i in db.tblIPs on a.ipid equals i...
You have to use the join keyword, and define the relationship between the entities in order to make a proper inner join. [Here](http://msdn.microsoft.com/en-us/library/bb397941.aspx) you can find some examples about that, I also highly recommend you to get [LinqPad](http://www.linqpad.net/), its a really valuable tool...
?: Operator in LINQ Query
[ "", "c#", "linq", "linq-to-sql", "" ]
I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet Which would you recommend and why?
As Tony said, this is really going to depend on your goals. If you're "tinkering" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to "raw" 3D programming using Python. On the other hand, if yo...
Start with pyglet. It contains the best high-level API, which contains all you need to get started, from opening a window to drawing sprites and OpenGL primitives using their friendly and powerful Sprite and Batch classes. Later, you might also want to write your own lower-level code, that makes calls directly to Open...
PyOpenGl or pyglet?
[ "", "python", "pyglet", "pyopengl", "" ]
The following code does not compile: ``` public class GenericsTest { public static void main(String[] args) { MyList<?> list = new MyList<Object>(); Class<?> clazz = list.get(0); // Does not compile with reason // "Type mismatch: cannot convert from Object to Class" My...
I think you are not understanding quite how generics work. ``` MyList<?> list = new MyList<Object>(); Class<String> clazz= list.get(0); ``` This code snippet does not compile because you are telling the compiler that `list` is going to hold `Class<Object>` types - and then in the next line you are expecting it to ret...
I don't have a compiler on this machine, but this should work. ``` public class GenericsTest { public static void main(String[] args) { MyList<Object> list = new MyList<Object>(); Class<?> clazz= list.get(0); } static class MyList<T> extends ArrayList<Class<? extends T>> { } } ``...
Introducing generics to Java code without breaking the build
[ "", "java", "generics", "" ]
I have a few ASP.Net database front-end websites where MS Access is the back-end. I am trying to use ASP.Net dynamic data website. Should I change this database to SQL Server Express or something else to make it easier or should this work from with MS Access.
Pick SQL Express for these reasons: 1. **Scaling**: MS Access will never scale. Once you get over about 10 concurrent connections you will start to see trouble. SQL Express will scale. You can always move SQL Express up to a full-blow SQL Server installation. While this is somewhat true of Access, some of your SQL sta...
A Jet back end will work fine for mostly read-only websites, even ones with decent traffic. Michael Kaplan's old website, <http://trigeminal.com>, uses a Jet database as the back end, and back when it was his primary site (he's since been hired by Microsoft), he said it was getting over 100K hits per day, and was holdi...
SQL Server Express / MS Access LINQ Features, Which One to Use?
[ "", "c#", "asp.net", "sql-server", "linq", "ms-access", "" ]
I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query. Here is my query at the moment: ``` var items = db.InventoryItem .Include("Kind") .Include("PropertyValues") .Include("PropertyValues.KindProperty") .Where(i...
You need to either use this one: ``` .Where(string.Format("it.ID in {0}", string.Join(",", valueIds.ToArray()))); ``` or construct the WHERE part dynamically, as in [this](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3917617&SiteID=1) post. ## P.S. - Information has been updated and this answer updated as f...
You can use Linq's `Any` extension method for this in some cases: ``` var userIds = new[] { 1, 2, 3 }; from u in Users where userIds.Any(i => i==u.Id) select u; ``` The generated SQL looks pretty strange in such a case, but like much Linq-to-Entities generated SQL it might be overly verbose for a human, bu...
How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported?
[ "", "c#", "linq", "entity-framework", "linq-to-entities", "" ]
Let's say I have **a `List` object** and **an iterator** for that list. Now I sort the list with `java.util.Collections.sort()` * What happens to the iterator? * Is its behavior still defined and can it still be used? * If not, can I prevent destroying the iterators for the list? I know, this problem could be circum...
Most of the collections in `java.util` are "fail-fast" and **may** throw a [`ConcurrentModificationException`](http://java.sun.com/javase/6/docs/api/java/util/ConcurrentModificationException.html) if the underlying collection is changed. It should be pointed out that this is intended for debugging and so is not guarant...
Iterators are generally invalid after *any* modification to their underlying collections, except via the iterator itself. (For instance, [`ListIterator`](http://java.sun.com/javase/6/docs/api/java/util/ListIterator.html) allows for insertion and removal.) I'd certainly expect any iterators to become invalidated after ...
When I sort a List what happens to its iterators?
[ "", "java", "collections", "concurrency", "" ]
Are DES Encryption called "One Way Encryption" or "two way Encryption" ? Are there a PHP class or method to decrypt the DES Encryption ?
The php [crypt](https://www.php.net/crypt) function is a one-way hashing function, if you want to be able to decrypt, take a look at the [mcrypt](https://www.php.net/manual/en/book.mcrypt.php) extension which supports [a range of algorithms](https://www.php.net/manual/en/mcrypt.ciphers.php)
It should be noted that there are (and have always been) questions surrounding the [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard) algorithm. It's been widely in use for a long time, but since it was originally specified with only a 56 bit key, it's questionable whether it's secure enough for any important...
PHP class or method to decrypt the DES Encryption
[ "", "php", "encryption", "des", "" ]
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file: ``` $doc->addChild('myToken'); ``` This generates (what I know as) a self-closing or single tag: ``` <myToken/> ``` However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need...
From the documentation at [SimpleXMLElement->\_\_construct](http://www.php.net/manual/en/function.simplexml-element-construct.php) and [LibXML Predefined Constants](https://www.php.net/manual/en/libxml.constants.php), I think this should work: ``` <?php $sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG); // so...
If you set the value to something empty (i.e. null, empty string) it will use open/close brackets. ``` $tag = '<SomeTagName/>'; echo "Tag: '$tag'\n\n"; $x = new SimpleXMLElement($tag); echo "Autoclosed: {$x->asXML()}\n"; $x = new SimpleXMLElement($tag); $x[0] = null; echo "Null: {$x->asXML()}\n"; $x = new SimpleXM...
Turn OFF self-closing tags in SimpleXML for PHP?
[ "", "php", "xml", "simplexml", "" ]
I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes `XmlElement` and `XmlIgnore` to manipulate the serialization of the object. If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably vi...
I've got an answer for the second part: ["Attributes that control XML serialization"](http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx). Still investigating the first part... EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which inclu...
The only way I've found to do this is via XSD. What you can do is validate while you deserialize: ``` static T Deserialize<T>(string xml, XmlSchemaSet schemas) { //List<XmlSchemaException> exceptions = new List<XmlSchemaException>(); ValidationEventHandler validationHandler = (s, e) => { //you coul...
Can I fail to deserialize with XmlSerializer in C# if an element is not found?
[ "", "c#", "xml", "xml-serialization", ".net-attributes", "" ]
I've got a popup div showing on rightclick (I know this breaks expected functionality but Google Docs does it so why not?) However the element I'm showing my popup on has a "title" attribute set which appears over the top of my div. I still want the tooltip to work but not when the popup is there. What's the best way ...
With [jquery](http://jquery.com) you could bind the hover function to also set the title attribute to blank onmouseover and then reset it on mouse out. ``` $("element#id").hover( function() { $(this).attr("title",""); $("div#popout").show(); }, function() { $("div#popout").hide(); $(this).attr("title",origi...
Here is another example of how it can be done by using [`data`](http://api.jquery.com/data/) for value storage and [`prop`](http://api.jquery.com/prop/) for value assigning ``` $('[title]').on({ mouseenter : function() { $(this).data('title', this.title).prop('title', ''); }, mouseleave: functi...
How to stop title attribute from displaying tooltip temporarily?
[ "", "javascript", "jquery", "html", "" ]
I need to store a double as a string. I know I can use `printf` if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the *value*, not the *key*).
The *boost (tm)* way: ``` std::string str = boost::lexical_cast<std::string>(dbl); ``` The *Standard C++* way: ``` std::ostringstream strs; strs << dbl; std::string str = strs.str(); ``` **Note**: Don't forget `#include <sstream>`
``` // The C way: char buffer[32]; snprintf(buffer, sizeof(buffer), "%g", myDoubleVar); // The C++03 way: std::ostringstream sstream; sstream << myDoubleVar; std::string varAsString = sstream.str(); // The C++11 way: std::string varAsString = std::to_string(myDoubleVar); // The boost way: std::string varAsString = b...
How do I convert a double into a string in C++?
[ "", "c++", "string", "double", "" ]
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this? * Time between calculations? * Current state of the CPU? * Differe...
From what I understand you're only guaranteed identical results provided that you're dealing with the same instruction set and compiler, and that any processors you run on adhere strictly to the relevant standards (ie IEEE754). That said, unless you're dealing with a particularly chaotic system any drift in calculation...
The short answer is that FP calculations are entirely deterministic, as per the [IEEE Floating Point Standard](http://en.wikipedia.org/wiki/IEEE_754), but that doesn't mean they're entirely reproducible across machines, compilers, OS's, etc. The long answer to these questions and more can be found in what is probably ...
How deterministic is floating point inaccuracy?
[ "", "c#", "math", "silverlight", "floating-point", "deterministic", "" ]
Does anyone know how to modify the content of the Excel ribbon at runtime with VSTO 2005SE? Not only update labels or dynamic menus, but also add or remove buttons, tabs, groups, drop downs etc. At runtime means not only at my add-in startup, but also during work with Excel.
I agree with Mike, working with the visibility callback on controls or groups is probably your best bet (that's what we are using). The entire ribbon layout is loaded from an XML string. I don't know if it is possible to trigger a reload of the XML, which you could then customize to load different XML content.
Irrespective of VS version, I don't think all that you want is actually possible with the current version of the RibbonX control\*. Specifically, there's no functionality for adding and removing. You *can* control visibility, though, so you can put everything in by default and make it visible or otherwise as needed. \...
Add Excel ribbon controls at runtime (VSTO 2005SE)
[ "", "c#", "excel", "vsto", "" ]
I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions: 1. How easy is it to transition from one DB (SQLit...
3) Is quite an interesting question. In general, SQLite is pretty useless for web-based stuff. It scales fairly well for size, but scales terribly for concurrency, and so if you are planning to hit it with a few requests at the same time, you will be in trouble. Now your idea in part 3) of the question is to use multi...
Your success with createTable() will depend on your existing underlying table schema / data types. In other words, how well SQLite maps to the database you choose and how SQLObject decides to use your data types. The safest option may be to create the new database by hand. Then you'll have to deal with data migration,...
Database change underneath SQLObject
[ "", "python", "mysql", "database", "sqlite", "sqlobject", "" ]
I don't even know where to go with this. Google wasn't very helpful. As with my previous question. I'm using TextMate's Command+R to compile the project. > game.h:16:error: declaration of ‘Player\* HalfSet::Player() const’ > > players.h:11:error: changes meaning of ‘Player’ from ‘class Player’ > > game.h:21:error: ‘Pl...
In C++ you cannot name a function the same name as a class/struct/typedef. You have a class named "Player" and so the HalfSet class has a function named "Player" ("Player \*Player()"). You need to rename one of these (probably changing HalfSet's Player() to getPlayer() or somesuch).
Your problem is that names are looked up in scopes. Within the declaration of `HalfSet::setPlayer(Player*)`, the unqualified name `Player` needs to be looked up. The first scope tried is `class HalfSet`. In that scope, the lookup of `Player` finds function `HalfSet::Player`, not `global class ::Player`. The solution i...
C++ odd compile error: error: changes meaning of "Object" from class "Object"
[ "", "c++", "xcode", "" ]
Below is my (simplified) schema (in MySQL ver. 5.0.51b) and my strategy for updating it. There has got to be a better way. Inserting a new item requires 4 trips to the database and editing/updating an item takes up to **7**! **items**: itemId, itemName **categories**: catId, catName **map**: mapId\*, itemId, cat...
Steps 6 & 7 can be combined easily enough: ``` DELETE categories.* FROM categories LEFT JOIN map USING (catId) WHERE map.catID IS NULL; ``` Steps 3 & 4 can also be combined: ``` INSERT IGNORE INTO map (mapId, itemId, catId) SELECT CONCAT('1|', c.catId), 1, c.catID FROM categories AS c WHERE c.catName IN(...
There are a number of things you can do to make a bit easier: * Read about [`INSERT...ON DUPLICATE KEY UPDATE`][1] * Delete old categories before you insert new categories. This may benefit from an index better. `DELETE FROM map WHERE itemId=2`; * You probably don't need `map.mapID`. Instead, declare a compound pri...
Updating an associative table in MySQL
[ "", "sql", "mysql", "database", "" ]
I've inherited a rather large application that really could use some cleanup. There is data access code littered throughout the application. In code behinds, some in business logic classes, some inline in in classic asp pages. What I'd like to do is refactor this code, removing all the data access code into a few DAL ...
If you have access to .NET Framework 3.5 and Linq to SQL, you can do it very easily, check this video: [LINQ to SQL: Using Stored Procedures](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx) > Using existing stored procedures and > functions is easy wi...
I recommend you get a hold of Code Smith. The product includes a template for ORM and fully supports generating classes from DB Schemas (and I think Procs). You can then Code Gen all the objects you need. Another option would be to use LINQ to SQL.
Automatically create C# wrapper classes around stored procedures
[ "", "c#", "sql-server", "stored-procedures", "orm", "" ]
Create a flat text file in c++ around 50 - 100 MB with the content 'Added first line' should be inserted in to the file for 4 million times
using old style file io **fopen** the file for write. **fseek** to the desired file size - 1. **fwrite** a single byte **fclose** the file
The fastest way to create a file of a certain size is to simply create a zero-length file using `creat()` or `open()` and then change the size using `chsize()`. This will simply allocate blocks on the disk for the file, the contents will be whatever happened to be in those blocks. It's very fast since no buffer writing...
Fastest way to create large file in c++?
[ "", "c++", "file-io", "iostream", "bulkinsert", "" ]
I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =< only. Here is the code I have: ``` var oImg = document.createElement("img"); oImg.se...
``` oImg.setAttribute('width', '1px'); ``` `px` is for CSS only. Use either: ``` oImg.width = '1'; ``` to set a width through HTML, or: ``` oImg.style.width = '1px'; ``` to set it through CSS. Note that old versions of IE don't create a proper image with `document.createElement()`, and old versions of KHTML don't...
``` var img = new Image(1,1); // width, height values are optional params img.src = 'http://www.testtrackinglink.com'; ```
What is the best JavaScript code to create an img element
[ "", "javascript", "dhtml", "" ]
In visual studio 2008, when we press Ctrl+F5, the ASP.NET Development Server is launched to simulate a Web Server. I'm wondering what server does it simulate? IIS6 or IIS7? Is it possible to customize what server it simulate?
It doesn't simulate a server as such, it runs on a server based on cassini that is written in .net and has source code available. I suppose it's more similar to IIS6 in that it does not support the IIS7 integrated pipeline feature. You can always choose to have VS use II6 or IIS7 if it's installed (depending on whether...
I don't think it "simulates" either, tbh, it just a web server for local development where IIS is not an option, based off [Cassini](http://www.asp.net/Downloads/archived/cassini/). More information [here](http://msdn.microsoft.com/en-us/library/58wxa9w5(VS.80).aspx).
ASP.NET Development Server simulates IIS6 or IIS7?
[ "", "c#", "asp.net", "visual-studio-2008", "" ]
IDE: Microsoft Visual Studio Professional 2008 Language: C# Background: I have one form and two groupboxes that are going to be used as preference catagory groupboxes. My problem is that everytime I drag one groupbox on top of the other (hide/show groupboxes upon listview catagory select), the base groupbox auto-pare...
You may consider resizing your second GroupBox into position over the first. Drag one side or one corner of the second group box until it covers the first GroupBox and continue to resize the second GroupBox until it is positioned as you desire. Also available, in the Layout Toolbar, are the alignment and sizing button...
The behavior of the group box is that you can drag controls into it, including other group box controls. If you let go of the mouse while dragging it over, it will become a child of that groupbox, and AFAIK there is no way to change the designer. Unless you work potentially with send to back first, than load the other ...
MSV08-C#: How do I stop two groupboxes from auto-parenting themselves when dragged on top of one another?
[ "", "c#", ".net", "" ]
I am developing a website using CodeIgniter and PHP. Some of my friends suggest I start using Subversion to take care of my organization. Could someone give me a basic explanation of what SVN is without the jargon and also if it is practical for a framework where 5 files are needed to run a single page?
Subversion allows you to store your source in a central location, make changes from multiple places (ie. laptop, desktop), track changes and revert changes to your source tree if needed. Have you ever made a big 'improvement' and then decided you were going in the wrong direction? With Subversion you can revert to the...
Every single project (even with only one developer) should be under source control, no matter what framework or language you are using. Using simple words, Subversion will keep a history of your code files, should you like to revert them to a previous state or restore a copy in case of a disk crash (SVN must be on ano...
Subversion... practical with a PHP framework app or not?
[ "", "php", "svn", "frameworks", "" ]
I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the request is successful it will return HTML or XML. I see how to define the expected request type in jQuery as part of the `$.ajax()` call. Is th...
Have you application generate correct Content-Type headers (application/json, text/xml, etc) and handle those in your success callback. Maybe something like this will work? ``` xhr = $.ajax( { //SNIP success: function(data) { var ct = xhr.getResponseHeader('Content-Type'); ...
how about using the `complete` option? ``` $.ajax({ ... complete : function(xhr, status) { // status is either "success" or "error" // complete is fired after success or error functions // xhr is the xhr object itself var header = xhr.getResponseHeader('Content-Type'); }, ... }); ```
Can I evaluate the response type of an $.ajax() call in success callback?
[ "", "javascript", "jquery", "ajax", "" ]
Is there some way to detect file handle leaks at program termination? In particular I would like to make sure that all of my handles that get created are being freed in code. For example, I may have a CreateFile() somewhere, and at program termination I want to detect and ensure that all of them are closed.
I have used !htrace command of windbg. ``` !htrace -enable !htrace -snapshot !htrace -diff ``` Allow you to compare the handle situation of two execution point and help you the locate the point where the leaked handle have been allocated. It worked well for me.
If you can (i.e. if it's not a huge legacy code-base you are bugfixing) you should consider using the [RAII](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) idiom to wrap around your file handles. By "taking" the file handle in the constructor and releasing it in the destructor you can be sure that...
Detect file handle leaks with Win32 C++
[ "", "c++", "winapi", "visual-c++", "" ]
In Python I could've converted it to Unicode and do '(?u)^[\w ]+$' regex search, but PHP doesn't seem to understand international \w, or does it?
Although I haven't tested myself, looking at <https://www.php.net/manual/en/reference.pcre.pattern.syntax.php> suggests the following: '/^[\p{L} ]+$/u' would work - the \p{L} will match any unicode letter. Additionally, you can apparently write this without the curly brackets - '/^[\pL ]+$/u'.
afaik PHP isn't aware of utf8, meaning that php itself won't be able to process it other than bytewise. PHP believes everything is latin1, but there is however extensions that might be useful for you, like mbstring. <http://se.php.net/mbstring>
How do I check that string has only international letters and spaces in UTF8 in PHP?
[ "", "php", "utf-8", "utf", "" ]
I'm writing an applicationt hat was prototyped on MySQL and is now connecting to an Oracle database. All I had to do to connect to the oracle database (having built up the table structure) was change the connection string. What is the format to connect to a SQL Server DB on another machine? I've read some tutorials ...
You should not use the JDBC-ODBC bridge in a production environment. It is much slower than other JDBC drivers and only necessary when a JDBC driver is not available. SQL Server has a [JDBC driver](http://www.microsoft.com/downloads/details.aspx?familyid=C47053EB-3B64-4794-950D-81E1EC91C1BA&displaylang=en) available f...
Do NOT use the JDBC-ODBC bridge driver. That was meant purely for testing, not for production. You can still make your application database agnostic using drivers that are optimized for the database you want to connect to. Just externalize the username, password database driver name and connect string, and don't use an...
Connecting to SQLServer using JDBC-ODBC Bridge
[ "", "java", "jdbc", "odbc-bridge", "" ]
One of my columns is called `from`. I can't change the name because I didn't make it. Am I allowed to do something like `SELECT from FROM TableName` or is there a special syntax to avoid the SQL Server being confused?
Wrap the column name in brackets like so, `from` becomes [from]. ``` select [from] from table; ``` It is also possible to use the following (useful when querying multiple tables): ``` select table.[from] from table; ```
If it had been in PostgreSQL, use double quotes around the name, like: ``` select "from" from "table"; ``` Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. **sEleCt \* from tAblE;** is inter...
How to deal with SQL column names that look like SQL keywords?
[ "", "sql", "sql-server", "" ]
I know that lots of web hosting providers are offering FreeBSD, but how good is FreeBSD as a development platform? Specifically, is Java 1.6 available in it? Is there somthing specific that it offers with regard to tools that is not available under Linux?
I've always found FreeBSD a wonderful secure hosting environment, but perhaps not the easiest development platform. You will have to dig a bit to get Java 1.6 up and running, though I think it will be doable. I hope you are familiar with emacs or vi. The ports system will afford you access to many pieces of software, b...
You can get binary distributions of Java from the [FreeBSD Foundation](http://freebsdfoundation.org/), they signed an agreement with Sun for that. Art from Java, FreeBSD is awonderful development platform with every language and environement you may need/want. Disclaimer: I've been a FreeBSD developer for more than 13 ...
How good is FreeBSD as a development platform?
[ "", "java", "operating-system", "freebsd", "platform", "" ]
Suppose that I have a Java program within an IDE (Eclipse in this case). Suppose now that I execute the program and at some point terminate it or it ends naturally. Is there a **convenient** way to determine which lines executed at least once and which ones did not (e.g., exception handling or conditions that weren't ...
[eclemma](http://www.eclemma.org/) would be a good start: a code coverage tool would allow a coverage session to record the information you are looking for. [![alt text](https://i.stack.imgur.com/bWhQj.gif)](https://i.stack.imgur.com/bWhQj.gif) (source: [eclemma.org](http://www.eclemma.org/images/smallscreen.gif))
What you're asking about is called "coverage". There are several tools that measure that, some of which integrate into Eclipse. I've used [jcoverage](http://java-source.net/open-source/code-coverage/jcoverage-gpl) and it works (I believe it has a free trial period, after which you'd have to buy it). I've not used it, b...
How to identify which lines of code participated in a specific execution of a Java program?
[ "", "java", "eclipse", "profiling", "code-coverage", "trace", "" ]
I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). `java.util.SimpleDateFormat` does not seem to output timezone offsets in the *hour:minute* format, it excludes the colon. Is there a simple way to get that timestamp in Java? ``` // I want 2008-11-13T12:23:30-08:00 String timestamp = new...
Starting in Java 7, there's the `X` pattern string for ISO8601 time zone. For strings in the format you describe, use `XXX`. [See the documentation](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#iso8601timezone). Sample: ``` System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"...
Check out the [Joda Time](http://www.joda.org/joda-time/) package. They make RFC 3339 date formatting a lot easier. **Joda Example:** ``` DateTime dt = new DateTime(2011,1,2,12,45,0,0, DateTimeZone.UTC); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); String outRfc = fmt.print(dt); ```
Output RFC 3339 Timestamp in Java
[ "", "java", "timestamp", "rfc3339", "" ]
I have html code that looks roughly like this: ``` <div id="id1"> <div id="id2"> <p>some html</p> <span>maybe some more</span> </div> <div id="id3"> <p>different text here</p> <input type="text"> <span>maybe even a form item</span> </div> </div> ``` Obviously there's more to it than that, ...
In this case, `document.getElementById('id1').appendChild(document.getElementById('id2'));` should do the trick. More generally you can use [`insertBefore()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore).
This function takes any node that is passed into it and wraps it with the tag given. In the example code snippet I wrapped a span tag with a section tag. ``` function wrap(node, tag) { node.parentNode.insertBefore(document.createElement(tag), node); node.previousElementSibling.appendChild(node); } ``` ``` functio...
"Cut and Paste" - moving nodes in the DOM with Javascript
[ "", "javascript", "dom", "" ]
What is the best method of hiding php errors from being displayed on the browser? Would it be to use the following: ``` ini_set("display_errors", 1); ``` Any best practice tips would be appreciated as well! I am logging the errors, I just want to make sure that setting the display\_errors value to off (or 0) will n...
The best way is to log your errors instead of displaying or ignoring them. This example will log the errors to syslog instead of displaying them in the browser. ``` ini_set("display_errors", 0); ini_set("log_errors", 1); //Define where do you want the log to go, syslog or a file of your liking with ini_set("error_lo...
Assuming you are in control of the php.ini file, you can make these changes globally inside that file instead of having the ini\_set code laying around in all your php files (which you might forget to put in one of your files one day, which could be bad in production).
Best way to suppress php errors on production servers
[ "", "php", "error-handling", "" ]