Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
When used like this: ``` import static com.showboy.Myclass; public class Anotherclass{} ``` what's the difference between `import static com.showboy.Myclass` and `import com.showboy.Myclass`?
See [Documentation](http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html) > The static import declaration is > analogous to the normal import > declaration. Where the normal import > declaration imports classes from > packages, allowing them to be used > without package qualification, the > stati...
There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this: ``` import org.apache.commons.lang.StringUtils; . . . if (StringUtils.isBlank(aString)) { . ...
What does the "static" modifier after "import" mean?
[ "", "java", "modifier", "static-import", "" ]
Why does the JavaScript function `encodeURIComponent` encode spaces to the hex Unicode value `%20` instead of `+`. Should URI parameters not spaces to `+`? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
Spaces encode to %20, I believe that's their ASCII character code. However, developers have taken a shine to encoding spaces to + because it generates URLs that are readable and typeable by human beings.
The + is not recognised as a space in all uses of a URI for example try using this link:- mailto:bloke@somewhere?subject=Hello+World The subject line still has the + whereas:- mailto:bloke@somewhere?subject=Hello%20World works.
Encoding spaces with the javascript encodeURIComponent function
[ "", "javascript", "" ]
Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in `Foo **`) in C++?
Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns. ``` #include <iostream> using namespace std; struct Foo { int a; }; void CreateFoo(Foo** p) { *p = new Foo(); (*p)->a = 12; } int main(int argc, char* argv[]) { Foo* p = NULL;...
IMO most common usage is to pass reference to pointer variable ``` void test(int ** var) { ... } int *foo = ... test(&foo); ``` You can create multidimensional jagged array using double pointers: ``` int ** array = new *int[2]; array[0] = new int[2]; array[1] = new int[3]; ```
To what use is multiple indirection in C++?
[ "", "c++", "pointers", "" ]
Is there a way to prevent VS2008 creating browse info file files for C++ projects. I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed. EDIT - it's also needed for go to declaration/definition
There is a registry key for this as well: `[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]` Intellisense ON ``` "IntellisenseOptions"=dword:00000000 ``` Intellisense OFF ``` "IntellisenseOptions"=dword:00000007 ``` Intellisense ON - NO Background UPDATE ``` "IntellisenseO...
In the project properties, you will find the browse information under: Configuration Properties -> C/C++ -> Browse Information Just tell it not to generate browse information. All it is used for is quickly browsing between code components (like using 'Go to Definition') and so forth. I personally like being able to q...
Prevent visual studio creating browse info (.ncb) files
[ "", "c++", "visual-studio", "visual-studio-2008", "" ]
I'm using the Excel interop in C# (`ApplicationClass`) and have placed the following code in my finally clause: ``` while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { } excelSheet = null; GC.Collect(); GC.WaitForPendingFinalizers(); ``` Although this kind of works, the `Excel.exe` proc...
Excel does not quit because your application is still holding references to COM objects. **I guess you're invoking at least one member of a COM object without assigning it to a variable.** For me it was the *excelApp.Worksheets* object which I directly used without assigning it to a variable: ``` Worksheet sheet = e...
You can actually release your Excel Application object cleanly, but you do have to take care. The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via `Marshal.FinalReleaseComObject()` is correct in theory, but, unfortunately, very difficult to manage in pr...
How do I properly clean up Excel interop objects?
[ "", "c#", "excel", "interop", "com-interop", "" ]
I'm trying to use CSS (**under `@media print`**) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option. To put it another way, I'm loo...
Here's some code I ended up using, in case someone might find it useful. All you need to do is make the outer DIV the size you want in inches. ``` function make_big(id) // must be an inline element inside a block-level element { var e = document.getElementById(id); e.style.whiteSpace = 'nowrap'; e.style.te...
The CSS font-size property accepts [length units](http://htmlhelp.com/reference/css/units.html#length) that include absolute measurements in inches or centimeters: > Absolute length units are highly dependent on the output medium, and > so are less useful than relative units. The following absolute units > are availab...
How do you find the largest font size that won't break a given text?
[ "", "javascript", "css", "printing", "" ]
There's a lot of people today who sell unittesting as bread-and-butter of development. That might even work for strongly algorithmically-oriented routines. However, how would you unit-test, for example, a memory allocator (think malloc()/realloc()/free()). It's not hard to produce a working (but absolutely useless) mem...
Highly testable code tends to be structured differently than other code. You describe several tasks that you want an allocator to do: * coalescing free blocks * reusing free blocks on next allocations * returning excess free memory to the system * asserting that the allocation policy (e.g. first-fit) really is ...
**If there is any logic in there, it can be unit-tested.** If your logic involves making decisions and calling OS/hardware/system APIs, fake/mock out the device dependent calls and unit test your logic to verify if the right decisions are made under a given set of pre-conditions. Follow the Arrange-Act-Assert triad i...
How would you unittest a memory allocator?
[ "", "c++", "c", "unit-testing", "testing", "memory-management", "" ]
It often happens that characters such as *é* gets transformed to *é*, even though the collation for the MySQL DB, table and field is set to utf8\_general\_ci. The encoding in the *Content-Type* for the page is also set to UTF8. I know about utf8\_encode/decode, but I'm not quite sure about where and how to use it. I...
On the first look at <http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet> I think that one important thing is missing (perhaps I overlooked this one). Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the clien...
Collation and charset are not the same thing. Your collation needs to match the charset, so if your charset is utf-8, so should the collation. Picking the wrong collation won't garble your data though - Just make string-comparison/sorting work wrongly. That said, there are several places, where you can set charset set...
How do I ensure that user entered data containing international characters doesn't get corrupted?
[ "", "php", "mysql", "internationalization", "" ]
I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download? **Update Oct 1, 2008:** Thanks for the advice, I was helping someone...
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page. ``` <img id="img1" src="imgfile1.png"> <img id="img2" src="imgfile2.png"> <canvas id="canvas"></canvas> <script type="text/javascript"> var img1 = document.getElementBy...
[MarvinJ](https://www.marvinj.org) provides the method **combineByAlpha()** in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow: ``` Marvin.combineByAlpha(image, imageOver, imageOutput, ...
Can you combine multiple images into a single one using JavaScript?
[ "", "javascript", "image-processing", "image-manipulation", "" ]
How do I copy a file in Python?
[`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is: ``` import shutil shutil.copyfile(src, dst) # 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp ``` * Copy the contents of the file named `src` to a file named `dst...
| Function | Copies metadata | Copies permissions | Uses file object | Destination may be directory | | --- | --- | --- | --- | --- | | [shutil.copy](https://docs.python.org/3/library/shutil.html#shutil.copy) | No | Yes | No | Yes | | [shutil.copyfile](https://docs.python.org/3/library/shutil.html#shutil.copyfile) | No...
How to copy files
[ "", "python", "file", "copy", "filesystems", "file-copying", "" ]
I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in `OnStart()` method). I had assumed that merely throwing an error in `OnStart()` would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. ...
if you are running .NET 2.0 or higher, you can use [ServiceBase.Stop](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop) to stop the service from OnStart. Otherwise call Stop from a new thread. ref [devnewsgroups] (<http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic...
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the `ExitCode`. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See [the windows error codes](h...
Handle exception on service startup
[ "", "c#", ".net", "windows-services", "error-handling", "" ]
I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance. What is the general practice for this? Real-world-scenario - I have several HTML pages that need client-side form validation. For this I use a jQuery plugin that I incl...
At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance. (Why performance? Because if the code is separate, it can easier be cached by browsers.) JavaScript doesn't belong in the HTML code and if it contains special characters (suc...
Maintainability is definitely a reason to keep them external, but if the configuration is a one-liner (or in general shorter than the HTTP overhead you would get for making those files external) it's performance-wise better to keep them inline. Always remember, that each HTTP request generates some overhead in terms of...
When should I use Inline vs. External JavaScript?
[ "", "javascript", "html", "" ]
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. I found a page on microsoft.com that says ...
You need to use `\r\n` as a solution.
I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior: * Every message starts with continuation off. * Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will ha...
How do I format a String in an email so Outlook will print the line breaks?
[ "", "java", "email", "outlook", "newline", "line-breaks", "" ]
I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop. The html looks like this: ``` <div onmouseover="jsHov...
I'd give the container div: ``` position: relative; ``` and add a third div in the container (should be the last child of the container) with: ``` position: absolute; top: 0; bottom: 0; left: 0; right: 0; ``` and catch the mouseover and mouseout events on this div instead. Because it has no child elements, you sho...
It sounds like what you really want is `mouseenter`/`mouseleave` (IE proprietary events, but easy to emulate): ``` // Observe mouseEnterLeave on mouseover/mouseout var mouseEnterLeave = function(e) { var rel = e.relatedTarget, cur = e.currentTarget; if (rel && rel.nodeType == 3) { rel = rel.parentNode;...
Problems with mouseout event
[ "", "javascript", "html", "events", "scriptaculous", "" ]
Let's say you have a function that returns a date: ``` Date myFunc(paramA, paramB){ //conditionally return a date? } ``` Is it appropriate to return `null` from this function? This seems ugly because it forces clients to check for `null`. The "null object" pattern is an implementation pattern that addresses this ...
The null object pattern is not for what you are trying to do. That pattern is about creating an object with no functionality in it's implementation that you can pass to a given function that requires an object not being null. An example is [NullProgressMonitor](http://download.eclipse.org/eclipse/downloads/documentatio...
null is quite acceptable. However if you want to return null on an error, consider throwing an exception instead.
Should I return null from or apply the "null object" pattern to a function returning a Date?
[ "", "java", "" ]
I have an ASPX page (On server A) which is invoked using NTLM credentials. Part of that page's job is to call an HTML page (On server B) and proxy it back to the client. (The firewall allows access to A, but not to B. The user would normally be allowed access to both servers.). Server B is also not open to anonymous ac...
You can certainly obtain the login name of the caller, but not the password. NTLM uses a challenge/response mechanism, so the password is never transmitted. Your server must have access to a password-equivalent (a hash) in order to form the challenge and check the response, but even if you can get hold of it that passw...
Page.User will get you the Security Principal of the user the page is running under. From there you should be able to figure it out.
Get the NTLM credentials from the Response on an APSX page
[ "", "c#", "asp.net", "credentials", "" ]
Compared to * Simple memory access * Disk access * Memory access on another computer(on the same network) * Disk access on another computer(on the same network) in C++ on windows.
relative timings (shouldn't be off by more than a factor of 100 ;-) * memory-access in cache = 1 * function call/return in cache = 2 * memory-access out of cache = 10 .. 300 * disk access = 1000 .. 1e8 (amortized depends upon the number of bytes transferred) + depending mostly upon seek times + the transfer itself...
A function call is simply a shift of the frame pointer in memory onto the stack and addition of a new frame on top of that. The function parameters are shifted into local registers for use and the stack pointer is advanced to the new top of the stack for execution of the function. In comparison with time Function cal...
What is the cost of a function call?
[ "", "c++", "optimization", "architecture", "memory", "" ]
I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times. Doing that, however, makes my php code look horrific... it really messes with the for...
Don't panic, every fresh Web programmer face this problem. You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page : * one with only PHP code (no HTML) that fills variables * another with HTML and very few PHP : this is your page design Then i...
Use a mvc approach. <http://www.phpmvc.net/> This is not something that you will pick up in a couple of hours. You really need to practice it. Main thing is the controller will access your model (the db layer), do stuff to your data and then send it to the view for rendering. This is oversimplified but you just need ...
Keeping my PHP pretty
[ "", "php", "html", "formatting", "" ]
I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. I did not use a framewo...
The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing. The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at first...
You might consider using something like [web.py](http://webpy.org/) which would be easy to distribute (since it's small) and it would also be easy to adapt your other tools to it since it doesn't require you to submit to the framework so much like Django does. Be forewarned, however, it's not the most loved framework ...
Python web development - with or without a framework
[ "", "python", "frameworks", "" ]
I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to *not* get null for the WebServiceContext. In other words: how can I execute t...
I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The [J2ee tutorial on @Resource](http://java.sun.com/javaee/5/docs/tutorial/doc/bncjk.html) indicates that the name of the variable is used as part of the lookup. I've encountered this same pro...
The following code works for me using Java 5, Tomcat 6 and Metro Could it possibly be that there is a conflict between the WS support in Java 6 and the version of Metro you are using. Have you tried it on a Java 5 build? ``` @WebService public class Sample { @WebMethod public void sample() { HttpSessi...
How can I get access to the HttpServletRequest object when using Java Web Services
[ "", "java", "web-services", "annotations", "servlets", "" ]
I hit this error while my web application was trying to execute a SELECT INTO on a MSSQL 2005 database. I really have two questions: 1. What does this error mean and how does this happen? 2. Is there a way to prevent these errors by coding in a different way?
Besides the obvious, that somebody changed the table while the code was executing, it could be a naming conflict with temp tables created in the SQL. It could be that there are two temp tables with different schemas, but they have the same name.
You can get this error if a database trigger(AFTER CREATE\_TABLE) changes the table, when using SELECT INTO.
How does a "Schema changed after the target table was created" error occur?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I often see code like: ``` Iterator i = list.iterator(); while(i.hasNext()) { ... } ``` but I write that (when Java 1.5 isn't available or for each can't be used) as: ``` for(Iterator i = list.iterator(); i.hasNext(); ) { ... } ``` because * It is shorter * It keeps `i` in a smaller scope * It reduces the ...
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
There are appropriate uses for the while, the for, and the foreach constructs: * `while` - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition * `for` -...
Iterate with for loop or while loop?
[ "", "java", "for-loop", "iterator", "" ]
Ideally I'd like a way to enable the mouse wheel for scrolling in old compiled java runtime apps, but java code to explicitly utilise it for an individual app would suffice.
Without access to the source code, you can't do it. If you do have access to the source, then do what RichH said.
You shouldn't have to recompile against 1.5 or 1.6 to get mousewheel, unless you wrote custom components. The mousewheel behaviors were added to the swing classes, so just running old java apps against the new JRE should have mousewheel support without having to do anything (at least in scrollable/JScrollPane based stu...
Is there any way to enable the mousewheel (for scrolling) in Java apps?
[ "", "java", "scroll", "mouse", "mousewheel", "" ]
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django. I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just th...
Start with [this Django snippet](http://www.djangosnippets.org/snippets/136/), but modify it to check `request.session['has_beta_access']`. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to `True`. Making it a publi...
You can probably restrict access to the entire site via apache with htaccess, taking the problem out of the django's project space entirely.
Making a beta code for a public django site
[ "", "python", "django", "authentication", "django-authentication", "" ]
Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing. Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?
You could try setting up your own handler for the [onerror event](http://developer.mozilla.org/En/DOM:window.onerror) and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, [support is somewhat flaky](http://www.quirksmode.org/dom/events/error.html). Here's an exam...
**Short answer:** Yes, it is possible. **Longer answer:** People have already written about how you can (at least partially) solve this issue by writing your own code. However, do note that there are services out there that seems to have made sure the JS code needed works in many browsers. I've found the following: *...
Logging Clientside JavaScript Errors on Server
[ "", "javascript", "logging", "error-handling", "" ]
I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work. Yet, I found this approach very unsatisfactory: time consuming and u...
Writing deadlock-proof code is really hard. Even when you access the tables in the same order you may still get deadlocks [1]. I wrote [a post on my blog](http://samsaffron.com/archive/2008/08/27/Deadlocked+) that elaborates through some approaches that will help you avoid and resolve deadlock situations. If you want ...
Zero deadlocks is basically an incredibly costly problem in the general case because you must know all the tables/obj that you're going to read and modify for every running transaction (this includes SELECTs). The general philosophy is called **ordered strict two-phase locking** (not to be confused with two-phase commi...
Zero SQL deadlock by design - any coding patterns?
[ "", "sql", "sql-server", "design-patterns", "deadlock", "" ]
in Javascript, the following: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); ``` yields "the quick","brown fox","jumps over","the lazy dog" I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog what regexp wil...
This seems to work: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/[^"]+(?=(" ")|"$)/g); alert(result); ``` Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature). See <http://...
It is not one regexp, but two simpler regexps. ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); // ["the quick","brown fox","jumps over","the lazy dog"] result.map(function(el) { return el.replace(/^"|"$/g, ""); }); // [the quick,brown fox,jumps over,the lazy d...
Regexp matching of list of quotes strings - unquoted
[ "", "javascript", "regex", "actionscript-3", "" ]
Does anyone know of a Django 1.0 + postgresql + apache + mod\_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.
Configure and build your appliance at [Elastic Server On-Demand](https://elasticserver.com/).
Another option I've had moderate success with [TurnKey Linux Django Appliance](http://www.turnkeylinux.org/appliances/django)
Django VMware appliance
[ "", "python", "django", "vmware", "" ]
What is the difference between a method [decorated](https://peps.python.org/pep-0318/) with [`@staticmethod`](http://docs.python.org/library/functions.html#staticmethod) and one decorated with [`@classmethod`](http://docs.python.org/library/functions.html#classmethod)?
Maybe a bit of example code will help: Notice the difference in the call signatures of `foo`, `class_foo` and `static_foo`: ``` class A(object): def foo(self, x): print(f"executing foo({self}, {x})") @classmethod def class_foo(cls, x): print(f"executing class_foo({cls}, {x})") @static...
A **staticmethod** is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. A **classmethod**, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first...
What is the difference between @staticmethod and @classmethod in Python?
[ "", "python", "oop", "static-methods", "python-decorators", "class-method", "" ]
Under what circumstances will the Win32 API function OleGetClipboard() fail and return `CLIPBRD_E_CANT_OPEN`? More background: I am assisting with a Firefox bug fix. Details here: [bug 444800 - cannot retrieve image data from clipboard in lossless format](https://bugzilla.mozilla.org/show_bug.cgi?id=444800#c19 "canno...
The documentation says that `OleGetClipboard` can fail with this error code if `OpenClipboard` fails. In turn, if you read that documentation, it says: "**OpenClipboard** fails if another window has the clipboard open." It's an exclusive resource: only one window can have the clipboard open at a time. Basically, if y...
Is your test running over Terminal Services? See [CLIPBRD\_E\_CANT\_OPEN error when setting the Clipboard from .NET](https://stackoverflow.com/questions/68666/clipbrdecantopen-error-when-setting-the-clipboard-from-net).
Why would the Win32 OleGetClipboard() function return CLIPBRD_E_CANT_OPEN?
[ "", "c++", "windows", "winapi", "ole", "" ]
Our server application is listening on a port, and after a period of time it no longer accepts incoming connections. (And while I'd love to solve this issue, it's not what I'm asking about here;) The strange this is that when our app stops accepting connections on port 44044, so does IIS (on port 8080). Killing our ap...
You may well be starving the stack. It is pretty easy to drain in a high open/close transactions per second environment e.g. webserver serving lots of unpooled requests. This is exhacerbated by the default TIME-WAIT delay - the amount of time that a socket has to be closed before being recycled defaults to 90s (if I r...
You haven't maxed out the available port handles have you ? `netstat -a` I saw something similar when an app was opening and closing ports (but not actually closing them correctly).
Can a TCP/IP Stack be killed programmatically?
[ "", "c#", "tcp", "" ]
I want to use modal pop-up windows in our web app in Ruby on Rails. Note that I don't want to create a new browser window, but a sub-window inside the existing webpage. We've tried things like TinyBox, but there are issues with returning error information from inside the controller. Any good method or tool that works w...
There's also [prototype-window](http://prototype-window.xilinus.com/).
I've never used it myself (not yet at least) but have you tried [RedBox](http://blog.craigambrose.com/articles/2006/08/16/redbox-a-rails-compatible-lightbox)?
What are some good pop-up dialog boxes for Ruby on Rails
[ "", "javascript", "ruby-on-rails", "user-interface", "modalpopups", "" ]
Does anyone know of any methods to create a file upload progress bar in PHP? I have often heard that it's impossible. I have one idea, but not sure if it would work: have a normal file upload, but instead submit to an iframe. When this is submitted, store the file information (size and temp location) in the session. A...
You can try [YUI](http://developer.yahoo.com/yui/uploader/) or [Prototype](http://www.google.com/search?q=prototype+upload+progress) or [JQuery](http://www.google.com/search?q=jquery+upload+progress)
You're pretty much figured out how to do it. The main problem is you usually don't have access to the size of the uploaded file until it's done uploading. There are workarounds for this: Enabling APC, you to access this information if you include a field called "APC\_UPLOAD\_PROGRESS" and use apc\_fetch() for retrievi...
Creating a file progress bar in PHP
[ "", "php", "ajax", "file-upload", "progress-bar", "" ]
What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e. The number of sessions the database was configured to allow ``` SELECT name, value FROM v$parameter WHE...
The **sessions** parameter is derived from the **processes** parameter and changes accordingly when you change the number of max processes. See the [Oracle docs](http://docs.oracle.com/cd/B28359_01/server.111/b28320/initparams001.htm#i1124357) for further info. To get only the info about the sessions: ``` select ...
How to check the maximum number of allowed connections to an Oracle database?
[ "", "sql", "oracle", "" ]
What would be the best practice way to handle the caching of images using PHP. The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag. When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid...
There is two typos in Dan Udey's rewrite example (and I can't comment on it), it should rather be : ``` RewriteCond %{REQUEST_URI} ^/images/cached/ RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule (.*) /images/generate.php?$1 [L] ``` Regards.
I would do it in a different manner. Problems: 1. Having PHP serve the files out is less efficient than it could be. 2. PHP has to check the existence of files every time an image is requested 3. Apache is far better at this than PHP will ever be. There are a few solutions here. You can use `mod_rewrite` on Apache. ...
Best way to cache resized images using PHP and MySQL
[ "", "php", "image", "caching", "resize", "" ]
I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget. Any suggestions?
You can make the root form (by which I assume you mean `JFrame`) be your own subclass of `JFrame`, and put standard functionality in its constructor, such as: ``` this.setIconImage(STANDARD_ICON); ``` You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, ...
There is another way, but its more of a "hack" then a real fix.... If you are distributing the JRE with your Application, you could replace the coffee cup icon resource in the java exe/dll/rt.jar wherever that is with your own icon. It might not be very legit, but it is a possibility...
How do I set an Application's Icon Globally in Swing?
[ "", "java", "swing", "" ]
I'm writing an application which reads large arrays of floats and performs some simple operations with them. I'm using floats, because I thought it'd be faster than doubles, but after doing some research I've found that there's some confusion about this topic. Can anyone elaborate on this?
The short answer is, "use whichever precision is required for acceptable results." Your one guarantee is that operations performed on floating point data are done in at least the highest precision member of the expression. So multiplying two **float**'s is done with at least the precision of **float**, and multiplying...
I just read the "Microsoft .NET Framework-Application Development Foundation 2nd" for the MCTS exam 70-536 and there is a note on page 4 (chapter 1): > **NOTE Optimizing performance with built-in types** > The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counte...
Are doubles faster than floats in C#?
[ "", "c#", "performance", "floating-point", "precision", "" ]
How would I upload a file to a webserver using c++ and MFC. We are not using .Net. Would I need to open a socket and do everything myself? If so, where is a good reference to follow?
You don't want to use direct socket calls. It's hard to get HTTP right this way. The easier way is to the WinINet APIs. Check out the docs for InternetOpen, this will likely be the first call you make. Functions you will likely need: * InternetOpen * InternetConnect * HttpOpenRequest * HttpSendRequest * HttpQueryInfo...
Here is the code I ended up using. I stripped out the error checking, and other notification stuff. This does a multi-part form upload. ``` DWORD dwTotalRequestLength; DWORD dwChunkLength; DWORD dwReadLength; DWORD dwResponseLength; CHttpFile* pHTTP = NULL; dwChunkLength = 64 * 1024; void* pBuffer = malloc(dwChunkLe...
MFC File upload
[ "", "c++", "mfc", "upload", "" ]
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server. Has anyone dealt with this that can give me some...
poking around the facebox.js I came across this line in the function init(settings)... ``` $('body').append($.facebox.settings.faceboxHtml) ``` I changed that to ... ``` $('#aspnetForm').append($.facebox.settings.faceboxHtml) ``` and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event: ``` btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null)); ``` this will let the button fires a PostBack.
JQuery Facebox Plugin : Get it inside the form tag
[ "", "c#", "asp.net", "jquery", "facebox", "" ]
Our team has been experiencing a recurring problem with velocity templates. Upon rendering, some throw a RuntimeException with the message "Template.merge() failure - Unable to render Velocity Template, '/template.vm'". We have not been able to reproduce the problem and the documentation on the web is pretty insufficie...
What version of Velocity are you using? There were some race conditions in old versions that caused this. Most were squashed in the Velocity 1.5 release. Though i would personally recommend using Velocity 1.6-beta1. It has vastly improved performance (memory and speed) and a lot of minor bug fixes that didn't make it i...
I am working on the same bug right now, on our website. It does appear to be a race condition: I can reproduce it consistently using multiple processes fetching the same page, but never reproduce it if I serialize the requests. I am using velocity-1.5; I tried migrating to 1.6-beta1 but see other errors. **RESOLVED*...
What causes a velocity Template.merge() failure? How does one avoid it?
[ "", "java", "velocity", "" ]
Is it possible to call a JavaScript function from the IMG SRC tag to get an image url? Like this: ``` <IMG SRC="GetImage()" /> <script language="javascript"> function GetImage() {return "imageName/imagePath.jpg"} </script> ``` This is using .NET 2.0.
Nope. It's not possible, at least not in all browsers. You can do something like this instead: ``` <img src="blank.png" id="image" alt="just nothing"> <script type="text/javascript"> document.getElementById('image').src = "yourpicture.png"; </script> ``` Your favourite JavaScript framework will provide nicer ways...
If you're in the mood for hacks, this works as well. ``` <img src='blah' onerror="this.src='url to image'"> ```
IMG SRC tags and JavaScript
[ "", "javascript", "asp.net", "image", "" ]
I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. In the code he defines a constant; ...
Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using m...
On the one hand, you'd like to think Threads == CPU/Cores makes perfect sense. Why have a thread if there's nothing to run it? The detail boils down to "what are the threads doing". A thread that's idle waiting for a network packet or a disk block is CPU time wasted. If your threads are CPU heavy, then a 1:1 correlat...
How many threads should I use in my Java program?
[ "", "java", "multithreading", "" ]
I'm thinking floats. For the record I'm also using NHibernate.
`decimal` You won't lose precision due to rounding.
The answer is application-dependent. Others have pointed out that decimal is better than float for representing an exact value. But sometimes it's better to use a float for the increased precision (e.g. a set of calculated weights that add up to 100% is probably better represented as a float)
What types should I use to represent percentages in C# and SQL Server?
[ "", "c#", "sql-server", "" ]
How can I know what encoding will be used by PHP when sending data to the browser? I.e. with the Cotent-Type header, for instance: iso-8859-1.
Usually Apache + PHP servers of webhosters are configured to send out **NO `charset` header**. The shortest way to test how your server is configured are these: * Use [this tool to see the server header](http://www.seoconsultants.com/tools/headers) by getting any one of your pages on your webiste. If in the server h...
You can use the header() solution that William suggested, however if you are running Apache, and the Apache config is using a default charset, that will win everytime (Internet Explorer will go crazy) See: [AddDefaultCharset](http://httpd.apache.org/docs/2.0/mod/core.html#adddefaultcharset)
PHP: Current encoding used to send data to the browser
[ "", "php", "header", "character-encoding", "" ]
I am **very** new to the entity framework, so please bear with me... How can I relate two objects from different contexts together? The example below throws the following exception: > System.InvalidOperationException: The > relationship between the two objects > cannot be defined because they are > attached to diffe...
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity. EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs. You could simply pass the co...
Another approach that you could use here is to detach objects from one context, and then attach them to another context. That's a bit of a hack, and it may not work in your situation, but it might be an option. ``` public void GuestUserTest() { SlideLincEntities ctx1 = new SlideLincEntities(); ...
How to relate objects from multiple contexts using the Entity Framework
[ "", "c#", ".net", "entity-framework", "" ]
I have a LinkedList, where Entry has a member called id. I want to remove the Entry from the list where id matches a search value. What's the best way to do this? I don't want to use Remove(), because Entry.Equals will compare other members, and I only want to match on id. I'm hoping to do something kind of like this: ...
``` list.Remove(list.First(e => e.id == searchId)); ```
Here's a simple solution: ``` list.Remove(list.First((node) => node.id == searchId)); ```
How do I remove an element that matches a given criteria from a LinkedList in C#?
[ "", "c#", ".net", "data-structures", "" ]
In this code I am debugging, I have this code snipit: ``` ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0'); ``` What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year. UPDATE: Tha...
It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a "just in case" for expiration years ending in 08, 07, etc., making sure that the leading zero is present.
This prints "98" to the console. ``` class Program { static void Main(string[] args) { Console.Write("1998".Substring(2).PadLeft(2, '0')); Console.Read(); } } ```
Can't figure out what this SubString.PadLeft is doing
[ "", "c#", "substring", "padleft", "" ]
For RMI on server-side, do we need to start `rmiregistry` program, or just call `LocateRegistry.createRegistry`? If both are possible, what are the advantages and disadvantages?
They're the same thing... `rmiregistry` is a separate program, which you can run from a command line or a script, while `LocateRegistry.createRegistry` does the same thing programatically. In my experience, for "real" servers you will want to use `rmiregistry` so that you know it's always running regardless of whether...
If we start rmiregistry first, RmiServiceExporter would register itself to the running rmiregistry. In this case, we have to set the system property 'java.rmi.server.codebase' to where the 'org.springframework.remoting.rmi.RmiInvocationWrapper\_Stub' class can be found. Otherwise, the RmiServiceExporter would not be st...
RMI server: rmiregistry or LocateRegistry.createRegistry
[ "", "java", "rmi", "rmiregistry", "" ]
Using VC2005, I have 3 projects to build: * libA (contains a typelib, results in libA.dll): IDL has a line `library libA { ...` * libB (contains a typelib importing libA, results in libB.dll): IDL has a line `importlib( "libA " );` * libC (imports libB): one of the source files contains `#import <libB.dll>` the `#imp...
Finally Found It! In the Visual Studio project, the A.idl file in LibA had the **MkTypeLib Compatible** setting ON. This overruled the behaviour inherited from the A project. To make things worse, it was only ON in the Debug configuration. The consequence was that for every ``` typedef [public] tagE enum { cE1, cE2 ...
Are you explicitly setting the project's dependencies? In other words have you set up the solution in the IDE so that project C depends on project B, and project B depends on project A?
Indirect Typelib not imported well from Debug dll
[ "", "c++", "visual-c++", "import", "typelib", "" ]
I want to save the objects I generated in a program. After restart the App should load automaticly all Objects in an Array. I want to write them in a file and parse them after restart. Are the other smarter possibilities than do it by hand? Thank you
You can use the *Berkeley DB* `PersistentMap` class to save your (`Serializable`) objects in a `Map` implementation (a cache) which persists them to a file. It's pretty simple to use and means you don't have to worry about what to save where. Three things to note about serialization: 1. How are you going to cope with...
Yes, the concept you are looking for is called serialization. There's a fine tutorial at Sun [here](http://java.sun.com/developer/technicalArticles/Programming/serialization/). The idea is that classes you want to persist have to implement the Serializable interface. After that you use java.io.ObjectOutputStream.write...
Java: Save objects in a textfile? Are there readymade solutions?
[ "", "java", "object", "store", "flat-file", "" ]
To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick: ``` ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */,...
try this (from a 32bit process): ``` > %WINDIR%\sysnative\reg.exe query ... ``` (found that [here](http://ovidiupl.spaces.live.com/blog/cns!1E8A6038167E4BE9!925.entry)).
Whether a 32-bit or 64-bit native (unmanaged) program is run depends solely on the executable. There are two copies of `reg.exe`, in C:\Windows\System32 (64-bit) and C:\Windows\SysWOW64 (32-bit). Because you don't specify a path, you're getting whatever appears first in the `PATH` environment variable, which is the 32-...
How to launch a Windows process as 64-bit from 32-bit code?
[ "", "c++", "winapi", "64-bit", "registry", "" ]
What role is Spring taking in Struts + Spring + Hibernate?
Spring provides many different "modules" and different programmers will use different parts of Spring. However, commonly in this sort of stack, you will see Spring being used as a provider of * An inversion of control container for dependency injection * An abstraction to Hibernate called "HibernateTemplate" * Framew...
Well, Hibernate handles the persistence part, JSP handles your GUI, Struts controls the flow between pages/actions/etc, and Spring can manage all your beans which contain the main business logic, instead of using EJB. Plus it can simplify the coding of your Hibernate DAO's and transaction managing. Instead of having to...
What is the role of Spring in Struts + Spring + Hibernate?
[ "", "java", "hibernate", "spring", "struts", "" ]
Typically I use `E_ALL` to see anything that PHP might say about my code to try and improve it. I just noticed a error constant `E_STRICT`, but have never used or heard about it, is this a good setting to use for development? The manual says: > Run-time notices. Enable to have PHP suggest changes to your code which w...
In PHP 5, the things covered by `E_STRICT` are not covered by `E_ALL`, so to get the most information, you need to combine them: ``` error_reporting(E_ALL | E_STRICT); ``` In PHP 5.4, `E_STRICT` will be included in `E_ALL`, so you can use just `E_ALL`. You can also use ``` error_reporting(-1); ``` which will alwa...
Use the following in php.ini: ``` error_reporting = E_ALL | E_STRICT ``` Also you should install [Xdebug](http://xdebug.org "Xdebug"), it can highlight your errors in blinding bright colors and print useful detailed information. Never let any error or notice in your code, even if it's harmless.
What is the recommended error_reporting() setting for development? What about E_STRICT?
[ "", "php", "error-reporting", "" ]
Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.
if you mean common lisp by lisp, then there's **[cl-rdbms](http://common-lisp.net/project/cl-rdbms/)**. it is heavily tested on postgres (uses [postmodern](http://common-lisp.net/project/postmodern/) as the backend lib), it has a toy sqlite backend and it also has an OCI based oracle backend. it supports abstracting aw...
At the moment there's no open-source library that supports all the SQL backends you mention. [CLSQL](http://clsql.b9.com/) comes quite close (lacking only support for MS SQL). The alternatives are: * [CL-RDBMS](http://common-lisp.net/project/cl-rdbms/) (which supports Oracle, Postgres through Postmodern and SQLite3) *...
What is the best SQL library for use in Common Lisp?
[ "", "sql", "database", "postgresql", "lisp", "common-lisp", "" ]
if I call php's `parse_ini_file("foo.ini")`, in what paths does it look for foo.ini ? the include path? the function's documentation doesn't mention it.
The filename argument for parse\_ini\_file is a standard php filename, so the same rules will apply as opening a file using [fopen](https://www.php.net/manual/en/function.fopen.php). You must either specify an absolute file path ("/path/to/my.ini") or a path relative to your current working directory ("my.ini"). See [...
I would imagine it only looks in the current working directory - See <https://www.php.net/manual/en/function.getcwd.php> if you want to know what that is. You can always find a path relative to your application by basing it on $\_SERVER['DOCUMENT\_ROOT']
PHP parse_ini_file() - where does it look?
[ "", "php", "file", "parsing", "path", "ini", "" ]
Since I upgraded to Visual Studio 2008 from vs2005, I have found a very annoying behaviour when debugging large projects. If I attempt to step into inline code, the debugger appears to lock up for tens of seconds. Each time that I step inside such a function, there is a similar pause. Has anyone experienced this and is...
I used to get this - I think it's a bug with the 'Autos' debug window: <http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/eabc58b1-51b2-49ce-b710-15e2bf7e7516/>
I get delays like this when debugging ASP.NET apps and it seems to happen when a symbol(pdb) file is getting accessed in the background. The larger the library, the longer the wait. My delay is at most about 10 seconds, but it does seem to happen with symbols that have already been accessed. I do get a lot of 1-3 seco...
Visual Studio debugger slows down in in-line code
[ "", "c++", "windows", "visual-studio", "debugging", "" ]
I am writing a web server in Java and I want it to support HTTP 1.1 Keep-Alive connections. But how can I tell when the client is done sending requests for a given connection? (like a double end-of-line or something). Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mi...
If you're building your server to meet the standard, then you've got a lot of information to guide you here already. Simple spoken, *it should be based on a time since a connection was used, and not so much at the level of request data.* In a longer-winded way, the [practical considerations section](http://www.w3.org...
> Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I just put [When should I close an HTTP 1.1 connection?](http://www.google.co.uk/search?q=When+should+I+close+an+HTTP+1.1+connection%3F) into Google, and the thir...
How do I know WHEN to close an HTTP 1.1 Keep-Alive Connection?
[ "", "java", "http", "http-headers", "network-protocols", "" ]
I have read on Stack Overflow some people that have converting to C#2.0 to C#3, but is it really worth it? I have a project that is done at 75% before going in maintenance phase. I am asking to myself if it is worth it to switch to C#3.0? ### Update: The project will have a web interface now so before entering the m...
No, I would advise not. I would advise starting 3.5 on new projects only, unless there is a specific reason otherwise. You will not have any benefit from 3.5 by just recompiling, since your code is already written (or at least 75% of it). If you need to migrate to 3.5 in the future, you can easily do it. Of course, yo...
**Clarification** C# 3.5 doesn't exist. There is C#1.0, C#2.0 and C#3.0. Then there is .NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, and .NET 3.5. We should not confuse the two. **C# 3.0 vs C#2.0** Now, is C#3.0 worth the move? I would say that with the existence of Extension methods and Lambda expressions, the answ...
Is the C# 2.0 to C# 3.0 transition worth it for this project?
[ "", "c#", ".net", "project-management", "code-migration", "" ]
I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we're interested in using JDBC to connect to a MySQL instance which only has UNIX domain sockets enabled. It doesn't look like this is supported, but from what I've read it should be at least possible to...
Checkout the JUDS library. It is a Java Unix Domain Socket library... <https://github.com/mcfunley/juds>
You could use junixsocket: <https://github.com/kohlschutter/junixsocket> It already provides code for connecting to MySQL from Java (Connector/J) via Unix sockets. One big advantage compared to other implementations is that junixsocket uses the standard Java Socket API.
UNIX socket implementation for Java?
[ "", "java", "unix", "jdbc", "unix-socket", "" ]
This has been an adventure. I started with the looping duplicate query located in [my previous question](https://stackoverflow.com/questions/161960), but each loop would go over all **17 million records**, **meaning it would take weeks** (just running `*select count * from MyTable*` takes my server 4:30 minutes using M...
Seeing the QueryPlan would help. Is this feasible? ``` SELECT m.* into #temp FROM tl_acxiomimport.dbo.tblacxiomlistings m inner join (SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, lon...
Something's up with your DB, server, storage or some combination thereof. 4:30 for a select count \* seems VERY high. Run a DBCC\_SHOWCONTIG to see how fragmented your table is, this could cause a major performance hit over a table that size. Also, to add on to the comment by RyanKeeter, run the show plan and if ther...
SQL Duplicate Delete Query over Millions of Rows for Performance
[ "", "sql", "sql-server", "duplicate-data", "sql-delete", "" ]
How to get the checked option in a group of radio inputs with JavaScript?
``` <html> <head> <script type="text/javascript"> function testR(){ var x = document.getElementsByName('r') for(var k=0;k<x.length;k++) if(x[k].checked){ alert('Option selected: ' + x[k].value) } } </script> </head> <body> <form> <inpu...
<http://www.somacon.com/p143.php>
How to get the checked option in a group of radio inputs with JavaScript?
[ "", "javascript", "" ]
Does anyone know how to resize images proportionally using JavaScript? I have tried to modify the DOM by adding attributes `height` and `width` on the fly, but seems did not work on IE6.
To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto. ``` image.style.width = '50%' image.style.height = 'auto' ``` This will ensure that its aspect ratio remains the same. Bear in mind that browsers tend to *suck* at resizing images nicely - you'll...
okay it solved, here is my final code ``` if($(this).width() > $(this).height()) { $(this).css('width',MaxPreviewDimension+'px'); $(this).css('height','auto'); } else { $(this).css('height',MaxPreviewDimension+'px'); $(this).css('width','auto'); } ``` Thanks guys
Javascript Image Resize
[ "", "javascript", "internet-explorer-6", "image-manipulation", "" ]
I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type. I know that, for example, if you just want to open a file using that application you can use something like: ``` System.Diagnostics.Process.S...
You can check under registry section `HKEY_CLASSES_ROOT` for the extension and action details. Documentation for this is [on MSDN](http://msdn.microsoft.com/en-us/library/cc144148.aspx). Alternatively, you can use the [IQueryAssociations](http://msdn.microsoft.com/en-us/library/bb761400.aspx) interface.
All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically [AssocQueryString](http://msdn.microsoft.com/en-us/library/bb773471.aspx): ``` using System.Runtime.InteropServices; [Dl...
Finding the default application for opening a particular file type on Windows
[ "", "c#", ".net", "windows", "file-type", "" ]
The code is ``` return min + static_cast<int>(static_cast<double>(max - min + 1.0) * (number / (UINT_MAX + 1.0))); ``` number is a random number obtained by rand\_s. min and max are ints and represent minimum and maximum values (inclusive). If you provide a solution not using unsigned int as a number, please also ...
The `static_cast<double>` is redundant because the "+1.0"s will cause promotion to double anyway.
@[Andrew Stein](https://stackoverflow.com/questions/140786/how-to-simplify-this-code-generates-a-random-int-between-min-and-max-base-on-un#140826) In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Pr...
How to simplify this code (generates a random int between min and max base on unsigned int)?
[ "", "c++", "random", "" ]
I was browsing Scott Hanselman's [Developer Interview question list](http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx), and ran across this question: > What is wrong with > DateTime.Parse(myString)? While I know there are inherent risks in parsing a string of unknow format...
In addition the locale problem, `DateTime.Parse()` could also throw an exception which you would then have to catch. Use `DateTime.TryParse()` or `DateTime.TryParseExact()` instead.
Using the current thread culture on the system is often a bad idea, as is "try a variety of formats, and see if any of them work." ParseExact with a specific culture is a much more controlled and precise approach. (Even if you specify the current culture, it makes it more obvious to readers that that's what's going on...
What is wrong with DateTime.Parse(myString)?
[ "", "c#", "datetime", "" ]
Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/100...
There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an ...
In C# most data types are not nullable (numbers, dates, etc), only strings are nullables. If you are getting data from a DB, then you will probable be working with [Nullable](http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx), or its syntactic-sugared version, int?, double?, DateTime?, etc. All nullables have [a m...
Helper functions for safe conversion from strings
[ "", "c#", "vb6", "type-conversion", "" ]
*[NOTE: This questions is similar to but **not the same** as [this one](https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events).]* Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros)...
As far as I can tell, the method described in the question is the only way to pass build variables to a Python script. Perhaps Visual Studio 2010 has something better?
You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macr...
How to pass all Visual Studio 2008 "Macros" to Python script?
[ "", "python", "visual-studio", "visual-studio-2008", "visual-c++", "visual-studio-2005", "" ]
I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?
The best-known library is [PIL](http://effbot.org/zone/pil-index.htm). However if you are simply doing basic manipulation, you are probably better off with the Python bindings for [ImageMagick](http://wiki.python.org/moin/ImageMagick), which will be a good deal more efficient than writing the transforms in Python.
Depending on what you mean by "image processing", a better choice might be in the numpy based libraries: [mahotas](http://luispedro.org/software/mahotas), [scikits.image](http://scikit-image.org), or [scipy.ndimage](http://www.scipy.org/SciPyPackages/Ndimage). All of these work based on numpy arrays, so you can mix and...
Image Processing, In Python?
[ "", "python", "image", "image-processing", "image-manipulation", "" ]
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. ie. 50 + 100 = 150 int.Max + 50 = int.Max and not int.Min + 50
``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` Update: If your penalties can be negative, this would be more appropriate: ``` int penaltySum(int a, int b) { if (a > 0 && b > 0) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } if (a ...
This answer... ``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` fails the following test: ``` [TestMethod] public void PenaltySumTest() { int x = -200000; int y = 200000; int z = 0; Assert.AreEqual(z, penaltySum(x, y)); } ``` I would suggest imple...
Looking for a .NET Function that sums up number and instead of overflowing simply returns int.MaxValue
[ "", "c#", ".net", "math", "" ]
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example: ``` select * from [User] where UserRolesBitmask | 22 = 22 ``` This selects all users that have the roles '2', '4' or '16' in their bit...
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. ``` from u in DataContext.Users where UserRolesBitmask | 22 == 22 select u ```
As a side note though for my fellow googlers: `UserRolesBitmask | 22 == 22` selects all users that don't have any other flags (its not a filter, its like saying `1==1`). What you want is either: * `UserRolesBitmask & 22 == 22` which selects users which have all the roles in their bitmask or: * `UserRolesBitmask & 22 ...
Can LINQ (to SQL) do bitwise queries?
[ "", "c#", "linq-to-sql", "bitmask", "" ]
I've got a dictionary, something like ``` Dictionary<Foo,String> fooDict ``` I step through everything in the dictionary, e.g. ``` foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); ``` It does that in the order the foos were added to the dictionary, so the first item added is the first foo return...
If you read the documentation on MSDN you'll see this: "The order in which the items are returned is undefined." You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavio...
You may be interested in the [`OrderedDicationary`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary) class that comes in [`System.Collections.Specialized`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized) namespace. If you look at the comments a...
Change cardinality of item in C# dictionary
[ "", "c#", "dictionary", "cardinality", "" ]
What is the best way to detect if a user leaves a web page? The `onunload` JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser). Creating one will probably be blocked by current browsers.
Try the `onbeforeunload` event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo *[onbeforeunload Demo](https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm)*. Alternatively, you can send out a...
Mozilla Developer Network has a nice description and example of [onbeforeunload](https://developer.mozilla.org/en/DOM/window.onbeforeunload). If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data): ``` window.addEventListener('beforeunload', function(e) { var...
Best way to detect when a user leaves a web page?
[ "", "javascript", "" ]
I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole w...
Haven't tried it myself, but I think <http://www.playframework.org/> has a lot of potential... coming from php and classic asp, it's the first java web framework that sounds promising to me.... *Edit by original question asker - 2011-06-09* Just wanted to provide an update. I went with Play and it was exactly wha...
(Updated for Spring 3.0) I go with [Spring MVC](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html) as well. You need to download Spring from [here](http://www.springframework.org/download) To configure your web-app to use Spring add the following servlet to your `web.xml` ```...
Can anyone recommend a simple Java web-app framework?
[ "", "java", "web-frameworks", "" ]
I got a program that writes some data to a file using a method like the one below. ``` public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permission...
**UPDATE:** Modified the code based on [this answer](https://stackoverflow.com/a/4397002/11702) to get rid of obsolete methods. You can use the Security namespace to check this: ``` public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermissio...
When your code does the following: 1. Checks the current user has permission to do something. 2. Carries out the action that needs the entitlements checked in 1. You run the risk that the permissions change between *1* and *2* because you can't predict what else will be happening on the system at runtime. Therefore, ...
How do you check for permissions to write to a directory or file?
[ "", "c#", ".net", "" ]
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: ``` if (datetime.now() - self.timestamp) > 100 # Where 100 is either seconds or minutes ``` This generates a type error. What is the proper way to do date time comparison in pytho...
Use the `datetime.timedelta` class: ``` >>> from datetime import datetime, timedelta >>> then = datetime.now() - timedelta(hours = 2) >>> now = datetime.now() >>> (now - then) > timedelta(days = 1) False >>> (now - then) > timedelta(hours = 1) True ``` Your example could be written as: ``` if (datetime.now() - self....
Compare the difference to a timedelta that you create: ``` if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5): print 'older' ```
Python Date Comparisons
[ "", "python", "datetime", "" ]
I've been trying to consider how Row Level Security could be implemented with the Entity Framework. The idea is to have a database agnostic means that would offer methods to restrict the rows coming from the ObjectContext. Some of my inital ideas have involved modifying the partial classes created by the EDMGEN tool a...
Sure you can do it. The important thing to do is to block direct access to the object context (preventing users from building their own ObjectQuery), and instead give the client a narrower gateway within which to access and mutate entities. We do it with the [Entity Repository pattern](http://www.martinfowler.com/eaaCa...
The place where you add security really depends on who you're trying to secure against. If, for example, you were securing a web site, then adding the filtering at the context level would be sufficient, because the "users" in this case are on the web site. They have no choice but to go through your context, since you ...
Row Level Security with Entity Framework
[ "", "c#", "database", "security", "entity-framework", "row-level-security", "" ]
I've been working with sessions, MVC design and object oriented PHP. Where should I save or retrieve data from a session? I would like to retrieve it from within methods so I don't have to pass the data to the methods. Whats the best practice?
I typically put this inside the controller. It just makes sense.. The controller decides what happens and why not let it decide if people are allowed to do the requested actions. Typically you have multiple controllers in a MVC system. Eg. BaseController (abstract - common), NonSessionController extends BaseController ...
Personally, I'm a huge fan of the [Zend\_Session](http://framework.zend.com/manual/en/zend.session.html#zend.session.introduction) wrapper class. I prefer to work with data in an object-oriented style and the namespacing advantage to using a wrapper is a huge plus. Which of these looks better to you? ``` $_SESSION['Z...
Best way to use sessions with MVC and OO PHP
[ "", "php", "oop", "session", "" ]
Is there a good Eclipse plugin for recording and playing back macros? I've tried [this one](http://web.archive.org/web/20161025001953/http://www.bdaum.de:80/eclipse/), but it didn't do me any good- it seemed like it wasn't ready for prime time. I know about editor templates, but I'm looking for something that I can u...
I put something together over the last month or so that you may find useful. It has limitations since the Eclipse editor/commands weren't designed with macro support in mind, but I think it works reasonably well. I just posted [Practical Macro](http://sourceforge.net/projects/practicalmacro/files/) at SourceForge a cou...
Emacs+ Version 3.x adds keyboard macros (<http://www.mulgasoft.com/emacsplus>) to its feature set.
Is there a macro recorder for Eclipse?
[ "", "java", "eclipse", "ide", "editor", "macros", "" ]
We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. The "old" way of doing things was to generate a (bad) password, give it to the partner with an I...
### Password Generation As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML. Entropy is used to measure password quality. So, choosing each bit with a ...
I'm unclear why transmitting the passwords over SSL -- via HTTPS -- is being considered "insecure" by your audit team. So when you ask for two things, it seems the second -- ensuring that the passwords are being transmitted in a secure way -- is already being handled just fine. As for the first, we'd have to know what...
How would you implement a secure static login credentials system in Java?
[ "", "java", "security", "encryption", "https", "" ]
I've been using various javascript frameworks including mootools, jquery, prototype and scriptaculous and have found them all good, but difficult to extend to more complex ideas. If I am going to knuckle down and learn one, which is the simplest to extend and use whilst staying powerful enough to use in a variety of d...
I propose jQuery. I'll give you some of the major arguments from the presentation that my team put on yesterday for senior management to convince them of that. Reasons: 1. Community acceptance. Look at [this graph](http://google.com/trends?q=jquery%2C+prototype%2C+yui%2C+scriptaculous+&ctab=0&geo=all&date=all&sort=0...
In my opinion, jQuery is exceptionally powerful and simple. It uses CSS selector syntax to pull back elements and only adds two functions to the global namespace: jQuery() and $(), which is an alias for jQuery(). There are a massive number of plugins available for jQuery to let you do things like create slide shows, a...
Which Javascript Framework is the simplest and most powerful?
[ "", "javascript", "frameworks", "" ]
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. What is the best way to achieve this?
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than). However; if you just want it to work, then in .NET 3.5 there are some opt...
I found that IL can actually handle this quite well. Ex. ``` ldarg.0 ldarg.1 add ret ``` Compiled in a generic method, the code will run fine as long as a primitive type is specified. It may be possible to extend this to call operator functions on non-primitive types. See [here](http://graphicsnut.blogspot.com/2011/...
Solution for overloaded operator constraint in .NET generics
[ "", "c#", "generics", "operator-overloading", "constraints", "" ]
I have a command line executable that alters some bits in a file that i want to use from my program. Is it possible to create my own executable that uses this tool and distribute only one executable? [edit] Clarification: The command line tool takes an offset and some bits and changes the bits at this offset in a giv...
It would be easier to roll your own implementation of this program than to write the wrapper; it sounds like it is trivial -- just open the file, seek to the right location, write your bits, close the file, you're done.
The easiest way is to embed this exe into your own and write it to disk to run it.
Combining two executables
[ "", "c++", "command-line", "assembly", "executable", "" ]
The system I work on here was written before .net 2.0 and didn't have the benefit of generics. It was eventually updated to 2.0, but none of the code was refactored due to time constraints. There are a number of places where the code uses ArraysLists etc. that store things as objects. From performance perspective, how...
Technically the performance of generics is, as you say, better. However, unless performance is hugely important AND you've already optimised in other areas you're likely to get MUCH better improvements by spending your time elsewhere. I would suggest: * use generics going forward. * if you have solid unit tests then ...
Here's the results I got from a simple parsing of a string from a 100KB file 100,000 times. The Generic List(Of char) took 612.293 seconds to go 100,000 times through the file. The ArrayList took 2,880.415 seconds to go 100,000 times through the file. This means in this scenario (as your mileage *will* vary) the Generi...
Generics vs. Array Lists
[ "", "c#", "performance", "generics", "" ]
I have a desktop application written in C#. It is trying to manage a socket connection and fails. The same application is successful if it is attached to the Visual Studio debugger. How can it be debugged?
This is a classic example of timing. If it works in the debugger then it means you have to re-factor your code a bit to handle this. Now if you are app is a server socket that receives connections from client and trying to spawn a thread for each of those connections, you might have to consider using select() to mana...
I'd say timing issues too having the debugger attached will slow down the code slightly which might mean that a race condition isn't occuring. To debug it try to add some logging code to your application, I personally use [log4net](http://logging.apache.org/log4net/index.html) You shouldn't have and problems with mal...
Why would an application act differently after the VS debugger is attached?
[ "", "c#", "visual-studio", "sockets", "debugging", "" ]
I would like to keep the overhead at a minimum. Right now I have: ``` // Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the use...
You can use "OK" and "Cancel" By substituting `MessageBoxButtons::YesNo` with `MessageBoxButtons::OKCancel` [MessageBoxButtons Enum](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx) Short of that you would have to create a new form, as I don't believe the Enum can be extended.
From everything I can find it looks like [Corin](https://stackoverflow.com/users/1736/corin) is right. Here is the code that I used to accomplish the original goal. I am not usually a Managed C++ programmer, so any editing would be appreciated. CustomMessageBox.h: ``` using namespace System::Windows::Forms; /// <sum...
What is an easy way to create a MessageBox with custom button text in Managed C++?
[ "", "c++", "" ]
If I have an object implementing the `Map` interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
``` Map<String, String> map = ... for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ``` On Java 10+: ``` for (var entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } ```
To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write: 1. Using **iterator** and **Map.Entry** ``` long ...
How do I efficiently iterate over each entry in a Java Map?
[ "", "java", "dictionary", "collections", "iteration", "" ]
It seems that C# 3 hit me without me even noticing, could you guys tell me about good in depth guides to C# 3? from lambda to linq to everything else that was introduced with the third version of the language. Printed books would be nice, but online guides would be even better!
[ScottGu](http://weblogs.asp.net/scottgu/default.aspx) has some great posts on C# 3: * [The C# ?? null coalescing operator (and using it with LINQ)](http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx) * [LINQ to SQL: Part 8](http://weblogs.asp.net/scottgu/a...
There are some high quality blogs out there. some of my favorites: [Eric Lippert](http://blogs.msdn.com/ericlippert/archive/tags/Lambda+Expressions/default.aspx), [Eric White](http://blogs.msdn.com/ericwhite/pages/FP-Tutorial.aspx), [Scott Gu](http://weblogs.asp.net/scottgu/archive/tags/LINQ/default.aspx)
Where can i find a good in depth guide to C# 3?
[ "", "c#", "documentation", "c#-3.0", "" ]
What’s the best way to capitalize the first letter of each word in a string in SQL Server.
From <http://www.sql-server-helper.com/functions/initcap.aspx> ``` CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) RETURNS VARCHAR(4000) AS BEGIN DECLARE @Index INT DECLARE @Char CHAR(1) DECLARE @PrevChar CHAR(1) DECLARE @OutputString VARCHAR(255) SET @OutputString = LOWER(...
As a table-valued function: ``` CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX)) RETURNS TABLE AS RETURN WITH a AS ( SELECT ( SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()' FROM string_split(@v, ' ') ORDER BY CHARINDEX(value,@v) FOR XML PATH (''), ...
How to capitalize the first letter of each word in a string in SQL Server
[ "", "sql", "sql-server", "string", "" ]
I'm building a Django project that needs search functionality, and until there's a `django.contrib.search`, I have to choose a search app. So, which is the best? By "best" I mean... * easy to install / set up * has a Django- or at least Python-friendly API * can perform reasonably complex searches Here are some apps ...
Check out [Haystack Search](http://haystacksearch.org/) - a new model based search abstraction layer that currently supports [Xapian](http://xapian.org/), [Solr](http://lucene.apache.org/solr/) and [Whoosh](https://bitbucket.org/mchaput/whoosh/wiki/Home). Looks like it's well supported and documented.
Justin, I'd try [djangosearch](http://code.google.com/p/djangosearch/) first: Jacob Kaplan-Moss (Django's lead developer) is working on it. Potential hazards: * The home page warns the API might not be entirely stable Potential benefits: * “The long term goal is for this to become `django.contrib.search`.”
What's the best Django search app?
[ "", "python", "django", "search", "search-engine", "" ]
What is the proper way to minimize a WinForms app to the system tray? Note: minimize to ***system tray***; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set Sh...
There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it: Some good info here (In the comments not the post): <http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx> And here it is in C++: <http://www.codeproject.com/KB/she...
``` this.WindowState = FormWindowState.Minimized ``` That is the built in way to do it and it looks fine to me most of the time. The only time is has some weirdness to it is if you call it on startup which has some weirdness sometimes which is why most people will also set the ShowInTaskbar = false and hide the form t...
What's the proper way to minimize to tray a C# WinForms app?
[ "", "c#", "winforms", "trayicon", "" ]
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: ``` abstract class Animal { public Leg GetLeg() {...} } abstract class Leg { } class Dog : Ani...
The short answer is that GetLeg is invariant in its return type. The long answer can be found here: [Covariance and contravariance](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx) I'd like to add that while inheritance is usually the first abstraction tool that mo...
Clearly, you'll need a cast if you're operating on a broken DogLeg.
Why doesn't inheritance work the way I think it should work?
[ "", "c#", "oop", "inheritance", "covariance", "contravariance", "" ]
I have a number of data classes representing various entities. Which is better: writing a generic class (say, to print or output XML) using generics and interfaces, or writing a separate class to deal with each data class? Is there a performance benefit or any other benefit (other than it saving me the time of writin...
There's a significant performance benefit to using generics -- you do away with [boxing and unboxing](http://en.wikipedia.org/wiki/Boxing_(Computer_science)#Boxing). Compared with developing your own classes, it's a coin toss (with one side of the coin weighted more than the other). Roll your own only if you think you ...
Not only yes, but HECK YES. I didn't believe how big of a difference they could make. We did testing in VistaDB after a rewrite of a small percentage of core code that used ArrayLists and HashTables over to generics. 250% or more was the speed improvement. [Read my blog about the testing](https://web.archive.org/web/2...
Do C# Generics Have a Performance Benefit?
[ "", "c#", ".net", "performance", "generics", "" ]
I'm pretty sure the answer to this question is no, but in case there's some PHP guru is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of `'@'` Much like empty and isset do. You can pass in a variable you just made up ...
Summing up, the proper answer is **no, you shouldn't** (see caveat below). There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which y...
You don't get any error when a variable is passed by reference (PHP will create a new variable silently): ``` function myHappyFunction(&$var) { } ``` But I recommend against abusing this for hiding programming errors.
Php function argument error suppression, empty() isset() emulation
[ "", "php", "error-handling", "error-suppression", "" ]
I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are share...
**Context:** While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble. YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they'...
I believe [YSlow](http://developer.yahoo.com/yslow/) does, but be aware that unless all requests are over a loopback connection you shouldn't worry. The HTTP overhead of split-up files will impact performance *far* more than parsing, unless your CSS/JS files exceed several megabytes.
Javascript and CSS parsing performance
[ "", "javascript", "css", "performance", "" ]
I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL...
I'm working with C# and Postgres using **Npgsql2** component, and they work fast, I recommend you. You can download from <https://github.com/npgsql/Npgsql/releases> **Note:** If you want an application that works with any database you can use the **DbProviderFactory** class and make your queries using **IDbConnection...
**Npgsql** - .Net Provider for PostGreSQL - is an excellent driver. If you have used the more traditional ADO.NET framework you are really in luck here. I have code that connects to Oracle that looks almost identical to the PostGreSQL connections. Easier to transition off of Oracle and reuse brain cells. It supports a...
C# .NET + PostgreSQL
[ "", "c#", ".net", "postgresql", "" ]
Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?
``` // Store the formatted string in 'result' String result = String.format("%4d", i * j); // Write the result to standard output System.out.println( result ); ``` See [format](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)) and its [syntax](http://docs....
Strings are immutable types. You cannot modify them, only return new string instances. Because of that, formatting with an instance method makes little sense, as it would have to be called like: ``` String formatted = "%s: %s".format(key, value); ``` The original Java authors (and .NET authors) decided that a static...
Sprintf equivalent in Java
[ "", "java", "string", "formatting", "" ]
I have been looking at the new [Objective-J / Cappuccino](http://cappuccino.org/) javascript framework from [280North](http://280north.com/). They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, ...
The Objective-J Tools package (<http://cappuccino.org/download>) and the source on github now include a vim highlight module.
> the source on github now include a vim > highlight module. I've found just doing what is suggested here is not enough: * download the file as Francisco suggests * unzip, `cd Tools/` dir * run the shell, `sh install-tools` * copy the objj.vim file to vim dir, `cp Tools/Editors/objj.vim /usr/share/vim/vim71/syntax/` ...
Anyone know of Objective-J syntax highlighting in vi?
[ "", "javascript", "vi", "cappuccino", "objective-j", "" ]
We are currently using the ExtJS tree view in an application - a requirement has arisen requiring a user to select multiple nodes (which the tree view supports currently through a pluggable selection model) - but you can not then drag the multiple selections to another part of the tree. Does anyone know of an ajax con...
Got the same issue. I just found the solution : ``` ..new Ext.tree.TreePanel({ ... selModel : new Ext.tree.MultiSelectionModel() ... }) ```
Check out this post in the ExtJS forum that details how you can enable multi-select in a Javascript tree. <http://extjs.com/forum/showthread.php?t=28115>
Javascript tree views that support multiple item drag/drop
[ "", "javascript", "ajax", "treeview", "drag-and-drop", "extjs", "" ]
About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<https://example.com>") Is there a better w...
Please use [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) (HTTP Strict Transport Security) from <http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx> ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <r...
The other thing you can do is use [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) by returning the "Strict-Transport-Security" header to the browser. The browser has to support this (and at present, it's primarily Chrome and Firefox that do), but it means that once set, the browser won't make reques...
Best way in asp.net to force https for an entire site?
[ "", "c#", "asp.net", "vb.net", "webforms", "https", "" ]
I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
Create a new launch configuration (Python Run) **Main tab** Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory) Don't forget to add the root folder of your application in the PYTHONPATH zone **Arguments** Set the base directory to the root folder ...
If you'd rather not include your Python installation in your project's workspace to get paster, you can create a pure-Python driver like: ``` #!/usr/bin/env python from paste.script.serve import ServeCommand ServeCommand("serve").run(["development.ini"]) ``` ...and run/debug that in Eclipse. Note: this is running ...
Debug Pylons application through Eclipse
[ "", "python", "eclipse", "pylons", "pydev", "pyramid", "" ]