Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
> **Possible Duplicate:** > [Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?](https://stackoverflow.com/questions/5938802/are-function-and-function-functionally-equal-i) This is something I haven't quite figured out yet, but I have been using function(){}() just because ...
Peter Michaux discusses the difference in [An Important Pair of Parens](http://peter.michaux.ca/articles/an-important-pair-of-parens). Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, thi...
The extra set of parentheses makes it clearer that you are constructing a function and then calling it. It's a coding style thing, not a functionality thing.
Difference between (function(){})(); and function(){}();
[ "", "javascript", "syntax", "" ]
I'm not getting any errors as such just a minor performance issue. ``` EXPLAIN SELECT a.nid, a.title, a.uid, b.parent, b.weight, c.name, d.value FROM table1 AS a INNER JOIN table2 AS b ON a.vid = b.vid AND a.status = 1 INNER JOIN table3 AS c ON c.uid = a.uid INNER JOIN table4 AS d ON d.content_id = a.nid AND d.value_t...
`ALL` means all rows, not all columns. Since it says there are no possible keys, I'd guess that you don't have an index on d.content\_id or d.value\_type or d.function. If you wanted to be fancy, you could put an index across all 3 of those columns.
Are d.value\_type and d.function indexed fields? That would be initial instinct as to the cause.
What's wrong with my MySQL query?
[ "", "php", "mysql", "inner-join", "" ]
According to the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html): > If there are any enclosing try statements whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thr...
Throwing an exception from a finally block will also clobber the original exception (if any). EDIT: Found a reference explaining "abrupt completion". From [§14.1: Normal and Abrupt Completion of Statements](http://java.sun.com/docs/books/jls/third_edition/html/statements.html#5894): > An abrupt completion always ha...
`Sys.exit()` or forcing an abort. GUI programs in particular are notorious for calling `Sys.exit()` on an exception, partly because of a bug that survived until JVM 1.5 --- an exception thrown from the GUI thread didn't make it over to the Main thread. Update: especially to whomever downvoted this. Sorry, but Sys.exit...
What exactly is "Abrupt completion of a finally clause"?
[ "", "java", "try-catch", "" ]
I found some code in a project which looks like that : ``` int main(int argc, char *argv[]) { // some stuff try { theApp.Run(); } catch (std::exception& exc) { cerr << exc.what() << std::endl; exit(EXIT_FAILURE); } return (EXIT_SUCCESS); } ``` I don't understand why the exceptions are being catched. If t...
If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called. So, if you aren't running under the debugger, it's pr...
Try-catch in the main function hides the exception from debugger. I would say, it isn't good. On the other hand, customers are not expected to have debuggers, so catching exceptions is nice. So it is good. Personally, I catch all exceptions in main function, when making a release build, and I don't do that, when buil...
Does it make sense to catch exceptions in the main(...)?
[ "", "c++", "exception", "" ]
I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information. With the help of a few online tutorials, I've managed to get the Javascript to display a ...
Setup the `onchange` event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division. ``` <html> <head> <script type="text/javascript"> window.onload = function() { var eSelect =...
After reading Tom's great response, I realised that if I ever added other options to my form it would break. In my example this is quite likely, because the options can be added/deleted using a php admin panel. I did a little reading and altered it ever so slightly so that rather than using **selectedIndex** it uses *...
Javascript - onchange within <option>
[ "", "javascript", "html", "" ]
When I run my tests in Visual Studio individually, they all pass without a problem. However, when I run all of them at once some pass and some fail. I tried putting in a pause of 1 second in between each test method with no success. Any ideas? Thanks in advance for your help...
It's possible that you have some shared data. Check for static member variables in the classes in use that means one test sets a value that causes a subsequent test to fail. You can also debug unit tests. Depending on the framework you're using, you should be able to run the framework tool as a debug start application...
It's very possible that some modifications/instantiations done in one test affect the others. That indicates poor test design and lack of proper isolation.
Testing in Visual Studio Succeeds Individually, Fails in a Set
[ "", "c#", ".net", "visual-studio", "unit-testing", "" ]
I have a VB background and I'm converting to C# for my new job. I'm also trying to get better at .NET in general. I've seen the keyword "T" used a lot in samples people post. What does the "T" mean in C#? For example: ``` public class SomeBase<T> where T : SomeBase<T>, new() ``` What does `T` do? Why would I want to ...
It's a symbol for a [generic type parameter](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx). It could just as well be something else, for example: ``` public class SomeBase<GenericThingy> where GenericThingy : SomeBase<GenericThingy>, new() ``` Only T is the default one used and encouraged by Microsoft.
T is not a keyword per-se but a placeholder for a generic type. See Microsoft's [Introduction to Generics](http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx) The equivalent VB.Net syntax would be: ``` Public Class SomeBase(Of T As {Class, New})) ```
What does "T" mean in C#?
[ "", "c#", ".net", "generics", "" ]
I want my JTextPane to insert spaces whenever I press Tab. Currently it inserts the tab character (ASCII 9). Is there anyway to customize the tab policy of JTextPane (other than catching "tab-key" events and inserting the spaces myself seems an)?
You can set a javax.swing.text.Document on your JTextPane. The following example will give you an idea of what I mean :) ``` import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JTextPane; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.D...
As far as I know, you'd have to catch key events, as you say. Depending on usage, you might also get away with waiting until the input is submitted, and changing tabs to spaces at that time.
Setting the tab policy in Swing's JTextPane
[ "", "java", "swing", "jtextpane", "" ]
The company I work for sells a J2EE application that runs on Tomcat, WebSphere, or WebLogic. We have a customer that is trying to decide between Tomcat and WebSphere. They're leaning towards WebSphere because they're concerned that Tomcat has more security holes. After searching around on the web, I've been unable to ...
I'd say use tomcat over WebSphere if at all possible. I think 99% of security is how you set it all up. Are you also evaluating the security implications of Apache HTTP Server, IBM HTTP Server, and IIS? Security involves so much more than just what application server you choose to run your webapp on. [Tomcat securi...
It's interesting that your client is "concerned that Tomcat has more security holes." I wonder if they could list what those holes are? If they can't, it's hearsay and FUD. I would say that all web servers/servlet engines suffer from the same issues. It's the applications that are deployed on them that represent the r...
Security of Tomcat versus WebSphere versus WebLogic
[ "", "java", "tomcat", "jakarta-ee", "websphere", "weblogic", "" ]
I want to write an Exception to an MS Message Queue. When I attempt it I get an exception. So I tried simplifying it by using the XmlSerializer which still raises an exception, but it gave me a bit more info: > {"There was an error reflecting type > 'System.Exception'."} with InnerException: > {"Cannot serialize mem...
I think you basically have two options: 1. Do your own manual serialization (probably do NOT want to do that). XML serialization will surely not work due to the exact message you get in the inner exception. 2. Create your own custom (serializable) exception class, inject data from the thrown Exception into your custom...
I was looking at Jason Jackson's answer, but it didn't make sense to me that I'm having problems with this even though System.Exception implements ISerializable. So I bypassed the XmlSerializer by wrapping the exception in a class that uses a BinaryFormatter instead. When the XmlSerialization of the MS Message Queuing ...
In C#, how can I serialize System.Exception? (.Net CF 2.0)
[ "", "c#", "exception", "serialization", "compact-framework", "" ]
I have a column containing items that can be sorted by the user: ``` DOC_ID DOC_Order DOC_Name 1 1 aaa 2 3 bbb 3 2 ccc ``` I'm trying to figure out a way to properly initialize DOC\_Order when the entry is created. A good value would either be the corresponding DO-CID ...
The syntax to add a default like that would be ``` alter table DOC_Order add constraint df_DOC_Order default([dbo].[NEWDOC_Order]()) for DOC_Order ``` Also, you might want to alter your function to handle when DOC\_Order is null ``` Create FUNCTION [dbo].[NEWDOC_Order] ( ) RETURNS int AS BEGIN RETURN (SELECT IS...
IF someone wants to do it using the interface, typing ``` [dbo].[NEWDOC_Order]() ``` does the trick. You apparently need all brackets or it will reject your input.
Bind a column default value to a function in SQL 2005
[ "", "sql", "sql-server-2005", "t-sql", "default-value", "" ]
I would like to be able to do somthing like the following: ``` //non-generic var MyTable = new Table(); string name = MyTable.Name; IEnumerable<String> rows = MyTable.Rows; //generic var MyTableGeneric = new Table<MyType>(); string name = MyTableGeneric.Name; IEnumerable<MyType> rows = MyTableGeneric .Rows; ``` Woul...
I'd say the second design is better. Less items and easier inheritance path. The first design has unnecessary interfaces, which you don't really need unless you're implementing something else which implements the interface, but doesn't inherit from the base class.
What's the difference betweeen a `Table` and a `Table<string>`? In other words, can you not just use `Table<string>` as your nongeneric form? If you *do* go for the second option, I'd suggest renaming one of your `Rows` properties - you may be able to get away with having two properties of different types through hidi...
Is this design a good idea - Interfaces and Abstract class
[ "", "c#", "generics", "interface", "abstract-class", "" ]
Is there a way to get all alphabetic chars (A-Z) in an array in PHP so I can loop through them and display them?
``` $alphas = range('A', 'Z'); ``` Documentation: <https://www.php.net/manual/en/function.range.php>
To get both upper and lower case merge the two ranges: ``` $alphas = array_merge(range('A', 'Z'), range('a', 'z')); ```
Way to get all alphabetic chars in an array in PHP?
[ "", "php", "" ]
I use RedGate SQL data compare and generated a .sql file, so I could run it on my local machine. But the problem is that the file is over 300mb, which means I can't do copy and paste because the clipboard won't be able to handle it, and when I try to open the file in SQL Server Management Studio I get an error about th...
From the command prompt, start up `sqlcmd`: ``` sqlcmd -S <server> -i C:\<your file here>.sql ``` Just replace `<server>` with the location of your SQL box and `<your file here>` with the name of your script. Don't forget, if you're using a SQL instance the syntax is: ``` sqlcmd -S <server>\instance. ``` Here is th...
I had exactly the same issue and had been struggling for a while then finally found the solution which is to set `-a` parameter to the `sqlcmd` in order to change its default packet size: ``` sqlcmd -S [servername] -d [databasename] -i [scriptfilename] -a 32767 ```
How do you import a large MS SQL .sql file?
[ "", "sql", "sql-server", "import", "" ]
Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that `synchronized(this)` should be avoided. Instead, they claim, a lock on a private reference is to be preferred. Some of the given reasons are: * [some *evil code* may steal your lock](https://stackoverflow.com/qu...
I'll cover each point separately. 1. > Some evil code may steal your lock (very popular this one, also has an > "accidentally" variant) I'm more worried about *accidentally*. What it amounts to is that this use of `this` is part of your class' exposed interface, and should be documented. Sometimes the ability o...
Well, firstly it should be pointed out that: ``` public void blah() { synchronized (this) { // do stuff } } ``` is semantically equivalent to: ``` public synchronized void blah() { // do stuff } ``` which is one reason not to use `synchronized(this)`. You might argue that you can do stuff around the `sync...
Avoid synchronized(this) in Java?
[ "", "java", "multithreading", "synchronization", "synchronized", "" ]
I'm running on a shared \*NIX server (run by Site5). I have a php script that runs in the background occasionally doing some offline calculations. It uses around 100% CPU while it runs. I've tried nice-ing it, like this: ``` nice -n 19 php script.php ``` but that doesn't seem to make any difference.
You could scatter usleep ( int $micro\_seconds ) through your code. This will force your script to stop for tiny amounts of time leaving the CPU free for other things. Will that be necessary though? If you script has a low priority, does it matter that it's using 100% of the CPU... If other processes with a higher pri...
Even niced, it'll use 100% CPU if available. However, the kernel will give priority to any other (non-niced) processes that come along.
How do I make php nicer to the CPU?
[ "", "php", "nice", "" ]
Instruction on accessing a interface to an application, in **plain** C/C++ **without**: * MFC * ATL * WTL Basically, I would like to make use of a COM object. Working sample source code or guidance - to **using** (functionality) a COM object, **not** creating a COM server. Regards
Here is a simple example in plain C++: ``` CoInitialize(NULL); // absolutely essential: initialize the COM subsystem IMyInterface* pIFace; // create the object and obtain a pointer to the sought interface CoCreateInstance(CLSID_MyObject, NULL, CLSCTX_ALL, IID_IMyInterface, &pIFace); pIFace->MethodIReallyNeed(); // use...
There's an article on CodeProject, [Introduction to COM - What It Is and How to Use It](http://www.codeproject.com/KB/COM/comintro.aspx) that you may find useful. It gives a pretty good introduction and a worked example.
Use of CoGetClassObject() in C - access COM Object interface
[ "", "c++", "c", "windows", "com", "" ]
still trying to find where i would use the "yield" keyword in a real situation. I see this thread on the subject [What is the yield keyword used for in C#?](https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c) but in the accepted answer, they have this as an example where someone is ite...
If you build and return a List (say it has 1 million elements), that's a big chunk of memory, and also of work to create it. Sometimes the caller may only want to know what the first element is. Or they might want to write them to a file as they get them, rather than building the whole list in memory and then writing ...
Yield allows you to build methods that produce data without having to gather everything up before returning. Think of it as returning multiple values along the way. Here's a couple of methods that illustrate the point ``` public IEnumerable<String> LinesFromFile(String fileName) { using (StreamReader reader = new...
Yield keyword value added?
[ "", "c#", "iterator", "ienumerable", "yield", "" ]
I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax. Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. The way this is currently working is very simple: the templates have ...
Use a real template tool: [mako](http://www.makotemplates.org/) or [jinja](http://jinja.pocoo.org/). Don't roll your own. Not worth it.
Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi)
Hiding implementation details on an email templating system written in Python
[ "", "python", "email", "formatting", "templates", "" ]
Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement? ``` [pseudocode] my_sequence = (2,5,7,82,35) if all the values in (type(i) for i in my_sequence) == int: do() ``` Instead of, say: ``` my_sequence = (2,5,7,82,35) all_int = True for i in my_sequence...
Use: ``` all( type(i) is int for i in lst ) ``` Example: ``` In [1]: lst = range(10) In [2]: all( type(i) is int for i in lst ) Out[2]: True In [3]: lst.append('steve') In [4]: all( type(i) is int for i in lst ) Out[4]: False ``` [Edit]. Made cleaner as per comments.
Do you mean ``` all( type(i) is int for i in my_list ) ``` ? Edit: Changed to `is`. Slightly faster.
If all in list == something
[ "", "python", "python-2.6", "" ]
I was just reading through ["Learning Python" by Mark Lutz and came across this code sample](http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false): ``` >>> L = ['grail'] >>> L.append(L) >>> L ['grail', [...]] ``` It was identified as a cyclic data structure. ...
Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first. Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all t...
I recently created a cyclic data structure to represent the eight cardinal and ordinal directions. Its useful for each direction to know its neighbors. For instance, Direction.North knows that Direction.NorthEast and Direction.NorthWest are its neighbors. This is cyclic because each neighor knows its neighbors until i...
What is a cyclic data structure good for?
[ "", "python", "data-structures", "recursion", "cyclic-reference", "" ]
Does there exist any way in .Net to check before opening if a file (on a local network drive) is already in use?
You should try to access it and if it failed, you either don't have required permissions (which you can check with GetAccessControl) or it's locked by another process. But I don't think there is any reliable measure to distinguish a lock and a permission failure (since you might be able to read the file, but not able ...
This will do. FileShare.None as mentioned in MSDN : > None : Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed. ``` File.Open(name, FileMode.Open, FileAccess.Read, FileShare.None); ``` EDIT : Remember to wrap in a Try/Catch bloc...
Checking if the file is already in use before opening (network drive, C#)
[ "", "c#", "file", "readonly", "" ]
Whenever I read about Swing they say they are light weight components. So I just googled Swing and found that it means Swing does not depend on native peers. Is that why they are called **"light weight"**? I mean by light weight I thought maybe the Swing components occupy less memory than the AWT components. Isn't that...
[Swing](http://java.sun.com/docs/books/tutorial/uiswing/) is considered lightweight because it is fully implemented in Java, without calling the native operating system for drawing the graphical user interface components. On the other hand, [AWT](http://en.wikipedia.org/wiki/Abstract_Window_Toolkit) (Abstract Window T...
Lightweight vs heavyweight is a question of how the UI components are implemented. Heavyweight components wrap operating system objects, lightweight components don't. They are implemented strictly in the JDK.
Swing components are light-weight?
[ "", "java", "swing", "awt", "" ]
Does the Hibernate API support object result sets in the form of a collection other than a List? For example, I have process that runs hundreds of thousands of iterations in order to create some data for a client. This process uses records from a Value table (for example) in order to create this output for each iterat...
I assume you are referring to the [`Query.list()`](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Query.html#list()) method. If so: no, there is no way to return top-level results other than a `List`. If you are receiving too many results, why not issue a more constrained query to the database? If the query is ...
If I understand correctly, you load a bunch of data from the database to memory and then use them locally by looking for certain objects in that list. If this is the case, I see 2 options. 1. Dont load all the data, but for each iteration access the database with a query returning only the specific record that you ne...
Can Hibernate return a collection of result objects OTHER than a List?
[ "", "java", "hibernate", "" ]
Lately all modern programming languages have a definitive web site to support, distribute, learn the programming language, as well as community forums, e-mail lists and so on. Java has java.sun.com, python has python.org, etc. However C/C++ does not seem to have such a site. Which site do you use, say in a document, t...
[The C Programming Language](http://cm.bell-labs.com/cm/cs/cbook/)
Bjarne Stroustrup keeps a lot of interesting links on [his homepage](http://www.research.att.com/~bs/). The [FAQ](http://www.research.att.com/~bs/bs_faq.html) and [C++ glossary](http://www.research.att.com/~bs/glossary.html) are good references, but make sure you also check out [Did you really say that?](http://www.res...
What is the definitive link for C and C++ programming languages?
[ "", "c++", "c", "" ]
Sometimes Eclipse comes up saying "hey you should debug this line!!!" but doesn't actually close the program. I can then continue to play big two, and even go through the same events that caused the error the first time and get another error box to pop up! The bug is simple, I'll fix it, I just want to know why some b...
Programming mistakes can be categorized in these categories: 1. Compile-time errors, which are caught by the compiler at the time of compilation and without correcting them, it's not possible to run the program at all. 2. Run-time errors, which are not caught by the compiler but put the computer in a situation which i...
A previous answer gets the java-part of this right: > If an exception occurs in your main > thread, it may be terminal, but if it > occurs in another thread it is not > terminal. It's terminal for the main > thread if the other threads in the > application are daemon threads. The bigger truth is that the JVM that you...
what does it mean when a bug doesn't crash the program
[ "", "java", "eclipse", "crash", "" ]
I am compiling a c++ static library in vs2008, and in the solution i also have a startup project that uses the lib, and that works fine. But when using the lib in another solution i get an run-time check failure. "The value of ESP was not properly saved across a functioncall" Stepping through the code i noticed a func...
Forgive me for stating the bleeding obvious here, but... I've seen this sort of thing happen many times before when object (.o) and header (.h) files get out of sync. Especially with respect to virtual methods. Consider: The object file is compiled with header: ``` class Foo { virtual void f(); }; ``` But then the h...
This is most probably due to incompatible calling conventions, where the library and the caller have different ideas about stack layout. Take a look at [MSDN](http://msdn.microsoft.com/en-us/library/984x0h58(VS.80).aspx) for more info.
Function call jumps to the wrong function
[ "", "c++", "visual-studio-2008", "static", "stack-pointer", "" ]
As made clear in update 3 on [this answer](https://stackoverflow.com/questions/367440/javascript-associative-array-without-tostring-etc#367454), this notation: ``` var hash = {}; hash[X] ``` does not actually hash the object `X`; it actually just converts `X` to a string (via `.toString()` if it's an object, or some ...
Hash your objects yourself manually, and use the resulting strings as keys for a regular JavaScript dictionary. After all, you are in the best position to know what makes your objects unique. That's what I do. Example: ``` var key = function(obj){ // Some unique object-dependent key return obj.totallyUniqueEmploy...
# Problem description JavaScript has no built-in general *map* type (sometimes called *associative array* or *dictionary*) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the *object*, a special type of map which only accepts strings as keys and has special semanti...
JavaScript hashmap equivalent
[ "", "javascript", "data-structures", "language-features", "hashmap", "" ]
I'm using `FontMetrics.getHeight()` to get the height of the string, but it gives me a wrong value, cutting off the descenders of string characters. Is there a better function I can use?
The `getStringBounds()` method below is based on the `GlyphVector` for the current `Graphics2D` font, which works very well for one line string of text: ``` public class StringBoundsPanel extends JPanel { public StringBoundsPanel() { setBackground(Color.white); setPreferredSize(new Dimension(40...
What makes you think it returns the wrong value? It's far more probable that your expectation of what it returns does not match the specification. Note that it's perfectly fine if some glyphs in the Font go over or under those values. `getMaxDescent()` and `getMaxAscent()` should tell you the absolute maximum values o...
How to get real string height in Java?
[ "", "java", "fonts", "awt", "" ]
Does anyone know of a Javascript based [HAML](http://haml.hamptoncatlin.com/) editor out there? I'm looking for for something like [TinyMCE](http://tinymce.moxiecode.com/) that just understands HAML (so it does indenting and highlighting correctly) I'm thinking of using an editor like this for a dynamic website I'm bu...
I noticed this question hasn't been answered in a while. While this isn't a complete answer, you may want to look at [MarkItUp](http://markitup.jaysalvat.com/home/). Its specifically *not* a WYSIWYG editor, but rather, an extensible and friendly markup editor. It doesn't support HAML directly, but its fairly easy to ex...
HAML was designed as a more elegant way to define page structure; It was not intended to be used for formatting text, like what you're asking it to do. In this case, you're probably better off using something like [Markdown](http://daringfireball.net/projects/markdown/) or [Textile](http://www.textism.com/tools/textil...
Javascript HAML editor
[ "", "javascript", "haml", "" ]
I'm trying to write a function that is able to determine whether a string contains a real or an integer value. This is the simplest solution I could think of: ``` int containsStringAnInt(char* strg){ for (int i =0; i < strlen(strg); i++) {if (strg[i]=='.') return 0;} return 1; } ``` But this solution is really s...
You are using strlen, which means you are not worried about unicode. In that case why to use strlen or strchr, just check for '\0' (Null char) ``` int containsStringAnInt(char* strg){ for (int i =0;strg[i]!='\0'; i++) { if (strg[i]=='.') return 0;} return 1; } ``` Only one parsing through the string, t...
What's the syntax of your real numbers? 1e-6 is valid C++ for a literal, but will be passed as integer by your test.
Fastest way to determine whether a string contains a real or integer value
[ "", "c++", "optimization", "parsing", "" ]
Why would I want to use PHP's [filter](http://www.php.net/filter) library? Why wouldn't I? It seems to try and do a bit of clean-up (it's awful when you have to work with regular expressions), but on the other hand function naming and parameter constants seem to be a disaster, if you ask me. It must have been included...
My stance is that the concept of filtering input data is flawed on a conceptual level. See my reply to the almost similar question [What’s the best method for sanitizing user input with PHP?](https://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php#130323)
Probably the best resource for this is the tutorial linked to from the PHP manual page: <http://devolio.com/blog/archives/413-Data-Filtering-Using-PHPs-Filter-Functions-Part-one.html> It's decent enough for simple filtering, but if you don't find your use-case on that page it probably isn't for you.
PHP filter() function - why?
[ "", "php", "" ]
I'm trying to use SDL in C++ with Visual Studio 2008 Express. The following program compiles but does not link: ``` #include <SDL.h> int main(int argc, char *argv[]) { return 0; } ``` The link error is: ``` LINK : fatal error LNK1561: entry point must be defined ``` I get this regardless of how or if I link wi...
I don't have VC++ available at the moment, but I have seen this issue several times. You need to create a Win32 project as opposed to a console project. A Win32 project expects a [WinMain](http://msdn.microsoft.com/en-us/library/ms633559(VS.85).aspx) function as a program entry point. SDLmain.lib contains this entry p...
To me it helped to add the following lines before main(): ``` #ifdef _WIN32 #undef main #endif ``` [German Wikipedia](http://de.wikibooks.org/wiki/SDL:_Die_erste_SDL-Anwendung) also suggests to add these lines instead: ``` #ifdef _WIN32 #pragma comment(lib, "SDL.lib") #pragma comment(lib, "SDLmain.lib") #endif ``` ...
How do you get a minimal SDL program to compile and link in visual studio 2008 express?
[ "", "c++", "visual-studio", "sdl", "" ]
I am not talking about the highlight colors but the actual colors. I got a color scheme with light background color but the braces/parentheses are barely visible. Anyone knows how to change this? Btw this is for C# because C++ seems to color braces/parentheses using operator color.
Tools > Options > Fonts and Colors > "Display Items" : Plain Text Unfortunately this changes a lot more than just braces but its the only way to target them as far as I know.
The Visual Studio 2014 CTP 14.0.22129 dark theme blacked-out the brackets and semi-colon for some reason. I was able to fix this by changing the foreground color of the "Punctuation" display item.
How to change the braces/parenthesis colors in Visual Studio
[ "", "c#", "visual-studio", "ide", "" ]
I am going to try to build a PHP website using a framework for the first time, and after some research here and there, I've decided to try to use **[Kohana](http://kohanaframework.org)** I downloaded the source from their website, and ran the downloaded stuff on my web server, and was then greeted with a 'Welcome to K...
The "Kohana Tutorial" pages are pants. Not so much for their content, but for the fact that they have a pretty damn unorganised wordpress blog and finding useful info isn't exactly made easy. What they need is a post/page at <http://learn.kohanaphp.com> that lists the most important tutorials, rather than forcing you t...
I had exactly the same problem! After a few searches I found the Kohaha101.pdf. This guide/tutorial really got me started! Link:[<http://pixelpeter.com/kohana/kohana101.pdf>[1](http://pixelpeter.com/kohana/kohana101.pdf) Good luck and enjoy Kohana!
Searching for a Kohana Beginner's Tutorial for PHP
[ "", "php", "frameworks", "kohana", "" ]
I have a table in SQL Server 2005 which has three columns: ``` id (int), message (text), timestamp (datetime) ``` There is an index on timestamp and id. I am interested in doing a query which retrieves all messages for a given date, say '12/20/2008'. However I know that simply doing where timestamp='12/20/2008' wo...
``` -- avoid re-calculating @MyDate +1 for every row DECLARE @NextDay DateTime Set @NextDay = @MyDate + 1 SELECT -- ... WHERE [timestamp] >= @MyDate AND [timestamp] < @NextDay ```
The use of two datetime variables has always worked infallibly in my experience. The issue of the resolution seems highly unlikely. The important fact to remember, however, is that a range (of any type) includes both end points. So you can't test using BETWEEN on two dates, because it will include both. Rather use some...
How to query SQL Server table based on a specific date
[ "", "sql", "sql-server", "database", "" ]
I am reading file from ResultSet and it's required to save file into Oracle Database. ``` ... ResultSet rs = ... java.sql.Blob myfile = rs.getBlob("field") java.io.OutputStream os = ((oracle.sql.BLOB) myfile).getBinaryOutputStream(); ``` I get get this error message ``` java.lang.ClassCastException ``` Any one have...
I have found the solution. I'd like to share with those who has this problem. The code to get outputstream from oracle blob is: ``` java.io.OutputStream os = ((oracle.sql.BLOB) myBlob).setBinaryStream(1L); ``` setBinaryStream() is actually returning java.io.OutputStream object
`java.sql.Blob` [is an interface](http://java.sun.com/javase/6/docs/api/java/sql/Blob.html). Presumably the implementation returned in your `ResultSet` is a different implementation to `oracle.sql.BLOB`? What does `myfile.getClass()` return?
Why I cannot cast oracle BLOB from native java Blob
[ "", "java", "oracle", "blob", "classcastexception", "" ]
I'm currently trying to implement a class to handle secure communications between instances of my app using RSACrytoServiceProveider class. First question : is it a good idea implement a single class to handle sender/reciever roles or should i split the roles into individual classes ?. This is what i have done so far: ...
I would make the encrypt/sign/decrypt/verify methods take parameters for the data rather than having member variables for them. Having member variables for the key and provider seems okay though. Basically I'd expect to use the same key multiple times but not the same data. I'd also make it immutable - make all the va...
I have made some adjustments, here is what the implementation looks like: ``` using System; using System.Security.Cryptography; namespace Agnus.Cipher { public class RSA : IDisposable { private RSACryptoServiceProvider rSAProviderThis; private RSACryptoServiceProvider rSAProviderOther = null; ...
Implementing RSA in C#
[ "", "c#", "rsa", "rsacryptoserviceprovider", "" ]
``` game.h needs: - packet.h - socket.h socket.h needs: - game.h ``` The problem comes when I try to include `socket.h` into `game.h`, because `socket.h` has `game.h` included already. How do I solve these kind of problems?
The usual way, use #ifdef and #define in your header files inside game.h: ``` #ifndef GAME_H #define GAME_H .. rest of your header file here #endif ``` This way, the contents will be read multiple times, but only defined once. **Edit**: Removed underscores at start and end of identifier per comments.
The key is forward declaration. Take the stuff from `game.h` that is required in `socket.h` (or vice-versa) and forward-declare it in yet another header, e.g. `game_forwards.h`. As an example, consider the following: ``` // game_fwd.h #ifndef GAME_FWD_H #define GAME_FWD_H class game; #endif // ndef GAME_FWD_H // g...
How do I solve circular includes between header files?
[ "", "c++", "header-files", "" ]
I still feel C++ offers some things that can't be beaten. It's not my intention to start a flame war here, please, if you have strong opinions about not liking C++ don't vent them here. I'm interested in hearing from C++ gurus about why they stick with it. I'm particularly interested in aspects of C++ that are little ...
I have stayed with C++ as it is still the highest performing general purpose language for applications that need to combine efficiency *and* complexity. As an example, I write real time surface modelling software for hand-held devices for the surveying industry. Given the limited resources, Java, C#, etc... just don't ...
**RAII / deterministic finalization**. No, garbage collection is not *just as good* when you're dealing with a scarce, shared resource. **Unfettered access to OS APIs**.
What can C++ do that is too hard or messy in any other language?
[ "", "c++", "" ]
Does anyone know how to disable an ASP.NET validator using JavaScript? I'm using javascript style.display = 'none' to disable parts of a web page. However these disabled parts have asp.net validators that are still firing and I need to disable then without doing a round trip to the server. Thanks.
Use this snippet: ``` function doSomething() { var myVal = document.getElementById('myValidatorClientID'); ValidatorEnable(myVal, false); } ```
This is an old question but surprised the following answer it not given. I implemented it using of the comments above and works flawlessly ``` # enable validation document.getElementById('<%=mytextbox.ClientID%>').enabled = true #disable validation document.getElementById('<%=mytextbox.ClientID%>').enabled = false ``...
Disable ASP.NET validators with JavaScript
[ "", "asp.net", "javascript", "validation", "" ]
How can you check whether a **string** is **convertible** to an **int?** Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the **string** or use the parsed **int** value instead. *In JavaScript we had this [parseInt()](http://www.w3schools.com/jsref/jsref_parseInt.asp...
`Int32.TryParse(String, Int32)` - <http://msdn.microsoft.com/en-us/library/f02979c7.aspx> ``` bool result = Int32.TryParse(value, out number); if (result) { Console.WriteLine("Converted '{0}' to {1}.", value, number); } ```
Could you not make it a little more elegant by running the tryparse right into the if? Like so: ``` if (Int32.TryParse(value, out number)) Console.WriteLine("Converted '{0}' to {1}.", value, number); ```
Convert string to int and test success in C#
[ "", "c#", "string", "parsing", "int", "" ]
I want to do something like this: ``` c:\data\> python myscript.py *.csv ``` and pass all of the .csv files in the directory to my python script (such that `sys.argv` contains `["file1.csv", "file2.csv"]`, etc.) But `sys.argv` just receives `["*.csv"]` indicating that the wildcard was not expanded, so this doesn't w...
You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ). ``` from glob import glob filelist = glob('*.csv') #You can pass the sys.argv a...
In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself. Vinko is right: the glob module does the job: ``` import glob, sys for arg in glob.glob(sys.argv[1]): print "Arg:...
Passing arguments with wildcards to a Python script
[ "", "python", "windows", "command-line", "arguments", "" ]
I work on a project that uses multiple open source Java libraries. When upgrades to those libraries come out, we tend to follow a conservative strategy: 1. if it ain't broke, don't fix it 2. if it doesn't have new features we want, ignore it We follow this strategy because we usually don't have time to put in the new...
I've learned enough lessons to do the following: 1. Check the library's change list. What did they fix? Do I care? If there isn't a change list, then the library isn't used in my project. 2. What are people posting about on the Library's forum? Are there a rash of posts starting shortly after release pointing out obvi...
Important: Avoid [Technical Debt](http://en.wikipedia.org/wiki/Technical_debt). "If it ain't broke, don't upgrade" is a crazy policy that leads to software so broken that no one can fix it. Rash, untested changes are a bad idea, but not as bad as accumulating technical debt because it appears cheaper in the short run...
How do you decide when to upgrade a library in your project?
[ "", "java", "versioning", "" ]
Is it recommended to set member variables of a base class to protected, so that subclasses can access these variables? Or is it more recommended to set the member variables to private and let the subclasses get or set the varible by getters and setters? And if it is recommended to use the getters and setters method, w...
This is very *similar* to [this question](https://stackoverflow.com/questions/355787), about whether to access information within the same class via properties or direct access. It's probably worth reading all those answers too. Personally, I don't like any fields to be non-private with the occasional exception of sta...
Classes in other assemblies can derive from your unsealed classes and can access protected fields. If you one day decide to make those fields into properties, those classes in other assemblies will need to be recompiled to work with the new version of your assembly. That's called "breaking binary compatibility", and is...
c# using setters or getters from base class
[ "", "c#", "variables", "member", "protected", "" ]
Besides the fact that `$_REQUEST` reads from cookies, are there any reasons why I should use `$_GET` and `$_POST` instead of `$_REQUEST`? What are theoretical and practical reasons for doing so?
I use $\_REQUEST when I just want certain data from the user to return certain data. Never use $\_REQUEST when the request will have side effects. Requests that produce side effects should be POST (for semantic reasons, and also because of basic CSRF stuff, a false img tag can hit any GET endpoint without a user even ...
> Besides the fact that $\_REQUEST reads from cookies Besides the fact that this is undefined (It's configurable on a per-installation level), the problem using `$_REQUEST` is that it over-simplifies things. There is (or should be) a semantic difference between a GET request and a POST request. Thus it should matter t...
Why should I use $_GET and $_POST instead of $_REQUEST?
[ "", "php", "security", "" ]
I've got a bunch of stateless ejb 3.0 beans calling each other in chain. Consider, BeanA.do(message) -> BeanB.do() -> BeanC.do() -> BeanD.do(). Now i'd like to access message data from BeanD.do(). Obvious solution is to pass message as a parameter to all that do() calls (actually that's how it works now), but i want so...
i don't believe there is anything in the EJB spec that provides that functionality. If you are on a specific app server, you may be able to use app server specific stuff (i think JBoss allows you to add stuff to a call context). you also may be able to fake something up using JNDI. personally, this seems (to me) like ...
You could have a class with static get/set methods that access a static ThreadLocal field. However I would take james' advice and consider very carefully if you want to couple your EJBs to that other class. Definitely double-check your app server docs as I'm not sure if using ThreadLocals in an EJB environment is suppo...
Associate arbitrary data with ejb call context
[ "", "java", "jakarta-ee", "ejb-3.0", "" ]
Given the following table in SQL Server 2005: ``` ID Col1 Col2 Col3 -- ---- ---- ---- 1 3 34 76 2 32 976 24 3 7 235 3 4 245 1 792 ``` What is the best way to write the query that yields the following result (i.e. one that yields the final column - a co...
There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad. ``` Select Id, Case When Col1 < Col2 And Col1 < Col3 Then Col1 When Col2 < Col1 And Col2 < Col3 Then Col2 Else Col3 End As TheMin From YourTab...
Using `CROSS APPLY`: ``` SELECT ID, Col1, Col2, Col3, MinValue FROM YourTable CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A ``` [SQL Fiddle](http://sqlfiddle.com/#!3/dbbd3/1)
What's the best way to select the minimum value from several columns?
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "min", "" ]
I'm trying to convert Matt Berseth's '[YUI Style Yes/No Confirm Dialog](http://mattberseth.com/blog/2007/10/yui_style_yesno_confirm_dialog.html)' so I can use it with the jQuery blockUI plugin. I have to admit I'm no CSS guru but I thought this would pretty easy even for me....except 10hrs later I'm at a loss as to wh...
hmm i'm not that familiar with blockUI, but the basics of centering a div are pretty universal. i'm assuming you want your `#confirmDialogue` div centered within the whole screen? if so, you want to do a few things: ``` #confirmDialogue { position: fixed; // absolutely position this element on the page hei...
Take a look at this [jQuery MSG plugin](http://dreamerslab.com/blog/en/jquery-blockui-alternative-with-jquery-msg-plugin/). It is very light weight and easy to use. ### Example code ``` // default usage, this will block the screen and shows a 'please wait...' msg $.msg(); // this will show a 'blah blah' msg $.msg({ ...
How can I get a DIV to centre on a page using jQuery and blockUI?
[ "", "javascript", "jquery", "css", "blockui", "" ]
I'm still trying to debug a very sneaky memory corruption problem. I came across a section of my code that allocates memory on one thread and deletes it on another. I have a vague feeling that this is wrong, but I'm not sure why. The threads share the process memory and access to these structures is protected by a mut...
As indicated in another answer by @monjardin, there is nothing inherently wrong with what you are trying to do. As an additional thought, you didn't mention the platform, etc. you are running into this problem on but if multi-threading is new to you and/or this application you are working on, you want to be sure that ...
remember that the memory manager itself has to be thread-safe too, not only your use of the memory. check your platform docs.
Memory allocation and deallocation across threads
[ "", "c++", "multithreading", "memory", "" ]
It seems to be a common requirement nowadays to have a search feature that can search almost anything you want. Can anyone give me samples or tips as to how to go about building a one stop search for an application? For example: you have 3 tables customers, products, employees. The application has a master page that h...
[Lucene.NET](http://incubator.apache.org/lucene.net/) is an extremely fast full text search engine. Sample usage: See [Source code](http://code.google.com/p/dotnetkicks/) of [DotNetKicks](http://www.dotnetkicks.com/) starting from [codebehind of search page](http://code.google.com/p/dotnetkicks/source/browse/trunk/Do...
If you want something really scalable, I guess you'll have to build first a data dictionnary, listing each table and each column in your database. The building of such a table can be [fully automated](https://stackoverflow.com/questions/281979/do-you-generate-your-data-dictionary#283813). You will indicate in this tab...
How do I build a search mechanism for my application?
[ "", "c#", "asp.net", "sql-server", "linq", "search", "" ]
What are general guidelines on when user-defined implicit conversion could, should, or should not be defined? I mean things like, for example, "an implicit conversion should never lose information", "an implicit conversion should never throw exceptions", or "an implicit conversion should never instantiate new objects"...
The first isn't as simple as you might expect. Here's an example: ``` using System; class Test { static void Main() { long firstLong = long.MaxValue - 2; long secondLong = firstLong - 1; double firstDouble = firstLong; double secondDouble = secondLong; // Prints False...
I'd agree with the first definitely - the second most of the time ("never say never"), but wouldn't get excited by the third; apart from anything else, it creates an unnecessary distinction between structs and classes. In some cases, having an implicit conversion can vastly simplify a calling convention. For explicit ...
.Net implicit conversion guidelines
[ "", "c#", "types", "implicit", "" ]
What have others done to get around the fact that the Commons Logging project (for both .NET and Java) do not support Mapped or Nested Diagnostic Contexts as far as I know?
For the sake of completeness, I ended up writing my own very simple generic interface: ``` public interface IDiagnosticContextHandler { void Set(string name, string value); } ``` then implemented a Log4Net specific version: ``` public class Log4NetDiagnosticContextHandler : IDiagnosticContextHandler { privat...
**Exec summary:** We opted to use the implementor logging framework directly (in our case, log4j). **Long answer:** Do you need an abstract logging framework to meet your requirements? They're great for libraries that want to play nice with whatever host environment they end up in, but if you're writing an applicati...
Logging Commons and Mapped Diagnostic Context
[ "", "java", ".net", "logging", "apache-commons", "" ]
Sample data: !!Part|123456,ABCDEF,ABC132!! The comma delimited list can be any number of any combination of alphas and numbers I want a regex to match the entries in the comma separated list: What I have is: !!PART\|(\w+)(?:,{1}(\w+))\*!! Which seems to do the job, the thing is I want to retrieve them in order into...
You can either use split: ``` string csv = tag.Substring(7, tag.Length - 9); string[] values = csv.Split(new char[] { ',' }); ``` Or a regex: ``` Regex csvRegex = new Regex(@"!!Part\|(?:(?<value>\w+),?)+!!"); List<string> valuesRegex = new List<string>(); foreach (Capture capture in csvRegex.Match(tag).Groups["value...
Unless I'm mistaken, that still only counts as one group. I'm guessing you'll need to do a string.Split(',') to do what you want? Indeed, it looks a lot simpler to not bother with regex at all here... Depending on the data, how about: ``` if (tag.StartsWith("!!Part|") && tag.EndsWith("!!")) { ...
Extract comma separated portion of string with a RegEx in C#
[ "", "c#", "regex", "" ]
I have this piece of code: ``` var myObj = function () { this.complex = function (text) { /* long piece of code */ } this.parse(text) { return text.replace(/valid_pattern/gi, function ($1) { return this.complex($1); } ); } } ``` Of course calling **this.complex($1)** won't do the trick, because I'm in t...
Maybe try: ``` var myObj = function () { this.complex = function (text) { /* long piece of code */ } this.parse(text) { var that = this; return text.replace(/valid_pattern/gi, function ($1) { return that.complex($1); } ); } } ``` It is one of the most useful tricks :-) **UPDATE:** The trick is not...
This is what prototype and others do ``` // Monkey Patching, not everyone likes it Function.prototype.bind = function( obj ) { var _this = this; return function() { return _this.apply( obj, arguments ) } } ``` Now you can do this ``` var myObj = function () { this.complex = function (text) { /...
String.replace; replace by function result problem
[ "", "javascript", "" ]
This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked. There's got to be a better and faster way. Any ideas? ``` try { using (F...
There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.
The truth is, even if you do figure out a way to check if the file is "locked" by the time you get to the next line where you open the file, something else in the OS may try to get a hold of that file, and your code to open it will fail anyway. You'll have to put a try/catch there anyway. Therefore, I say no. There isn...
Detecting whether a file is locked by another process (or indeed the same process)
[ "", "c#", ".net", "" ]
How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?
Unpack the tuple to a list? ``` l = list(t) ```
You can use the asterisk to unpack a variable length, for instance: ``` foo, bar, *other = funct() ``` This should put the first item into `foo`, the second into `bar`, and all the rest into `other`. **Update:** I forgot to mention that this is Python 3.0 compatible only.
Unpack to unknown number of variables?
[ "", "python", "casting", "iterable-unpacking", "" ]
I have a user defined function in SQL called getBuisnessDays it takes @startdate and @enddate and returns the number of business days between the two dates. How can I call that function within my select? Here's what I'd like to do.. ``` SELECT getBusinessDays(a.opendate,a.closedate) FROM account a WHERE ... ```
Yes, you can do almost that: ``` SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays FROM account a WHERE... ```
If it's a table-value function (returns a table set) you simply join it as a Table this function generates one column table with all the values from passed comma-separated list ``` SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4') ```
SQL User Defined Function Within Select
[ "", "sql", "sql-server", "select", "user-defined-functions", "" ]
This following code gets this compile error: "*`invalid types 'int[int]' for array subscript`*". What should be changed? ``` #include <iostream> using namespace std; int main(){ int myArray[10][10][10]; for (int i = 0; i <= 9; ++i){ for (int t = 0; t <=9; ++t){ for (int ...
You are subscripting a three-dimensional array `myArray[10][10][10]` four times `myArray[i][t][x][y]`. You will probably need to add another dimension to your array. Also consider a container like [Boost.MultiArray](http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/index.html), though that's probably over your ...
What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9). ``` const int DIM_SIZE = 10; int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE]; for (int i = 0; i < DIM_SIZE; ++i){ for (int t = 0; t < DIM_SIZE; ++t){ for (int x = 0; x < DIM_SIZE; ++x...
invalid types 'int[int]' for array subscript
[ "", "c++", "arrays", "compiler-errors", "" ]
How can I create a Popup balloon like you would see from Windows Messenger or AVG or Norton or whomever? I want it to show the information, and then slide away after a few seconds. **Edit: It needs to be blocking like Form.ShowDialog()** because the program exits after displaying the notification
You can use the notifyIcon control that's part of .NET 2.0 System.Windows.Forms. That allows you to place an icon for your application in the System Tray. Then, you can call the ShowBalloonTip(int timeOut) method on that. Be sure however to first set the text, and icon properties on the notifyIcon for it to work. Small...
Don't create a modal (blocking) balloon. Please. A big part of the design of these UIs is that they are *not* dialogs: they're transient, potentially *non-interactive* elements, intended to provide incidental information to a user *without* necessarily interrupting their workflow. A balloon that steals focus and blocks...
Creating a Popup Balloon like Windows Messenger or AVG
[ "", "c#", ".net", "popup-balloons", "" ]
How do I convert a date string, formatted as `"MM-DD-YY HH:MM:SS"`, to a `time_t` value in either C or C++?
Use `strptime()` to parse the time into a `struct tm`, then use `mktime()` to convert to a `time_t`.
In the absence of `strptime` you could use `sscanf` to parse the data into a `struct tm` and then call `mktime`. Not the most elegant solution but it would work.
Date/time conversion: string representation to time_t
[ "", "c++", "c", "datetime", "" ]
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in ...
First normalize 2 XML, then you can compare them. I've used the following using lxml ``` import xml.etree.ElementTree as ET obj1 = objectify.fromstring(expect) expect = ET.tostring(obj1) obj2 = objectify.fromstring(xml) result = ET.tostring(obj2) self.assertEquals(expect, result) ```
This is an old question, but the accepted [Kozyarchuk's answer](https://stackoverflow.com/a/321893/3357935) doesn't work for me because of attributes order, and the [minidom solution](https://stackoverflow.com/a/321941/3357935) doesn't work as-is either (no idea why, I haven't debugged it). This is what I finally came...
Comparing XML in a unit test in Python
[ "", "python", "xml", "elementtree", "" ]
I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas. ``` // see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3 class NonSerializableSurrogate : ISerializationSurrogate { public void GetObjectData...
Did you see this post that I wrote as a followup to the CountingDemo: <http://dotnet.agilekiwi.com/blog/2007/12/update-on-persistent-iterators.html> ? Unfortunately, Microsoft have confirmed that they probably will change the compiler details (one day), in a way that is likely to cause problems. (e.g. f/when you update...
> Some objects need execute arbitrary "events" reaching some condition. Just how arbitrary are these events? Can they be counted, assigned ID's and mapped to referentially? ``` public class Command<T> where T : ISerializable { T _target; int _actionId; int _conditionId; public Command<T>(T Target, int Action...
Serializing anonymous delegates in C#
[ "", "c#", ".net-3.5", "serialization", "" ]
Is there a good equivalent implementation of `strptime()` available for Windows? Unfortunately, this POSIX function does not appear to be available. [Open Group description of strptime](http://www.opengroup.org/onlinepubs/009695399/functions/strptime.html) - summary: it converts a text string such as `"MM-DD-YYYY HH:M...
An open-source version (BSD license) of `strptime()` can be found here: [<http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD>](http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD) You'll need to add the following declaration to use it: ``` char *strptime(const char * __res...
If you don't want to port any code or condemn your project to boost, you can do this: 1. parse the date using `sscanf` 2. then copy the integers into a `struct tm` (subtract 1 from month and 1900 from year -- months are 0-11 and years start in 1900) 3. finally, use `mktime` to get a UTC epoch integer Just remember to...
strptime() equivalent on Windows?
[ "", "c++", "c", "windows", "datetime", "" ]
Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better. ``` def foo(): var_a = 2 var_b = 3 def _closure(x): return var_a + var_b + x return _closure localClosure = foo() # Local closure is now "return 2 + 3 + x" a = ...
I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call `foo()` again, the new closure would have a different set of variables from ...
It is quite possible in python 3 thanks to the magic of [nonlocal](http://jeremyhylton.blogspot.com/2007/02/nonlocal-implemented.html). ``` def foo(): var_a = 2 var_b = 3 def _closure(x, magic = None): nonlocal var_a if magic is not None: ...
Modify bound variables of a closure in Python
[ "", "python", "functional-programming", "closures", "" ]
I have a simple task of authenticating against Active Directory using Java. Just verifying credentials and nothing else. Let's say my domain is "fun.xyz.tld", OU path is unknown, and username/password is testu/testp. I know there's a few Java libraries out there that simplify this task, but I wasn't successful at impl...
Here's the code I put together based on example from this blog: [LINK](https://community.oracle.com/blogs/kohsuke/2008/06/12/more-active-directory-integration-java) and this source: [LINK](https://github.com/jenkinsci/active-directory-plugin/blob/master/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixA...
There are 3 authentication protocols that can be used to perform authentication between Java and Active Directory on Linux or any other platform (and these are not just specific to HTTP services): 1. Kerberos - Kerberos provides Single Sign-On (SSO) and delegation but web servers also need SPNEGO support to accept SSO...
Authenticating against Active Directory with Java on Linux
[ "", "java", "authentication", "active-directory", "ldap", "" ]
Say I need to call a javascript file in the `<head>` of an ERb template. My instinct is to do the usual: ``` <head> <%= javascript_include_tag :defaults %> <!-- For example --> </head> ``` in my application's layout. The problem of course becoming that these javascript files are loaded into every page in my applicati...
I would use [content\_for](http://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for). For instance, specify the place to insert it in the application layout: ``` <head> <title>Merry Christmas!</title> <%= yield(:head) -%> </head> ``` And send it there from a view: ``` <%- content_for(:head) do -%> <%= ...
I feel there's nothing wrong including all yr defaults since they can then be cached on user's browser.
Javascript Include Tag Best Practice in a Rails Application
[ "", "javascript", "ruby-on-rails", "header", "rjs", "" ]
I know that the f# list is not the same at the c# List. What do I need to do to be able to pass a list of ints from a c# application to an f# library? I'd like to be able to use pattern matching on the data once it's in the f# code.
Here is how I ended up doing it. The FSharp code: ``` let rec FindMaxInList list = match list with | [x] -> x | h::t -> max h (FindMaxInList t) | [] -> failwith "empty list" let rec FindMax ( array : ResizeArray<int>) = let list = List.ofSeq(array) FindMaxInList list ``` The c Sharp code: ``` ...
You can use ``` Seq.toList : IEnumerable<'a> -> list<'a> ``` to convert any `IEnumerable<'a>` `seq` to an F# list. Note that F# lists are immutable; if you want to work with the mutable list, you don't need to do anything special, but you won't be able to use pattern matching. Or, rather, you *can* define active patt...
What can I do to pass a list from C# to F#?
[ "", "c#", "f#", "" ]
I've looked breifly into [GWT](http://code.google.com/webtoolkit/) and like the idea that I can develop in Java and have the application compile down to HTML and JavaScript. Is the concept behind GWT and AWT and Swing the same or different?
GWT is very much similar to Swing in its usage of Widgets, Panels and the EventListeners it provides. A different way to look at GWT is to think of Javascript and HTML as Assembly language and GWT as a sort of High level language which generates Javascript and HTML. With GWT its easy to develop desktop-like apps for th...
It is programmed very similarly(patterned after Swing) and the code is 100% java (compiles with a standard Java compiler without errors), but the way it works is very different. Instead of compiling into a Java app, it compiles into Javascript that is sent to your browser. This ability to program good active Javascrip...
Is Google Web Toolkit similar to AWT and Swing
[ "", "java", "swing", "gwt", "awt", "" ]
Currently I am evaluating number of web service frameworks in Java. I need web service framework that will help me to expose some functionality of existent application running on JBoss, The application is mostly developed using Spring and POJOs (no EJBs). What I need is a framework having following properties: 1. It ...
I've used CXF's forerunner, XFire, for a while now and it's not been too bad. At the time, we migrated from Axis for two major reasons: performance and ease of development. At the time (don't know if this is true now), the performance of XFire was much better than anything out there, and with annotation-driven developm...
We have tried Metro and CXF and kept CXF because Metro includes too many dependencies like Sun's APIs in its jar files which makes it difficult to integrate in another application server than Glassfish. CXF has a cleaner packaging with explicit external dependencies. We also failed to enable Gzip compression with Metro...
Java Web Service framework/library, which is a better one and why?
[ "", "java", "web-services", "spring", "jakarta-ee", "frameworks", "" ]
I have a SQLServer with a linked server onto another database somewhere else. I have created a view on that linked server ``` create view vw_foo as select [id], [name] from LINKEDSERVER.RemoteDatabase.dbo.tbl_bar ``` I'd like to to the following ``` alter table [baz] add foo_id int not null go alter table [baz] wi...
Foreign keys can't be connected to non-local objects - they have to reference local tables. You get the "maximum number of prefixes" error because you're referencing the table with a 4-part name (LinkedServer.Database.Schema.Object), and a local object would only have a 3-part name. Other solutions : 1. Replicate the...
You can, but you have to use some dynamic SQL trickery to make it happen. ``` declare @cmd VARCHAR(4000) SET @cmd = 'Use YourDatabase ALTER TABLE YourTable DROP CONSTRAINT YourConstraint' exec YourServer.master.dbo.sp_executesql @SQL ```
Can you have a Foreign Key onto a View of a Linked Server table in SQLServer 2k5?
[ "", "sql", "sql-server", "sql-server-2005", "foreign-keys", "linked-server", "" ]
**Dupe: [Null Difference](https://stackoverflow.com/questions/302701/null-difference)** A lifetime ago I came across an article that explained that the following were not equal (in c#): ``` if (o == null) {} if (null == o) {} ``` The article explained that the latter was preferred because it resulted in a more accur...
it's an old habit to prevent you from typing `if (o = null)`. if (null = o) is a syntax error. kind of pointless in C#, because null values aren't ever coerced into booleans.
The latter is a holdover from the C/C++ days, where it was possible to accidentally assign a value instead of compare. C# won't allow you to do this, so either/or is acceptable (but I find the former more readable).
Checking for null, which is better? "null ==" or "==null"
[ "", "c#", ".net", "null", "" ]
I currently have a small Java program which I would like to run both on the desktop (ie in a JFrame) and in an applet. Currently all of the drawing and logic are handled by a class extending Canvas. This gives me a very nice main method for the Desktop application: ``` public static void main(String[] args) { MyCa...
[Applet](http://java.sun.com/j2se/1.5.0/docs/api/java/applet/Applet.html) is a [Container](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html), just [add](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#add(java.awt.Component)) your Canvas there.
Generally, the way you would have an application that is also an applet is to have your entry point class extend Applet, and have its setup add the Canvas to itself, etc. etc. Then, in the main method version, you just instantiate your Applet class and add it to a new Frame (or JApplet / JFrame, etc.). See [here](htt...
Painting a Canvas in an Applet
[ "", "java", "graphics", "applet", "canvas", "" ]
I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export me...
I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your *Export(List<data> list)* method. Btw, you never really mentioned what was going wrong and where. I see you had written "if they have Excel export to excel and i...
This is an excellent example, but I think that need a globalization modification. ``` String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description)); ```
Export HTML Table in asp.net MVC
[ "", "c#", "asp.net-mvc", "" ]
I have two simple while loops in my program that I feel ought to be math equations, but I'm struggling to convert them: ``` float a = someValue; int b = someOtherValue; int c = 0; while (a <= -b / 2) { c--; a += b; } while (a >= b / 2) { c++; a -= b; } ``` This code works as-is, but I feel it could b...
It can be proved that the following is correct: ``` c = floor((a+b/2)/b) a = a - c*b ``` Note that floor means round down, towards negative infinity: not towards 0. (E.g. floor(-3.1)=-4. The `floor()` library functions will do this; just be sure not to just cast to int, which will usually round towards 0 instead.) P...
``` c = (int)((a - (b / 2)) / b + 1); a -= c * b; ``` Test case at <http://pastebin.com/m1034e639>
Turn while loop into math equation?
[ "", "c++", "c", "algorithm", "math", "" ]
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java. And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinform...
Java uses static binding for overloaded methods, and dynamic binding for overridden ones. In your example, the equals method is overloaded (has a different param type than Object.equals()), so the method called is bound to the **reference** type at compile time. Some discussion [here](http://forums.techarena.in/softwa...
The `equals` method of `Test` does not override the `equals` method of `java.lang.Object`. Look at the parameter type! The `Test` class is overloading `equals` with a method that accepts a `Test`. If the `equals` method is intended to override, it should use the @Override annotation. This would cause a compilation err...
Java dynamic binding and method overriding
[ "", "java", "inheritance", "dynamic-binding", "" ]
Given an enum that has assigned values, what is the best way to get the next or previous enum given a value. For example, consider this enum: ``` public enum TimeframeType { None = 0, [Description("1 month")] Now = 30, [Description("1-3 months")] Short = 90, [Description("3-6 months")] Medi...
You are trying to solve the wrong problem. This is far too complex for a simple enum to calculate. Refactor the enum to a class and use a comparison interface. If this route is open to you look at how this *could* be implemented by a class: ``` public class TimeFrame: IComparable { private int days; public int...
Enums in .NET aren't really meant to be ordered, so you shouldn't rely on it. Someone else later might just come and add a value somewhere in the middle that would be out of order. Thus there also isn't such a functionality built in. You can write your own functions (similar to what you have already written) but that's...
Next or previous enum
[ "", "c#", "enums", "" ]
So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.
As for future plans of MySQLdb, you might want to ask the author (Andy Dustman). His blog is here: <http://mysql-python.blogspot.com/>
It appears the MySQLdb is pretty much a dead project. However, [PyMySQL](https://github.com/PyMySQL/PyMySQL/) is a dbapi compliant, pure-python implementation of a mysql client, and it has python 3 support. EDIT: There's also [MySQL Connector/Python](https://launchpad.net/myconnpy). Same idea.
MySQL-db lib for Python 3.x?
[ "", "python", "mysql", "python-3.x", "" ]
Is there a quick way to detect classes in my application that are never used? I have just taken over a project and I am trying to do some cleanup. I do have [ReSharper](http://www.jetbrains.com/resharper/) if that helps.
I don't recommend deleting old code on a new-to-you project. That's really asking for trouble. In the best case, it might tidy things up for you, but isn't likely to help the compiler or your customer much. In all but the best case, something will break. That said, I realize it doesn't really answer your question. For...
1. [NDepend](http://www.ndepend.com/) 2. [Resharper 4.5](http://rabdullin.com/journal/2008/12/19/resharper-45-features-and-release-date.html) (4.0 merely detects unused private members) 3. Build your own code quality unit-tests with Mono.Cecil (some samples could be found in the *Lokad.Quality* the [this open source pr...
How do I find and remove unused classes to cleanup my code?
[ "", "c#", "resharper", "" ]
Found the following in an Oracle-based application that we're migrating *(generalized)*: ``` SELECT Table1.Category1, Table1.Category2, count(*) as Total, count(Tab2.Stat) AS Stat FROM Table1, Table2 WHERE (Table1.PrimaryKey = Table2.ForeignKey(+)) GROUP BY Table1.Category1, Table1.Category2 ``` What ...
Depending on which side of the "=" the "(+) is on, it denotes a LEFT OUTER or a RIGHT OUTER join (in this case, it's a left outer join). It's old Oracle syntax that is sometimes preferred by people who learned it first, since they like that it makes their code shorter. Best not to use it though, for readability's sake...
As others have stated, the `(+)` syntax is obsolete, proprietary syntax that Oracle used for years to accomplish the same results as an `OUTER JOIN`. I assume they adopted their proprietary syntax before SQL-92 decided on the standard syntax. The equivalent query to the one you showed, using standard SQL `OUTER JOIN` ...
Oracle: What does `(+)` do in a WHERE clause?
[ "", "sql", "oracle", "operators", "" ]
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return `None`. This code works: ``` def main(): my_list = get_list() if len(my_list) > 0: return my_list[0] return None ``` but it seems to me t...
## Python 2.6+ ``` next(iter(your_list), None) ``` If `your_list` can be `None`: ``` next(iter(your_list or []), None) ``` ## Python 2.4 ``` def get_first(iterable, default=None): if iterable: for item in iterable: return item return default ``` Example: ``` x = get_first(get_first_li...
The best way is this: ``` a = get_list() return a[0] if a else None ``` You could also do it in one line, but it's much harder for the programmer to read: ``` return (get_list()[:1] or [None])[0] ```
Python idiom to return first item or None
[ "", "python", "idioms", "" ]
I'm using SQL Server 2005 and would like to know how I can get a list of all tables with the number of records in each. I know I can get a list of tables using the `sys.tables` view, but I'm unable to find the count. Thank you
From here: <http://web.archive.org/web/20080701045806/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-get-a-list-of-sql-server-tables-and-their-row-counts.html> ``` SELECT [TableName] = so.name, [RowCount] = MAX(si.rows) FROM sysobjects so, sysindexes si WHERE so.xtype = 'U' AND ...
For what it's worth, the sysindexes system table is deprecated in SQL 2008. The above still works, but here's query that works going forward with SQL 2008 system views. ``` select schema_name(obj.schema_id) + '.' + obj.name, row_count from ( select object_id, row_count = sum(row_count) from sys...
Counting rows for all tables at once
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: ``` <main> <object1 attr="name">content</object> </main> ``` And turn it into something like this: ``` main main.object1 = "content" main.object1.attr = "name" ``` The XML data will have a more com...
It's worth looking at [`lxml.objectify`](http://lxml.de/objectify.html). ``` xml = """<main> <object1 attr="name">content</object1> <object1 attr="foo">contenbar</object1> <test>me</test> </main>""" from lxml import objectify main = objectify.fromstring(xml) main.object1[0] # content main.object1[1] ...
I've been recommending this more than once today, but try [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) (easy\_install BeautifulSoup). ``` from BeautifulSoup import BeautifulSoup xml = """ <main> <object attr="name">content</object> </main> """ soup = BeautifulSoup(xml) # look in the main node ...
How can I convert XML into a Python object?
[ "", "python", "xml", "" ]
I have to work on some code that's using generic lists to store a collection of custom objects. Then it does something like the following to check if a given object's in the collection and do something if so: ``` List<CustomObject> customObjects; //fill up the list List<CustomObject> anotherListofCustomObjects; //fil...
Well, you seem to have answered it yourself? If you need fast query against a set of data, then a dictionary may be better than a flat list (for largish data sizes, which yours is). You could, for example, use the object as its own key - ``` Dictionary<CustomObject,CustomObject> ... ``` Note that the meaning of equa...
Another way besides dictionaries is, if you're on .NET 3.5, to use Linq to objects and Intersect: ``` foreach(CustomObject c in customObjects.Intersect(anotherListOfCustomObjects)) { // do stuff. } ``` According to reflector, it uses Hash-based sets to perform the intersection of the sequences.
Best way of checking content of Generic List
[ "", "c#", ".net", "performance", "generics", "" ]
I need some way to add a class attribute to the output of the `label_tag()` method for a forms field. I see that there is the ability to pass in an `attrs` dictionary and I have tested it in the shell and I can do something like: ``` for field in form: print field.label_tag(attrs{'class':'Foo'}) ``` I will see t...
A [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases. If this is a task of high importance; I'...
**Technique 1** I take issue with another answer's assertion that a filter would be "less elegant." As you can see, it's very elegant indeed. ``` @register.filter(is_safe=True) def label_with_classes(value, arg): return value.label_tag(attrs={'class': arg}) ``` Using this in a template is just as elegant: ``` ...
Add class to Django label_tag() output
[ "", "python", "django", "forms", "newforms", "" ]
I'm looking for a piece of code which behaves a bit like a singleton but isn't (because singleton's are bad :) What I'm looking for must meet these goals: 1. Thread safe 2. Simple (Understand & use, i.e. few lines of code. Library calls are OK) 3. Fast 4. Not a singleton; for tests, it must be possible to overwrite th...
Here is a solution that fulfills all my requirements: ``` /** Lazy initialization of a field value based on the (correct) * double checked locking idiom by Joschua Bloch * * <p>See "Effective Java, Second Edition", p. 283 */ public abstract class LazyInit<T> { private volatile T field; /** Return the value. ...
The best idiom for threadsafe initialization code (imho) is the lazy inner class. The classic version is ``` class Outer { class Inner { private final static SomeInterface SINGLETON; static { // create the SINGLETON } } public SomeInterface getMyObject() { return Inner.SINGLETON; } } ``...
Ways for lazy "run once" initialization in Java with override from unit tests
[ "", "java", "multithreading", "singleton", "lazy-evaluation", "" ]
In C# how do you write a DataSet to file without it being written with pretty print? Using C# and .NET 2.0, I've been using dataSet.WriteXml(fileName, XmlWriteMode.IgnoreSchema), which by default is writing the Xml file with pretty print. The company consuming the Xml files I write suggested that writing without the p...
It's pretty simple, you just have to create an `XmlWriter` using an `XmlWriterSettings` which has the `Indent` property set to false: ``` // The memory stream for the backing. using (MemoryStream ms = new MemoryStream()) { // The settings for the XmlWriter. XmlWriterSettings settings = new XmlWriterSettings(); ...
Even easier than using XmlWriterSettings: ``` XmlTextWriter xml = new XmlTextWriter(fileName, Encoding.UTF8) { Formatting = Formatting.None }; dataSet.WriteXml(xml); ```
How to NOT write XML with pretty print from C# DataSet
[ "", "c#", "xml", "" ]
**(resolved: see bottom)** I have the following code snippet: ``` Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted affected = CInt(DirectCast(e.Command.Parameters("@affected"), IDbDataParameter).Value)...
From [MSDN](http://msdn.microsoft.com/en-us/library/ms187342.aspx) > After an INSERT, SELECT INTO, or bulk > copy statement is completed, > @@IDENTITY contains the last identity > value that is generated by the > statement. If the statement did not > affect any tables with identity > columns, @@IDENTITY returns NULL. ...
You should use `SCOPE_IDENTITY()` as oppose to `@@IDENTITY` in 99.9% of cases. It is very rare you will have a situation that requires something other than `SCOPE_IDENTITY()` > `@@IDENTITY` returns the last IDENTITY > value produced on a connection, > regardless of the table that produced > the value, and regardless o...
Why would @@IDENTITY or SCOPE_IDENTITY() be DBNull?
[ "", "sql", "vb.net", "identity", "" ]
For years and years, I've tried to understand the [part](http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4) of Java specification that deals with memory model and concurrency. I have to admit that I've failed miserably. Yes' I understand about locks and "synchronized" and wait() and notify(). And I...
I'm not going to attempt to actually answer your questions here - instead I'll redirect you to the book which I seeing recommended for advice on this topic: [Java Concurrency in Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601). One word of warning: if there *are* answers here, expect quite a few of ...
* non-`volatile` variables can be cached thread-locally, so different threads may see different values at the same time; `volatile` prevents this ([source](http://www.javamex.com/tutorials/synchronization_volatile.shtml)) * writes to variables of 32 bits or smaller are guaranteed to be atomic ([implied here](http://jav...
Java memory model - can someone explain it?
[ "", "java", "concurrency", "" ]
It is obvious what I am trying to do below, but I get the following exception: > Unable to return a TimeSpan property value for a Duration value of 'Automatic'. I was discouraged to read that > NaturalDuration cannot be determined until after MediaOpened has occurred. ([link](http://msdn.microsoft.com/en-us/library/...
> I have to come up with a contrived method to open the file, wait for the media opened event in a separate thread, then return the duration only after the event has fired That's exactly what it means, unfortunately. The below is what I just came up with for this: ``` using System; using System.Threading; using Syste...
Yes, there is no straightforward way to open a media file and get the media duration, the reason is that the file is opened in the background (to support files that take a long time to open, for example files on remote servers), so right after you call Open the file hasn't been opened yet. Your best option is to restr...
How do I write a method to open, start playing, then return the duration of an audio file using a MediaPlayer in WPF?
[ "", "c#", "wpf", "audio", "" ]
Is there a way that I can get the last value (based on the '\' symbol) from a full path? Example: `C:\Documents and Settings\img\recycled log.jpg` With this case, I just want to get `recycled log.jpg` from the full path in JavaScript.
``` var filename = fullPath.replace(/^.*[\\/]/, '') ``` This will handle both / OR \ in paths.
Just for the sake of performance, I tested all the answers given here: ``` var substringTest = function (str) { return str.substring(str.lastIndexOf('/')+1); } var replaceTest = function (str) { return str.replace(/^.*(\\|\/|\:)/, ''); } var execTest = function (str) { return /([^\\]+)$/.exec(str)[1]; } ...
How to get the file name from a full path using JavaScript?
[ "", "javascript", "" ]
How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? --- Failing to use the `global` keyword where appropriate often causes `UnboundLocalError`. The precise rules for this are explained at [UnboundLocalError on local varia...
You can use a global variable within other functions by declaring it as `global` **within each function that assigns a value to it**: ``` globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print(globvar) # No need for glo...
If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces. Say you've got a module like this: ``` # sample.py _my_global = 5 def func1(): _my_global = 42 def func2(): print _my_global func1() func2() ``` You might ...
How to use a global variable in a function?
[ "", "python", "global-variables", "scope", "" ]
What do you find to provide the best menu for an ASP.Net 2.0 - 3.5 web application? Suggestions do not have to particularly be ASP.Net controls, but could be other menu's that work well within an ASP.Net web application. I would like for the suggestions to be options that do not require purchasing or royalty fees. Ope...
I use jQuery Superfish: <http://users.tpg.com.au/j_birch/plugins/superfish/>. Highly recommended [by others](http://encosia.com/2008/10/19/7-of-my-favorite-jquery-plugins-for-use-with-aspnet/) as well.
I've found that the most flexible is to use CSS to style an unordered list like this: ``` <div id="nav_main" > <ul> <li id="current">Button 1</li> <li><a href="#">Button 2</a></li> <li><a href="#">Button 3</a></li> <li><a href="#">Button 4</a></li> <li><a href="#">Button 5</a></li> </ul> </div> ``` You'll f...
What is the best menu for an ASP.Net application?
[ "", "asp.net", "javascript", "html", "asp.net-2.0", "" ]
How to create a java.awt.Image from image data? Image data is not pure RGB pixel data but encoded in jpeg/png format. JavaME has a simple api Image.createImage(...) for doing this. ``` public static Image createImage(byte[] imageData, int imageOffset, in...
``` import java.awt.*; Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.createImage(imageData,imageOffset,imageLength); ```
Use javax.imageio.ImageIO ``` BufferedImage image = ImageIO.read(new ByteArrayInputStream(myRawData)); ``` **Do not** use the older functions which return an implementation of Image other than BufferedImage. The Image interface is in fact only a handle that might be loaded by a background thread and give you all kind...
How to create a java.awt.Image from image data?
[ "", "java", "image", "awt", "" ]
I am to take up the task of porting a C++ networking application code base of quite a size from Solaris to Linux platform. The code also uses third party libraries like ACE. The application when written initially was not planned for a possible porting in future. I would like to get some advice and suggestions as to ho...
**"There is no such thing as a portable application only applications that have been ported"** First start with using the same tools on both platforms, if you can. I.E. if the Solaris version has not been changed to use GCC and GNU make etc, I advise you to change this first and get the Solaris build working. You will...
ACE is a plus there, as it is multiplatform. You must check where and how your type sizes are used. If ACE\_\* basic types are used you are hitting a streak there, as those are portable, else I would start by changing the Solaris version into using multiplatform data types and elements (use ACE facilities since you alr...
Porting Application from Solaris to Linux
[ "", "c++", "linux", "solaris", "porting", "" ]
I'm trying to create a query which uses a list of ids in the where clause, using the Silverlight ADO.Net Data Services client api (and therefore Linq To Entities). Does anyone know of a workaround to Contains not being supported? I want to do something like this: ``` List<long?> txnIds = new List<long?>(); // Fill li...
**Update:** EF ≥ 4 supports [`Contains`](http://msdn.microsoft.com/en-us/library/bb352880.aspx "Enumerable.Contains<T>") directly (Checkout [`Any`](http://msdn.microsoft.com/en-us/library/bb534972.aspx "Enumerable.Any<T>")), so you don't need any workaround. ``` public static IQueryable<TEntity> WhereIn<TEntity, TValu...
You can fall back on hand coding some e-sql (note the keyword "it"): ``` return CurrentDataSource.Product.Where("it.ID IN {4,5,6}"); ``` Here is the code that I used to generate some e-sql from a collection, YMMV: ``` string[] ids = orders.Select(x=>x.ProductID.ToString()).ToArray(); return CurrentDataSource.Product...
'Contains()' workaround using Linq to Entities?
[ "", "c#", "linq", "entity-framework", ".net-3.5", "linq-to-entities", "" ]
Some of Oracle's analytic functions allow for a [windowing clause](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i97640) to specify a subset of the current partition, using keywords like "unbounded preceding/following", "current row", or "value\_expr preceding/following" where value\_e...
It doesn't really matter which you use. They are two different ways of expressing the windowing, but the optimizer will perform the query the same way. The term "current row" is one that is common to multiple databases with analytic functions, not just Oracle. It's more of a stylistic difference, in the same way that s...
The Oracle documentation that I have to hand (Oracle 9.2) says: > If you specified RANGE: > > * value\_expr is a logical offset. It must be a constant or expression that > evaluates to a positive numeric value > or an interval literal. This implies that you shouldn't really be using 0 since it isn't a positive nu...
Any difference between "current row" and "0 preceding/following" in windowing clause of Oracle analytic functions?
[ "", "sql", "oracle", "analytics", "" ]
I was wondering if anyone has any preference for referencing images/ css or javascript files in their sites? The reason I ask is if a client wants to host the site we've writen under a virtual directory, the site usually has to have it's file references changed - even down to url (...image path) in CSS files because w...
**Images** (like background-url) **in CSS are always referenced relative to the css file.** Example: ``` /img/a.gif /css/c.css ``` To reference `a.gif` from the css file, you must always reference it like such `../img/a.gif`, irrelevant to where a page is located or how it is rewritten
I like to keep all of my style images in sub-directories of the style sheet location, for example: Site->Style->Common.css Site->Style->Images->Background.png This way you alleviate the issues with "up" directories in the CSS being confusing, or needing to move the CSS easily, as it is all self contained in a singl...
JavaScript/ CSS/ Image reference paths
[ "", "javascript", "css", "" ]
I'm working on a project, written in Java, which requires that I build a very large 2-D sparse array. Very sparse, if that makes a difference. Anyway: the most crucial aspect for this application is efficency in terms of time (assume loads of memory, though not nearly so unlimited as to allow me to use a standard 2-D a...
Sparsed arrays built with hashmaps are very inefficient for frequently read data. The most efficient implementations uses a Trie that allows access to a single vector where segments are distributed. A Trie can compute if an element is present in the table by performing only read-only TWO array indexing to get the effe...
Following framework to test Java Matrix Libraries, provides also a good list of these! <https://lessthanoptimal.github.io/Java-Matrix-Benchmark/> Tested Libraries: ``` * Colt * Commons Math * Efficient Java Matrix Library (EJML) * Jama * jblas * JScience (Older benchmarks only) * Matrix Toolkit Java (MTJ) * OjAlgo * ...
Sparse matrices / arrays in Java
[ "", "java", "algorithm", "sparse-matrix", "sparse-array", "" ]
Is there a good, free telnet library available for C# (not ASP .NET)? I have found a few on google, but they all have one issue or another (don't support login/password, don't support a scripted mode). I am assuming that MS still has not included a telnet library as part of .NET v3.5 as I couldn't find it if it was. I...
Best C# Telnet Lib I've found is called [Minimalistic Telnet](https://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library). Very easy to understand, use and modify. It works great for the Cisco routers I need to configure.
Here is my code that is finally working ``` using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Threading; class TelnetTest { static void Main(string[] args) { TelnetTest tt = new TelnetTest(); tt.tcpClient = new TcpCl...
C# Telnet Library
[ "", "c#", ".net", "telnet", "" ]