Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In Jesse Liberty's Learning C# book, he says > "Objects of one type can be converted into objects of another type. > This is called casting." If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, y...
The simple answer is: it depends. For value types, casting will involve genuinely converting it to a different type. For instance: ``` float f = 1.5f; int i = (int) f; // Conversion ``` When the casting expression unboxes, the result (assuming it works) is *usually* just a copy of what was in the box, with the same ...
Absolutely not! Convert tries to get you an Int32 via "any means possible". Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion. You should always use cast when you know (by design) that the object is an Int32 or another class that has an casting operat...
Is casting the same thing as converting?
[ "", "c#", "clr", "casting", "" ]
I have a set of XSDs from which I generate data access classes, stored procedures and more. What I don't have is a way to generate database table from these - is there a tool that will generate the DDL statements for me? This is not the same as [Create DB table from dataset table](https://stackoverflow.com/questions/...
Commercial Product: Altova's [XML Spy](http://www.altova.com/features_sql.html). Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database. While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it w...
There is a command-line tool called [XSD2DB](http://xsd2db.sourceforge.net/), that generates database from xsd-files, available at sourceforge.
How can I create database tables from XSD files?
[ "", ".net", "sql", "database", "xsd", "code-generation", "" ]
I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was...
The depression in the responses is overwhelming... But don't fear, we've got [the holy book to exorcise the demons of legacy C++ code](https://rads.stackoverflow.com/amzn/click/com/0131177052). Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code. Turn to page 127: **The...
Since you're testing legacy code I'm assuming you can't refactor said code to have less dependencies (e.g. by using the [pimpl idiom](http://www.gotw.ca/gotw/028.htm)) That leaves you with little options I'm afraid. Every header that was included for a type or function will need a mock object for that type or function...
C++ Unit Testing Legacy Code: How to handle #include?
[ "", "c++", "unit-testing", "legacy", "" ]
I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable. Has it been done? Is it impossible?
Yes it **can be done** without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap. I would **look at the [boost::coroutine](http://www.boost.org/doc/libs/1_53_0/libs/coroutine/doc/html/index.html) library**. The one thing that you should watch out for is a ...
On POSIX, you can use makecontext()/swapcontext() routines to portably switch execution contexts. On Windows, you can use the fiber API. Otherwise, all you need is a bit of glue assembly code that switches the machine context. I have implemented coroutines both with ASM (for AMD64) and with swapcontext(); neither is ve...
How do you implement Coroutines in C++
[ "", "c++", "coroutine", "c++17", "" ]
The original query looks like this (MySQL): ``` SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date ``` Would it be possible to rewrite it (without unions or procedures), so that result will look like this: * list of books where title matches query ordered by date, followed by...
In sql server I would do the following: ``` select * from books where title like '%text%' or description like '%text%' order by case when title like '%text%' then 1 else 2 end, date ``` I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise...
``` select * from books where title like "%text%" or description like "%text%" order by date, case when title like "%text%" then 0 else 1 end ```
Is it possible to build following SQL query
[ "", "sql", "mysql", "database", "" ]
I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this: ``` MemoryStream stream = new MemoryStream(); XmlTextWriter xmlTex...
Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. If you still want to do the double write, for whatever reason, do one of two things. Either 1. Make sure that the StreamReader and Str...
Both your StreamWriter and your StreamReader are using UTF-8, because you're not specifying the encoding. That's why things are getting corrupted. As tomasr said, using a FileStream to start with would be simpler - but also MemoryStream has the handy "WriteTo" method which lets you copy it to a FileStream very easily....
Writing XML files using XmlTextWriter with ISO-8859-1 encoding
[ "", "c#", ".net", "xml", "encoding", "iso-8859-1", "" ]
The code that I want to write is like this: ``` void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff } } ...
This is NOT a good idea [This article talks about ruby's timeout library.](http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html) which throws exceptions across threads. It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exc...
There are enough problems with exceptions that can be thrown on threads by other mechanisms, like aborting threads and the likes, that you should find another way of doing it. An exception is a mechanism used to signal that a process has experienced something exceptional that it cannot deal with. You should try to avo...
Is there a good method in C# for throwing an exception on a given thread
[ "", "c#", "multithreading", "exception", "" ]
I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like - ``` Syntax error on token "}", delete this token Syntax error on token "catch", Identifier expected Syntax error, insert "Finally" to complete TryStatement ``` I'm doing best ...
I have just downloaded Ganymede 3.4.2 and added WTP 3.0.4 to it and this error has gone for me.
I actually found out what my problem was through the [eclipse webtools usergroup](http://www.eclipse.org/newsportal/article.php?id=17447&group=eclipse.webtools#17447). The issue for me was the use of the Spring form custom tag library. If you self-close the tag... ``` <form:errors path="*" /> ``` ...then you get the ...
Eclipse Ganymede not validating JSPs properly
[ "", "java", "eclipse", "validation", "jsp", "ganymede", "" ]
Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters? For example I have the following navigation-rule ``` <navigation-rule> <navigation-case> <from-outcome>showMessage</from-outcome> <to-view-id>/showMessa...
This is an interesting idea. I'd be curious to know how it pans out in practice. **Getting the navigation rules** Navigation is handled by the [NavigationHandler](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html). Getting hold of the NavigationHandler isn't dif...
Tried using PrettyFaces? It's an open-source JSF extension designed specifically to make bookmarkable JSF pages / JSF with GET requests possible. [PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigation for JSF / JSF2](http://ocpsoft.com/prettyfaces "PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigat...
How to create a GET request with parameters, using JSF and navigation-rules?
[ "", "java", "jsf", "redirect", "navigation", "" ]
I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?
I ended up using two queries since MySQL5 doesn't yet support LIMIT's in subqueries ``` SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1; DELETE FROM entries WHERE unixTime < $sqlResult; ```
Blockquote ``` delete from table where id not in ( select id from table order by id desc limit 50 ) ``` You select the ids of the data you don't want to delete, and the you delete everything NOT IN these value...
Delete all but the 50 newest rows
[ "", "mysql", "sql", "" ]
My [Google-fu](https://english.stackexchange.com/questions/19967/what-does-google-fu-mean) has failed me. In Python, are the following two tests for equality equivalent? ``` n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' ``` Does this hold true for objects where you would be c...
`is` will return `True` if two variables point to the same object (in memory), `==` if the objects referred to by the variables are equal. ``` >>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True # Make a new copy of list `a` via the slice operator, # and assign it to variable `b` >>> b = a[:] >>> b is a Fa...
There is a simple rule of thumb to tell you when to use `==` or `is`. * `==` is for *value equality*. Use it when you would like to know if two objects have the same value. * `is` is for *reference equality*. Use it when you would like to know if two references refer to the same object. In general, when you are compa...
Is there a difference between "==" and "is"?
[ "", "python", "reference", "equality", "semantics", "" ]
Is there an easy way to programmatically determine the number of lines within a text file?
**Seriously belated edit: If you're using .NET 4.0 or later** The `File` class has a new [`ReadLines`](http://msdn.microsoft.com/en-us/library/dd383503.aspx) method which lazily enumerates lines rather than greedily reading them all into an array like `ReadAllLines`. So now you can have both efficiency and conciseness...
The easiest: ``` int lines = File.ReadAllLines("myfile").Length; ```
Determine the number of lines within a text file
[ "", "c#", "input", "text-files", "" ]
I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g. ``` class object ...
`const` is about program semantics and not about implementation details. You should mark a member function `const` when it does not change the visible state of the object, and should be callable on an object that is itself `const`. Within a `const` member function on a class `X`, the type of `this` is `X const *`: poin...
No. A const method is a method that doesn't change the state of the object (i.e. its fields), but you can't assume that given the same input, return value of a const method is determined. In other words, `const` keyword does NOT imply that the function is one-to-one. For instance a method that returns the current time...
What are the semantics of a const member function?
[ "", "c++", "methods", "constants", "" ]
Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have ``` using antlr.collections; using myNamespace; ``` at the top of their files in order to use m...
Bear in mind that the consumers of your code won't actually *need* to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source. The bigger "impact" (if indeed there really is a severe one) is that the consumer of...
How about deriving a class using the same name in the new namespace? I meant: ``` namespace MyForms { class Class1 : Some.Other.Namespace.Class1 { // ... } } ```
can I expose a class from another .net namespace as a class in my namespace?
[ "", "c#", ".net", "namespaces", "" ]
I'm just wondering what the optimal solution is here. Say I have a normalized database. The primary key of the whole system is a varchar. What I'm wondering is should I relate this varchar to an int for normalization or leave it? It's simpler to leave as a varchar, but it might be more optimal For instance I can have...
Can you really use names as primary keys? Isn't there a high risk of several people with the same name? If you really are so lucky that your name attribute can be used as primary key, then - by all means - use that. Often, though, you will have to make something up, like a customer\_id, etc. And finally: "NAME" is a ...
I believe that the majority of people who have developed any significant sized real world database applications will tell you that surrogate keys are the only realistic solution. I know the academic community will disagree but that is the difference between theoretical purity and practicality. Any reasonable sized q...
SQL Server normalization tactic: varchar vs int Identity
[ "", "sql", "sql-server", "database-design", "optimization", "normalization", "" ]
How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?
Session\_id can indeed be duplicated, but the probability is very low. If you have a website with a fair traffic, it may happens once in you web site life, and will just annoy one user for one session. This is not worth to care about unless you expect to build a very high traffic website or a service for the bank indu...
It's not very unique as shipped. In the default configuration it's the result of a hash of various things including the result of gettimeofday (which isn't terribly unique), but if you're worried, you should configure it to draw some entropy from /dev/urandom, like so ``` ini_set("session.entropy_file", "/dev/urandom"...
How unique is the php session id
[ "", "php", "session", "guid", "" ]
is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do\_this :do\_that
vim supports scripting in python (and in perl as well, I think). You just have to make sure that the vim distribution you are using has been compiled with python support. If you are using a Linux system, you can download the source and then compile it with ``` ./configure --enable-pythoninterp make sudo make instal...
Yes it is. There are several extensions on <http://www.vim.org/scripts/index.php> It can be done with python as well if the support for python is compiled in. Article about it: <http://www.techrepublic.com/article/extending-vim-with-python/> Google is our friend. HTH
Vim extension (via Python)?
[ "", "python", "vim", "" ]
How can I make this work? ``` switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } ``` I don't want to use the name since string comparing for types is just awfull and can be subject to change.
``` System.Type propertyType = typeof(Boolean); System.TypeCode typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: //doStuff break; case TypeCode.String: //doOtherStuff ...
You can't. What you can do is create a mapping between Types and a delegate using a dictionary: ``` var TypeMapping = new Dictionary<Type, Action<string>>(){ {typeof(string), (x)=>Console.WriteLine("string")}, {typeof(bool), (x)=>Console.WriteLine("bool")} }; string s = "my string"; TypeMapping[s.GetType()...
Switch over PropertyType
[ "", "c#", "switch-statement", "" ]
I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use? I can't use a ListView because you can only edit the first column (the label) and that's no good to me. Is the DataGridView the way to go, or are there third party alternative components that do a be...
DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required.
DataGridView is good. If you prefer a prettier interface, [Telerik controls](http://www.telerik.com/products/winforms/overview.aspx) are better.
Editable data grid for C# WinForms
[ "", "c#", "winforms", "user-interface", "editing", "" ]
I know in php you can embed variables inside variables, like: ``` <? $var1 = "I\'m including {$var2} in this variable.."; ?> ``` But I was wondering how, and if it was possible to include a function inside a variable. I know I could just write: ``` <?php $var1 = "I\'m including "; $var1 .= somefunc(); $var1 = " in t...
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call: ``` <? function somefunc($stuff) { $output = "<b>{$stuff}</b>"; return $output; } $somefunc='somefunc'; echo "foo {$somefunc("bar")} baz"; ?> ``` will output "`foo <b>bar</b> baz`". I find...
`"bla bla bla".function("blub")." and on it goes"`
In PHP is it possible to use a function inside a variable
[ "", "php", "html", "variables", "function", "" ]
I'm writing a pretty straightforward `e-commerce app` in **asp.net**, do I need to use transactions in my stored procedures? Read/Write ratio is about 9:1
Many people ask - do I need transactions? Why do I need them? When to use them? The answer is simple: use them all the time, unless you have a very good reason not to (for instance, don't use atomic transactions for "long running activities" between businesses). The default should always be yes. You are in doubt? - us...
Remember in SQL Server all single statement CRUD operations are in an implicit transaction by default. You just need to turn on explict transactions (BEGIN TRAN) if you need to make multiple statements act as an atomic unit.
Do I really need to use transactions in stored procedures? [MSSQL 2005]
[ "", "sql", "asp.net", "sql-server", "e-commerce", "" ]
The method signature of a Java `main`method is: ``` public static void main(String[] args) { ... } ``` Is there a reason why this method must be static?
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: ``` public class JavaClass{ protected JavaClass(int x){} public void main(String[] args){ } } ``` Should the JVM call `new JavaClass(int)`? What should it pass for `x`? ...
This is just convention. In fact, even the name main(), and the arguments passed in are purely convention. Java 21 introduced [alternative conventions](https://openjdk.org/jeps/445) as a preview feature; you can omit the `String[]` parameter, the `public` modifier, and even the `static` modifier. If you omit the `stat...
Why is the Java main method static?
[ "", "java", "static", "program-entry-point", "" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and...
There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to [grab it from svn.python.org](https://svn.python.org/projects/python/trunk/Tools/scripts/pin...
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited. I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python? I'd assume that you use a ...
Is there a way to convert indentation in Python code to braces?
[ "", "python", "" ]
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was an...
I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it.
Iron python, beautiful soup, win32 app
[ "", ".net", "python", "ironpython", "" ]
I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL. My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also lik...
While you might get it to work like first answer suggest you will likely run into problems due to threading. There is no simple solutions when it comes to threading, and here you would have SDL Qt and OpenGL mainloop interacting. Not fun. The easiest and sanest solution would be to decouple both parts. So that SDL and...
This is a simplification of what I do in my project. You can use it just like an ordinary widget, but as you need, you can using it's m\_Screen object to draw to the SDL surface and it'll show in the widget :) ``` #include "SDL.h" #include <QWidget> class SDLVideo : public QWidget { Q_OBJECT public: SDLVideo...
How do I use Qt and SDL together?
[ "", "c++", "winapi", "qt", "sdl", "" ]
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the li...
[RichQ's answer](https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734) is a reasonable technique, if you're using an array, vector, etc. If you're using a collection that isn't indexed by ordinal values... or think you *might need to* at some p...
Many times the caller wants access just to iterate over the collection. Take a page out of Ruby's book and make the iteration a private aspect of your class. ``` #include <algorithm> #include <boost/function.hpp> class Blah { public: void for_each_data(const std::function<void(const mydata&)>& f) const { ...
Efficient alternatives for exposing a Collection
[ "", "c++", "performance", "collections", "data-integrity", "" ]
I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons. In the RenderContent call in the Webpart I've got some code to add event handlers: ``` ArrayList nextPages = new ArrayList(); //populate nextPages .... ...
By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad(): ``` protected override void OnLoad(EventArge e) { base.OnLoad(e); EnsureChildControls(); var linkButtons = from c in AfterPageRepea...
Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit. From there it is easy enough to process because the CommandName ...
ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call
[ "", "c#", "asp.net", "sharepoint", "web-parts", "" ]
Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way ...
You basically want to signal the end of 1 process (return to the original `Requester.php`) and spawn a new process (finish `Provider.php`). There is probably a more elegant way to pull this off, but I've managed this a couple different ways. All of them basically result in exec-ing a command in order to shell off the s...
You can flush the output buffer with the flush() command. Read the comments in the [PHP manual](http://se.php.net/manual/en/function.flush.php) for more info
PHP: How to return information to a waiting script and continue processing
[ "", "php", "" ]
I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this: ``` select assigner_staff_id as staff_id, active_flag, assign_date, complete_date, mod_date from work where assigner_staff_id = '2096'; ``` The results it give me loo...
What are you using to get the results? The output you pasted looks like it's coming from SQL\*PLUS. It may be that whatever tool you are using to generate the results has some method of modifying the output. By default Oracle outputs columns based upon the width of the title or the width of the column data which ever ...
In your statement, you can specify the type of output you're looking for: ``` select /*csv*/ col1, col2 from table; select /*Delimited*/ col1, col2 from table; ``` there are other formats available such as xml, html, text, loader, etc. You can change the formatting of these particular options under tools > preferenc...
How to format Oracle SQL text-only select output
[ "", "sql", "oracle", "formatting", "" ]
My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this: This input: > The Web Should produce this output: > The Web This Is A Test Variable I've got it working. But looking at my code, I'm running multiple identical regexes on the same ...
The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled. Another possibility is to use a single regex as below: ``` MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE) item = MatchedQuotes.s...
[`sub`](http://docs.python.org/lib/node46.html) can take a callable as it's argument rather than a simple string. Using that, you can replace all variables with one function call: ``` >>> import re >>> var_matcher = re.compile(r'<%(.*?)%>', re.LOCALE) >>> string = '<%"TITLE"%> <%"SHMITLE"%>' >>> values = {'"TITLE"': "...
I'm using Python regexes in a criminally inefficient manner
[ "", "regex", "algorithm", "optimization", "python", "" ]
I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte\*) constructor which contains a warning in it's remarks: "The value parameter is assumed to ...
Any reason not to use the `String(sbyte*, int, int)` constructor? If you've worked out which portion of the buffer you need, the rest should be simple: ``` public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length) { unsafe { fixed (byte* pAscii = buffer) { r...
Oneliner (assuming the buffer actually contains ONE well formatted null terminated string): ``` String MyString = Encoding.ASCII.GetString(MyByteBuffer).TrimEnd((Char)0); ```
Fastest way to convert a possibly-null-terminated ascii byte[] to a string?
[ "", "c#", ".net", "string", "ascii", "" ]
Why is it wrong to use `std::auto_ptr<>` with standard containers?
The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. `std::auto_ptr` does not fulfill this requirement. Take for example this code: ``` class X { }; std::vector<std::au...
The **copy semantics** of `auto_ptr` are not compatible with the containers. Specifically, copying one `auto_ptr` to another does not create two equal objects since one has lost its ownership of the pointer. More specifically, copying an `auto_ptr` causes one of the copies to let go of the pointer. Which of these rem...
Why is it wrong to use std::auto_ptr<> with standard containers?
[ "", "c++", "stl", "raii", "auto-ptr", "c++-faq", "" ]
What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.
I don't know of any I've personally used with a C API, but [wxWidgets](http://www.wxwidgets.org/) is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, [wxPython](http://www.wxpython.org/) is a Python wrapper around wxWidgets and it is pretty easy to use.
I really like Qt. Have been working with it in several projects now. Although the project, I am currently working on, will be released for windows only, some of our developers code under Mac OS X using the gcc. And using different compilers and environments is an extra benefit for locating errors & bugs. I forgot to ...
Easiest cross platform widget toolkit?
[ "", "c++", "c", "cross-platform", "gui-toolkit", "" ]
I am looking for a tool that can take a unit test, like ``` IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); ``` and generate, automatically, the corresponding stub class and interface ``` interface IPerson // inferred from IPerson p = new Person(); { string Name { ...
What you appear to need is a parser for your language (Java), and a name and type resolver. ("Symbol table builder"). After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression...
Its amazing how no one really gave anything towards what you were asking. I dont know the answer, but I will give my thoughts on it. If I were to attempt to write something like this myself I would probably see about a resharper plugin. The reason I say that is because as you stated, resharper can do it, but in indiv...
Generating classes automatically from unit tests?
[ "", "c#", "unit-testing", "code-generation", "" ]
I am building a small website for fun/learning using a fairly standard Web/Service/Data Access layered design. To save me from constantly having to create instances of my service layer/data access layer classes, I have made the methods in them all static. I shouldn't get concurrency issues as they use local variables ...
Disadvantages: * You will be unable to write unit tests as you will be unable to write mock data access/business logic objects to test against. * You will have concurrency problems as different threads try to access the static code at the same time - or if you use synchronized static methods you will end up with threa...
You know those rides at the amusement park where they say "please keep your hands and feet inside the ride at all times"? It turns out the ride is a lot more fun if you don't. The only real trade-off is that you're not really following a true keeping-your-hands-and-feet-inside-the-ride-at-all-times approach. The point...
Static layers in a java web application
[ "", "java", "data-access-layer", "business-logic-layer", "" ]
I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?
Yes, assuming the HTTP server you're talking to supports/allows this: ``` public long GetFileSize(string url) { long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(...
> Can this be done with HTTP headers? Yes, this is the way to go. *If* the information is provided, it's in the header as the `Content-Length`. Note, however, that this is not necessarily the case. Downloading only the header can be done using a `HEAD` request instead of `GET`. Maybe the following code helps: ``` Ht...
How to get the file size from http headers
[ "", "c#", "http", "download", "http-headers", "" ]
Is there a built in dll that will give me a list of links from a string. I want to send in a string with valid html and have it parse all the links. I seem to remember there being something built into either .net or an unmanaged library. I found a couple open source projects that looked promising but I thought there w...
[SubSonic.Sugar.Web.ScrapeLinks](http://web.archive.org/web/20090510122547/http://subsonichelp.com/html/d4d577b3-5089-17a2-c667-db50ad3c9ff9.htm) seems to do part of what you want, however it grabs the html from a url, rather than from a string. You can check out their implementation [here](https://github.com/subsonic/...
I'm not aware of anything built in and from your question it's a little bit ambiguous what you're looking for exactly. Do you want the entire anchor tag, or just the URL from the href attribute? If you have well-formed XHtml, you might be able to get away with using an XmlReader and an XPath query to find all the anch...
Parse HTML links using C#
[ "", "c#", ".net", "html", "" ]
I'm trying to match elements with a name that is `'container1$container2$chkChecked'`, using a regex of `'.+\$chkChecked'`, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?
my guess, by your use of quotes, is you did something like ``` re = new RegExp('.+\$chkChecked'); ``` which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter instead you want ``` re = new RegExp('.+\\$chkChecked'); ```
try ``` string.match( /[$]chkChecked$/ ) ``` alternatively, you could try ``` string.match( /[^a-zA-Z0-9]chkChecked/ ) ``` ( Also, make sure your using `//` around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )
JavaScript RegEx Elements Match
[ "", "javascript", "regex", "" ]
I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, ex...
I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me. If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post Edit Ok, here's the basic Intercept...
+1 on postsharp. Have been using for several things (including some attempts on adding preconditions and postconditions to C# code) and don't know how I'd make it without it...
PostSharp - il weaving - thoughts
[ "", "c#", "visual-studio", "logging", "aop", "postsharp", "" ]
I'm looking for a suite of plugins that can help me finally switch over to vim full-time. Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it. What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by impo...
[Here you can find some info](http://www.sontek.net/python-with-a-modular-ide-vim) about this. It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim ...
And I write another plugin: <https://github.com/klen/python-mode> Old (now its more powerful) screencast here: <https://www.youtube.com/watch?v=67OZNp9Z0CQ>
Has anyone found a good set of python plugins for vim -- specifically module completion?
[ "", "python", "vim", "code-completion", "" ]
I've got many assemblies/projects in the same c#/.net solution. A setting needs to be saved by people using the web application gui, and then a console app and some test projects need to access the same file. Where should I put the file and how to access it? I've tried using "AppDomain.CurrentDomain.BaseDirectory" but...
Personally, I would be leveraging the database because the alternative is either a configuration headache or is more trouble than it's worth. You *could* configure each application to point to the same file, but that becomes problematic if you want to move the file. Or you could write a service to manage the file and ...
Put the file in ``` Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "[Company Name]\[Application Suite]"); ```
Letting several assemblies access the same text file
[ "", "c#", ".net", "file", "file-io", "filesystems", "" ]
So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly: ``` from decimal import Decimal >>> Decimal('1.0') + ...
Changing the decimal working precision to 2 digits is *not* a good idea, unless you absolutely only are going to perform a single operation. You should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and rou...
Decimals won't throw away decimal places like that. If you really want to limit precision to 2 d.p. then try ``` decimal.getcontext().prec=2 ``` EDIT: You can alternatively call quantize() every time you multiply or divide (addition and subtraction will preserve the 2 dps).
Significant figures in the decimal module
[ "", "python", "floating-point", "decimal", "physics", "significance", "" ]
Microsoft WPF? Adobe AIR/Flex? Adobe Flash? Curl programming language? How does AJAX fit in? Given a server written in C++ .NET.
The answer does depend really on what your application actually does and your platform requirements. If its a regular web application like gmail and you want it to work on lots of browsers and platforms; then I'd recommend a combination of HTML, CSS and [GWT](http://code.google.com/webtoolkit/) as this means your appl...
Using WPF you can build desktop and then almost 1:1 port it to silverlight and target the web
Best technology for developing an app that runs on DESKTOP and in BROWSER?
[ "", "c++", "client", "distributed", "" ]
What is the best way to disable the warnings generated via `_CRT_SECURE_NO_DEPRECATE` that allows them to be reinstated with ease and will work across Visual Studio versions?
If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add `_CRT_SECURE_NO_WARNINGS` symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions". Also you can define it just before yo...
You could disable the warnings temporarily in places where they appear by using ``` #pragma warning(push) #pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent // deprecated code here #pragma warning(pop) ``` so you don't disable all warnings, which can be harmful at times.
Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE
[ "", "c++", "visual-studio", "visual-c++", "" ]
Say I have the following C++: ``` char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; ``` Is this safe according to the C++ standard? Do I need to cast back to a `char*` and then use `delete[]`? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it...
It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite: [16.13] Can I drop the `[]` when deleting array of some built-in type (`char`, `int`, etc.)? [http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins)
No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that [thudbang](https://stackoverflow.com/questions/70880/deleting-a-buffer-through-a-different-type-of-pointer#70905) linked to says, `operator delete[]` might be overloaded to do something different to `operator...
deleting a buffer through a different type of pointer?
[ "", "c++", "pointers", "memory-management", "" ]
Let me first say, we validate every field on the server side, so this a question about client-side usability. What is the conventional wisdom on *exactly when* to validate and format html form input fields using javascript? As an example, we have a phone number field. We allow numbers, spaces, parentheses, and hyphen...
By far the best answer so far was not an answer but a comment (see above.) I'm adding it as an answer in case anyone misses it in the comment. See the following article on A List Apart. [Inline Validation in Web Forms by Luke Wroblewski](http://www.alistapart.com/articles/inline-validation-in-web-forms/)
> Validate and format it when the user exits the field. Yes. Provide noninvasive feedback to the user if validation or formatting rules fail. By noninasive I mean don't popup an alert or modal dialog box, thereby forcing the user to click something. Rather dynamically display a message adjacent or underneath the field...
What Event to Trigger Javascript Form Field Validation and Formatting?
[ "", "javascript", "validation", "usability", "" ]
I have an application that is causing a lot of headaches. It's a .NET app connecting to SQL Server 2005 via a web service. The program has grid that is filled by a long running stored procedure that is prone to timing out. In the case when it does time out and a SqlException is thrown, there is no execption handling to...
Since a SqlConnection closes while disposing i usually use this syntax ``` using (SqlConnection conn = new SqlConnection()) { // SqlCode here } ```
There is a connection limit; if your app crashes frequently and does not close the connections automatically, new connection requests will be denied. That said, connections do time out after a while if they're not closed.
What are the consequences of not closing database connection after an error?
[ "", ".net", "sql", "sql-server", "sql-server-2005", "web-services", "" ]
what is an efficient way to get a certain time for the next day in Java? Let's say I want the long for tomorrow 03:30:00. Setting Calendar fields and Date formatting are obvious. Better or smarter ideas, thanks for sharing them! Okami
I take the brute force approach ``` // make it now Calendar dateCal = Calendar.getInstance(); // make it tomorrow dateCal.add(Calendar.DAY_OF_YEAR, 1); // Now set it to the time you want dateCal.set(Calendar.HOUR_OF_DAY, hours); dateCal.set(Calendar.MINUTE, minutes); dateCal.set(Calendar.SECOND, seconds); dateCal.set(...
I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., "better or smarter ideas") with `Date`s almost always lands you in trouble. Heck, just using `java.util.Date` is asking for trouble. Added: Many have recommended [Joda Time](http://joda-time.sourceforge....
Get the time of tomorrow xx:xx
[ "", "java", "date", "" ]
Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++? I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service. I also know that you can retrieve performance counter data, but I need to create some custom counters...
See here: <http://msdn.microsoft.com/en-us/library/aa371925.aspx> It is not really hard, but a bit tedious as the API involves extensive usage of self-referential, variable-length structures and has to employ some IPC mechanism to obtain the data from the monitored process.
The support for adding C++ performance counters changed in Vista and beyond. The Performance DLL approach suggested in another answer still works, but the new technique described [here](https://msdn.microsoft.com/en-us/library/aa965334(v=vs.85).aspx) is easier to use. In this approach you write a manifest that describ...
Creating Custom Performance Counters in Visual C++
[ "", "c++", "visual-c++", "performancecounter", "" ]
I am searching for a good system for PHP, which does UnitTesting, Subversion, Coding Standards. I would love to hear your suggestions and which one is the best and why. I will be running it on a debian server so anything which runs on mac or windows servers would be out of the question.
I second Hudson for CI and PHP. I have written a tutorial on setting it up if you are interested. Edit: My tutorial is out of date. I highly recommend: <http://jenkins-php.org/>
We have played with Xinc, but we stuck with phpUnderControl for now. It seemed a bit more mature, when we evaluated the different solutions. phpug came with the obvious support for phpUnit, also generates docs (phpDocumentor) uses xdebug code coverage and project mess detection and even checks on CS (through phpcs). A...
Alternative to phpUnderControl - is it the best?
[ "", "php", "version-control", "continuous-integration", "" ]
I am working on a very large scale computing library that is using STL heavily. The library is being built using MSVC2003 and it is using its STL implementation. I am looking for an alternative STL implementation that would help the library lower its memory requirements and increase its performance. It is not possible...
[STLPort](http://stlport.org/). Haven't measured memory usage differences, but it's definitely quicker (yes, real world usage).
I question your basic premise, that you can not switch to a newer version of MSVC. I don't think you're going to get lower memory and increased performance "for free" by downloading a new STL. Or at least, if you did, you would probably have to do as many code fixes as if you were to just update to the latest MSVC. L...
What is the STL implementation with the lowest memory footprint?
[ "", "c++", "optimization", "stl", "" ]
I am working on a legacy project in `VC++/Win32/MFC`. Recently it became a requirement that the application work on a **tablet pc**, and this ushered in a host of new issues. I have been able to work with, and around these issues, **but am left with one wherein I could use some expert suggestions.** I have a particula...
As a tablet user I can answer a few of your questions. First: > You cannot very easily keep a "keyboard focus" on a window when the stylus has to trail out of the focused window to push a key on the virtual keyboard. Most of the virtual keyboards I've used (The windows tablet input panel and one under ubuntu) allow ...
@Greg - A clarification, this is a laptop pc with integrated tablet and stylus built in. the device has no dedicated keyboard (it is a virtual one on the touchscreen) and is not a wacom input device. Sorry for the confusion. It appears that there is an [SDK](http://www.microsoft.com/downloads/details.aspx?FamilyId=B46...
What happens when the stylus "lifts" on a tablet PC?
[ "", "c++", "windows", "events", "tablet-pc", "stylus-pen", "" ]
Everyone has accidentally forgotten the `WHERE` clause on a `DELETE` query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical. What if, in place of actual `DELETE` queries, the application and maintenance scripts did something...
That is fine if you want to do that, but it seems like a lot of work. How many people are manually changing the database? It should be very few, especially if your users have an app to work with. When I work on the production db I put EVERYTHING I do in a transaction so if I mess up I can rollback. Just having a stand...
This would be fine as long as your appliction does not require that the data is immediately deleted since you have to wait for the next interval of the cron job. I think a better solution and the more common practice is to use a development server and a production server. If your development database gets blown out, s...
Database safety: Intermediary "to_be_deleted" column/table?
[ "", "sql", "database", "" ]
In JavaScript, you can use [Lazy Function Definitions](http://peter.michaux.ca/article/3556) to optimize the 2nd - Nth call to a function by performing the **expensive** one-time operations only on the first call to the function. I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed,...
Use a local static var: ``` function foo() { static $called = false; if ($called == false) { $called = true; expensive_stuff(); } } ``` Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the funct...
Have you actually profiled this code? I'm doubtful that an extra boolean test is going to have any measurable impact on page rendering time.
Lazy Function Definition in PHP - is it possible?
[ "", "php", "design-patterns", "optimization", "" ]
I haven't kept up lately with the C++ world. Exactly where do things stand these days regarding the standard? Is TR1 adopted? Is there a TR2? How do these relate to C++0x? Are the subsumed? Has a decision been reached on threading yet?
You can find an extensive article about the upcoming C++0x on [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B0x) and the current state of C++ evolution [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2705.html). It is also worth giving a look at the current GNU implementation in [gcc](http://www.gnu.or...
I'd recommend you to visit <http://www.open-std.org/jtc1/sc22/wg21/>
State of C++ Standard
[ "", "c++", "standards", "" ]
The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday. For instance, how would I find out that there are 10 week days in between `31/08/2008` and `13/09/2008`?
``` $datefrom = strtotime($datefrom, 0); $dateto = strtotime($dateto, 0); $difference = $dateto - $datefrom; $days_difference = floor($difference / 86400); $weeks_difference = floor($days_difference / 7); // Complete weeks $first_day = date("w", $datefrom); $da...
If you are creating an invoicing system, you have to think about the bank holidays, Easter, etc. It is not simple to compute it. The best solution I have ever seen is to pregenerate a table with days and its type to SQL database (row per day = 365 rows per year) and then perform simple count query with proper selectio...
Given two dates what is the best way of finding the number of weekdays in PHP?
[ "", "php", "date", "" ]
Is there any good tool for working on Dabtabase apart from Toad which requires license and DBVisualiser not supportive
Try fabForce Database Designer; it is GPL too. <http://fabforce.net/dbdesigner4/>
i'd recommend oracle SQLdeveloper. it has all the functionality you need for developing and maintanice
Is there any good tool for working on Database apart from Toad which requires license and DBVisualiser not supportive
[ "", "sql", "database", "" ]
I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is...
This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <he...
if you do want to not use the conditional comments, so that you can put the css in a separate file, use `!important`. Something like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <style> ...
How do I get a floating footer to stick to the bottom of the viewport in IE 6?
[ "", "javascript", "css", "internet-explorer-6", "sticky-footer", "" ]
``` public class Test { public static void main(String[] args) { } } class Outer { void aMethod() { class MethodLocalInner { void bMethod() { System.out.println("Inside method-local bMethod"); } } } } ``` Can someone tell me how to print the mes...
You can only instantiate `MethodLocalInner` within `aMethod`. So do ``` void aMethod() { class MethodLocalInner { void bMethod() { System.out.println("Inside method-local bMethod"); } } MethodLocalInner foo = new MethodLocalInner(); // Default Constructor ...
Within the method *aMethod* after the declaration of the class *MethodLocalInner* you could for instance do the following call: ``` new MethodLocalInner().bMethod(); ```
Method Local Inner Class
[ "", "java", "inner-classes", "method-invocation", "" ]
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory). I've already written the code and it works, and I'm answering this myself so I can search for it later. Bu...
Here's how I did it (grabbing all files ending in ".ranks"): ``` import urllib2, cStringIO, zipfile try: remotezip = urllib2.urlopen(url) zipinmemory = cStringIO.StringIO(remotezip.read()) zip = zipfile.ZipFile(zipinmemory) for fn in zip.namelist(): if fn.endswith(".ranks"): ranks_...
Thanks Marcel for your question and answer (I had the same problem in a different context and encountered the same difficulty with file-like objects not really being file-like)! Just as an update: For Python 3.0, your code needs to be modified slightly: ``` import urllib.request, io, zipfile try: remotezip = urll...
How do I read selected files from a remote Zip archive over HTTP using Python?
[ "", "python", "http", "zip", "" ]
How to set all the values in a `std::map` to the same value, without using a loop iterating over each value?
Using a loop *is* by far the simplest method. In fact, it’s a one-liner:[C++17] ``` for (auto& [_, v] : mymap) v = value; ``` Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use `std::fill`. To use them anyway (pre-C++20), we need to write ada...
I encountered the same problem but found that the range returned by boost::adaptors::values is mutable, so it can then be used with normal algorithms such as std::fill. ``` #include <boost/range/adaptor/map.hpp> auto my_values = boost::adaptors::values(my_map); std::fill(my_values.begin(), my_values.end(), 123); ```
Setting all values in a std::map
[ "", "c++", "stl", "" ]
A couple of days ago, I read a blog entry (<http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx>) where the author discuss the idea of a generic natural language DSL parser using .NET. The brilliant part of his idea, in my opinion, is that the text is parsed and matched against cla...
Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. **[ANTLR](http://www.antlr.org/) isn't that hard to pickup and I think it is worthing looking into based on your problem.** If you use a parse grammar to build and abstract syntax tree from the input, its pretty easy to...
You might want to consider [Xtext](http://wiki.eclipse.org/Xtext), which internally uses ANTLR and does some nice things like auto-generating an editor for your DSL.
What would the best tool to create a natural DSL in Java?
[ "", "java", "dsl", "nlp", "parsing", "" ]
While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere. This led me to think about the best way to group 'helper' functions togeth...
Overhead is not an issue, namespaces have some advantages though * You can reopen a namespace in another header, grouping things more logically while keeping compile dependencies low * You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ....) e.g. I've done stuff like ...
A case where one might use `class` (or `struct`) over `namespace` is when one needs a type, for example: ``` struct C { static int f() { return 33; } }; namespace N { int f() { return 9; } } template<typename T> int foo() { return T::f(); } int main() { int ret = foo<C>(); //ret += foo<N>(); // compile erro...
'Helper' functions in C++
[ "", "c++", "class", "namespaces", "" ]
I would like to encrypt strings which could potentially only be about three or four characters but run to about twenty characters. A hashing function ([md5](http://www.php.net/md5), [sha1](http://www.php.net/sha1), [crypt](http://www.php.net/crypt) etc) is not suitable as I would like to be able to decrypt the informat...
I highly recommend the suggestions of **Chris Kite**. Without knowing more about what you're doing, why, and the threats you anticipate needing to protect against AES-128 is likely sufficient. The ability to use symmetric encryption is great for a standalone app that will be both the decryptor and encryptor of data. As...
I like to use GnuPG for anything that needs to be encrypted on a server and then possibly decrypted either on the server or on another server (which is usually my case). This allows for an extra level of security since in my scenario the encrypting server doesn't have the key to decrypt the data. It also allows for eas...
What is the best way to encrypt a very short string in PHP?
[ "", "php", "encryption", "" ]
Events are synchronous in C#. I have this application where my main form starts a thread with a loop in it that listens to a stream. When something comes along on the stream an event is fired from the loop to the main form. If the main form is slow or shows a messagebox or something the loop will be suspended. What is...
Hmmm, I've used different scenarios that depended on what I needed at the time. I believe the BeginInvoke would probably be the easiest to code since you're almost there. Either way you should be using Invoke already, so just changing to BeginInvoke. Using a callback on a separate thread will accomplish the same thing...
Since you're using a form, the easier way is to use the [BackgroundWorker](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker) component. > The BackgroundWorker class allows you > to run an operation on a separate, > dedicated thread. Time-consuming > operations like downloads and data...
Best way to make events asynchronous in C#
[ "", "c#", "events", "asynchronous", "" ]
What is the difference between `==` and `===`? * How exactly does the loosely `==` comparison work? * How exactly does the strict `===` comparison work? What would be some useful examples?
## Difference between `==` and `===` The difference between the loosely `==` equal operator and the strict `===` identical operator is exactly explained in the [manual](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison): Comparison Operators | Example | Name | Result | | --- | ...
The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value. Examples: ``` 1 === 1: true 1 == 1: true 1 === "1": false // 1 is an integer, "1" is a stri...
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
[ "", "php", "operators", "" ]
In an application where users can belong to multiple groups, I'm currently storing their groups in a column called `groups` as a binary. Every four bytes is a 32 bit integer which is the `GroupID`. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually fi...
You have a many-to-many relationship between users and groups. This calls for a separate table to combine users with groups: ``` User: (UserId[PrimaryKey], UserName etc.) Group: (GroupId[PrimaryKey], GroupName etc.) UserInGroup: (UserId[ForeignKey], GroupId[ForeignKey]) ``` To find all users in a given group, you jus...
I'd definitely go for the separate table - certainly the best relational view of data. If you have indexes on both UserID and GroupID you have a quick way of getting users per group and groups per user.
What is the best way to add users to multiple groups in a database?
[ "", "sql", "database", "" ]
I have a large codebase, and I'd like to refactor the package structure so that classes which interact heavily go in the same package. It seems that it should be possible to create a tool that could look at the interactions between classes, and then group together those classes that interact heavily. These groupings m...
Structure Analysis for Java is an Eclipse plugin that does some dependency analysis: <http://stan4j.com/>
Structure101 is another product that can analyze the structure of your code and do dependency and what-if analysis. <http://www.headwaysoftware.com/products/structure101/index.php>
Is there a tool that will look at my Java code, and suggest a good package structure?
[ "", "java", "refactoring", "" ]
Phantom References serve for post-mortem operations. The Java specification states that a **phantom referenced object** will not be deallocated until the phantom-reference itself is cleaned. My question is: What purpose does this feature (object not deallocated) serve? (The only idea i came up with, is to allow nativ...
The only good use-case I can think of, that would prevent deallocation, is one where some kind of JNI-implemented asynchronous data source is writing into the referenced object, and must be told to stand down - to stop writing into the object - before the memory is recycled. If prior deallocation were allowed, a simple...
Edit, since I've misunderstand the question first: Quoted from here <http://www.memorymanagement.org/glossary/p.html>: > The Java specification says that the > phantom reference is not cleared when > the reference object is enqueued, but > actually, there's no way in the > language to tell whether that has been > don...
Phantom Referenced Objects
[ "", "java", "finalize", "phantom-reference", "" ]
I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that ``` void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x < x1; x +...
Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y. This boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun). ``` template< int XIncrement, YIncrement > struct DrawSca...
Why you just do not extract the body of the for cycle into a separate function? Then you can do the funny stuff in the extracted function. ``` void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x < x1; x += step) { DrawScale(dc, x, y0, x, y1); } } void DrawScaleY(H...
Orthogonal variables code duplication problem
[ "", "c++", "code-duplication", "" ]
Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at leas...
If you have a crash, you can get information about where the crash happened whether you have a debug or a release build. And you can see the call stack even if you are on a computer that does not have the source code. To do this you need to use the PDB file that was built with your EXE. Put the PDB file inside the sam...
If you run the debug version on a machine with VS, it should offer to bring it up and let you see the stack trace. The problem is that the real problem is not on the call stack any more. If you free a pointer twice, that can result in this problem somewhere else unrelated to the program (the next time anything accesse...
How to get a stack trace when C++ program crashes? (using msvc8/2005)
[ "", "c++", "debugging", "visual-studio-2005", "stack-trace", "" ]
``` public static Logger getLogger() { final Throwable t = new Throwable(); final StackTraceElement methodCaller = t.getStackTrace()[1]; final Logger logger = Logger.getLogger(methodCaller.getClassName()); logger.setLevel(ResourceManager.LOGLEVEL); return logger; } ``` This method would return a lo...
I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free.
The [MethodHandles](https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.html) class (as of Java 7) includes a [Lookup](https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.Lookup.html) class that, from a static context, can find and return the name of the current class. Consider...
Java logger that automatically determines caller's class name
[ "", "java", "logging", "stack-trace", "" ]
I have an Asset object that has a property AssignedSoftware, which is a collection. I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception. Is there a standard .NET excepti...
From the Class Library design guidelines for errors (<http://msdn.microsoft.com/en-us/library/8ey5ey87(VS.71).aspx>): > In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and pe...
Why has `InvalidOperationException` been accepted as the answer?! It should be an `ArgumentException`?! `InvalidOperationException` should be used if the object having the method/property called against it is not able to cope with the request due to uninit'ed state etc. The problem here is **not the object being Added...
What is the correct .NET exception to throw when try to insert a duplicate object into a collection?
[ "", "c#", "exception", "collections", "" ]
I'm searching a small **Java** based RSS/Feed Generator, something like the [FeedCreator.class.php](http://www.bitfolge.de/rsscreator-en.html) library, any suggestions?, thanks!
There's the Rome framework as well <http://rometools.github.io/rome/> Does RSS and Atom
How about [jRSS](http://jrss.sourceforge.net/)? It looks promising -- supports generating RSS 2 and is relatively small.
Do you know a good Java RSS/Feed Generator?
[ "", "java", "rss", "generator", "feed", "" ]
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a `URLConnection`. How can I specify this?
This should do the trick: ``` URL url = new URL(yourUrlHere); Proxy proxy = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress( InetAddress.getByAddress( new byte[]{your, ip, interface, here}), yourTcpPortHere)); URLConnection conn = url.openConnection(proxy); ``` And you are done. Dont forg...
Using the Apache commons HttpClient I have also found the following to work (removed try/catch for clarity): ``` HostConfiguration hostConfiguration = new HostConfiguration(); byte b[] = new byte[4]; b[0] = new Integer(192).byteValue(); b[1] = new Integer(168).byteValue(); b[2] = new Integer(1).byteValue(); b[3] = new...
How can I specify the local address on a java.net.URLConnection?
[ "", "java", "tomcat", "ip", "urlconnection", "" ]
I believe strongly in using unit-tests as part of building large multi-platform applications. We currently are planning on having our unit-tests within a separate project. This has the benefit of keeping our code base clean. I think, however, that this would separate the test code from the implementation of the unit. W...
There are many Test Unit frameforks for C++. CppUnit is certainly not the one I would choose (at least in its stable version 1.x, as it lacks many tests, and requires a lot of redundant lines of codes). So far, my preferred framework is [CxxTest](http://cxxtest.sf.net/), and I plan on evaluating [Fructose](http://fruct...
That's a reasonable approach. I've had very good results both with [UnitTest++](http://unittest-cpp.sourceforge.net/) and [Boost.Test](http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/index.html) I've looked at CppUnit, but to me, it felt more like a translation of the JUnit stuff than something aimed at C++. ...
How do you implement unit-testing in large scale C++ projects?
[ "", "c++", "unit-testing", "coding-style", "" ]
If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path? I know of ``` Path.Combine ``` but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters. e.g: ``` stri...
> Does C# support unlimited args in methods? Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested): ``` string CombinePaths(params string[] parts) { string result = String.Empty; foreach (string s in par...
LINQ to the rescue again. The [Aggregate](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate) extension function can be used to accomplish what you want. Consider this example: ``` string[] ary = new string[] { "c:\\", "Windows", "System" }; string path = ary.Aggregate((aggregation, val) => ...
Building a directory string from component parts in C#
[ "", "c#", "filesystems", "string-building", "" ]
How can I find the 2nd, 3rd, ... nth maximum value of a column?
You could sort the column into descending format and then just obtain the value from the nth row. EDIT:: Updated as per comment request. ***WARNING*** completely untested! ``` SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6 ``` Something like the above should work for Oracle ... you might ...
Consider the following Employee table with a single column for salary. ``` +------+ | Sal | +------+ | 3500 | | 2500 | | 2500 | | 5500 | | 7500 | +------+ ``` The following query will return the Nth Maximum element. ``` select SAL from EMPLOYEE E1 where (N - 1) = (select count(distinct(SAL)) from ...
Query to find nᵗʰ max value of a column
[ "", "sql", "database", "" ]
I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore. Which module do you recommend? Why?
psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called [bpgsql](http://barryp.org/software/bpgsql/). I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile...
I suggest Psycopg over Psycopg2 since the first one seems a bit more sable. At least in my experience. I have an application running 24/7 and sometimes I was getting random memory crashes (double free or corruption errors) from Psycopg2. Nothing I could have debug fast or easily since it's not a Python error but a C er...
Python PostgreSQL modules. Which is best?
[ "", "python", "postgresql", "module", "" ]
So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?
PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The [RFC for closures](http://wiki.php.net/rfc/closures) gives a good example: ``` function replace_spaces ($text) { $replacement = function ($matches) { return str...
When you will need a function in the future which performs a task that you have decided upon now. For example, if you read a config file and one of the parameters tells you that the `hash_method` for your algorithm is `multiply` rather than `square`, you can create a closure that will be used wherever you need to hash...
Closures in PHP... what, precisely, are they and when would you need to use them?
[ "", "php", "oop", "closures", "" ]
Inspired by another question asking about the missing `Zip` function: Why is there no `ForEach` extension method on the `IEnumerable` interface? Or anywhere? The only class that gets a `ForEach` method is `List<>`. Is there a reason why it's missing, maybe performance?
There is already a `foreach` statement included in the language that does the job most of the time. I'd hate to see the following: ``` list.ForEach( item => { item.DoSomething(); } ); ``` Instead of: ``` foreach(Item item in list) { item.DoSomething(); } ``` The latter is clearer and easier to read **in m...
ForEach method was added before LINQ. If you add ForEach extension, it will never be called for List instances because of extension methods constraints. I think the reason it was not added is to not interference with existing one. However, if you really miss this little nice function, you can roll out your own version...
Why is there no ForEach extension method on IEnumerable?
[ "", "c#", ".net", "vb.net", "extension-methods", "" ]
Greetings, I'm trying to find either a free .NET library or a command-line executable that lets me convert M4A files to either MP3s or WMA files. Please help :).
Found it! <http://pieter.wigleven.com/it/archives/3> There may be other solutions, but this is gold for what I was looking for. P.S. I've written [a .NET DLL](https://github.com/AlexeyMK/M4A-to-MP3--.net-) which handles this behind-the-scenes. It's pretty terrible code, but it gets the job done.
This is simple if you know the right tools: ``` ffmpeg -i infile.m4a tmp.wav lame tmp.wav outfile.mp3 ``` Here a batch version (sorry Linux/Mac only): ``` #!/bin/bash n=0 maxjobs=3 for i in *.m4a ; do ffmpeg -i "$i" "$TMP/${i%m4a}wav" (lame "$TMP/${i%m4a}wav" "${i%m4a}mp3" ; rm "$TMP/${i%m4a}wav") & #...
How do I convert an M4A file to an MP3 or WMA file programmatically?
[ "", "c#", ".net", "mp3", "" ]
I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in th...
This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores: * Flash is even easier to reverse...
You may be asking the wrong question. You seem focused on the methods people are using to game their way up the high score list, but blocking specific methods only goes so far. I have no experience with TamperData, so I can't speak to that. The question you should be asking is: "How can I verify that submitted scores ...
What is the best way to stop people hacking the PHP-based highscore table of a Flash game
[ "", "php", "actionscript-3", "security", "actionscript", "actionscript-2", "" ]
How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: ``` import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.S...
I was missing ``` l.set_option(ldap.OPT_REFERRALS, 0) ``` From the init.
If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server: ``` import win32security token = win32security.LogonUser( username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) authenticated = bo...
Authenticating against active directory using python + ldap
[ "", "python", "authentication", "active-directory", "ldap", "" ]
I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java: ``` Array ( ["col_name_1"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"],...
You can use a Map and a List (these both are interfaces implemented in more than one way for you to choose the most adequate in your case). For more information check the tutorials for [Map](http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html) and [List](http://java.sun.com/docs/books/tutorial/coll...
Try using a `Map<String, List<String>>`. This will allow you to use Strings as keys / indices into the outer map and get a result being a list of Strings as values. You'll probably want to use a `HashMap` for the outer map and `ArrayList`'s for the inner lists. If you want some clean code that is similar to the PHP yo...
Java: Arrays & Vectors
[ "", "java", "arrays", "data-structures", "hashmap", "" ]
Any ideas how to determine the number of active threads currently running in an [`ExecutorService`](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html)?
Use a [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) implementation and call [getActiveCount()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()) on it: ``` int getActiveCount() // Returns the approximate numb...
Assuming `pool` is the name of the ExecutorService instance: ``` if (pool instanceof ThreadPoolExecutor) { System.out.println( "Pool size is now " + ((ThreadPoolExecutor) pool).getActiveCount() ); } ```
Active threads in ExecutorService
[ "", "java", "multithreading", "concurrency", "" ]
What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?
If the IronPython and .Net Compact Framework teams work together, Visual Studio may one day support Python for Windows Mobile development out-of-the-box. Unfortunately, [this feature request has been sitting on their issue tracker for ages](http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=9191)...
(I used to write customer apps for Windows Mobile.) Forget about python. Even if it's technically possible: * your app will be big (you'll have to bundle the whole python runtime with your app) * your app will use lots of memory (python is a memory hog, relative to C/C++) * your app will be slow * you wont find any d...
Windows Mobile development in Python
[ "", "python", "windows-mobile", "" ]
I've been doing some work with the JAX-RS reference implementation (Jersey). I know of at least two other frameworks (Restlet & Apache CXF). My question is: Has anyone done some comparison between those frameworks and if so, which framework would you recommend and why?
FWIW we're using Jersey as its packed full of features (e.g. WADL, implicit views, XML/JSON/Atom support) has a large and vibrant developer community behind it and has great [spring integration](http://www.javakaffee.de/blog/2008/04/21/jersey-spring-integration-mostly-complete/). If you use JBoss/SEAM you might find R...
[Restlet](http://www.restlet.org) has an extensive list of extensions for Spring, WADL, XML, JSON as well and many more, including an extension for JAX-RS API. It is also the sole framework [available in six consistent editions](http://www.restlet.org/downloads/testing): * Java SE * Java EE * Google Web Toolkit * Goo...
JAX-RS Frameworks
[ "", "java", "rest", "jax-rs", "" ]
I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? ``` for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } ``` vs ``` function myEventHandler() { // do something } for (var i = 0; i <...
The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function: ``` for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } ``` You are creating a thousand distinct...
Here's my test code: ``` var dummyVar; function test1() { for (var i = 0; i < 1000000; ++i) { dummyVar = myFunc; } } function test2() { for (var i = 0; i < 1000000; ++i) { dummyVar = function() { var x = 0; x++; }; } } function myFunc() { var x = 0;...
Does use of anonymous functions affect performance?
[ "", "javascript", "performance", "optimization", "" ]
I'm trying to store an xml serialized object in a cookie, but i get an error like this: ``` A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...") ``` I know the problem from similiar cases when you try to store something that looks like javascript co...
I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for *all* headers including the cookie). Pick a less verbose encoding strategy such as delimiters instead e.g. a|b|c or separate cookie values. Delimited encoding makes it especially easy and fast to decode the valu...
Storing serialized data in a cookie is a very, very bad idea. Since users have complete control over cookie data, it's just too easy for them to use this mechanism to feed you malicious data. In other words: *any* weakness in your deserialization code becomes instantly exploitable (or at least a way to crash something)...
Storing xml data in a cookie
[ "", "c#", "asp.net", "serialization", "cookies", "" ]
I want to run javascript/Python/Ruby inside my application. I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process. For example, the cr...
Basically, you have two problems: how to define point of injections in your generated code, and how to run python / ruby / whatev scripts from there. Depending on how you generate the process, one possible solution would be to add a function to each possible point of injection. The function would check, whether the us...
Look into IronPython and IronRuby -- these will allow you to easily interoperate with C#.
Running scripts inside C#
[ "", "c#", "scripting", "" ]
On a file path field, I want to capture the directory path like: ``` textbox1.Text = directory path ``` Anyone?
Well I am using VS 2008 SP1. This all I need: ``` private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog profilePath = new FolderBrowserDialog(); if (profilePath.ShowDialog() == DialogResult.OK) { profilePathTextBox.Text = profilePath.SelectedPath; } else ...
There is a FolderBrowserDialog class that you can use if you want the user to select a folder. <http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx> ``` DialogResult result = folderBrowserDialog1.ShowDialog(); if (result.Equals(get_DialogResult().OK)) { textbox1.Text = folderBrow...
OpenFileDialog. How about "Specify Directory Dialog"?
[ "", "c#", "directory", "openfiledialog", "" ]
Let me start off with a bit of background. This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem. A n...
See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays. Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/l...
Note that even if you did find it this way, there's no guarantee that the longest match is actually the one being looked for. Instead, you may find common initialisation code or string tables added by the same compiler for instance.
Find matching sequences in two binary files
[ "", "python", "binary", "diff", "antivirus", "" ]
Why use one over the other?
== is the identity test. It will return true if the two objects being tested are in fact the same object. `Equals()` performs an equality test, and will return true if the two objects consider themselves equal. Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For ex...
@John Millikin: > Pointed out below: some value types like DateTime provide overloads for the == operator >that give it equality semantics. So the exact behavior will depend on the types of the >objects you are comparing. To elaborate: DateTime is implemented as a struct. All structs are children of System.ValueType...
== or .Equals()
[ "", "c#", "" ]
There is a [Microsoft knowledge base article](http://support.microsoft.com/?scid=194627) with sample code to open all mailboxes in a given information store. It works so far (requires a bit of [copy & pasting](http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx) on compilers newer than VC++ 6.0). At one poin...
Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it. The following code snippet, inserted after ``` printf("Created MAPI session\n"); ``` in the example from [KB194627](http://support.microsoft.com/kb/194627), will show the *Server DN*. ``` LPPROFSECT lpProfSect; h...
It'll be in Active Directory, so you'd use ADSI/LDAP to look at CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=*example*,DC=*com*. Use Sysinternals' ADExplorer to have a dig around in there to find the value you're looking for.
How to find out the distinguished name of the information store to feed to IExchangeManageStore::GetMailboxTable?
[ "", "c++", "outlook", "exchange-server", "mapi", "" ]
I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.
``` select so.name, sc.text from sysobjects so inner join syscomments sc on so.id = sc.id where sc.text like '%INSERT INTO xyz%' or sc.text like '%UPDATE xyz%' ``` This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the quer...
`sys.sql_dependencies` has a list of entities with dependencies, including tables and columns that a sproc includes in queries. See [this post](https://stackoverflow.com/questions/69923/stored-procedures-reverse-engineering#93967) for an example of a query that gets out dependencies. The code snippet below will get a l...
List of Stored Procedure from Table
[ "", "sql", "sql-server", "stored-procedures", "" ]
My company is considering changing continuous integration servers (I won't say which one we have now, so I won't skew your responses in anyway :) ) I wondering if anybody has any recommendations? Best user experience, level of difficulty to maintain, etc... Our code is all in java, and we use ANT as a build tool.
I recently implemented a [Hudson](http://hudson-ci.org/) server. Having previously used Cruise Control, **I am very satisfied with Hudson and very impressed with its ease of setup and use.** Adding new projects is infinitely easier than it was with Cruise Control.
*Edit: We use Hudson now.* A while ago I looked into a bunch of these with the following requirements: * Java code * Ant builds * Groovy builds * Distributed builds * SCM trigger integration * http reports * smtp reports The [Continuous Integration Feature Matrix](http://confluence.public.thoughtworks.org/display/CC...
Continuous Integration Servers
[ "", "java", "continuous-integration", "" ]
Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)? I would expect to be able to instantiate a an object of some sort, give it a template along the lines of ``` Dear ${customer.firstName}. You order will be dispatched on ...
You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper. This blog post describes how to do it: [Java: using EL outside J2EE](http://illegalargumentexceptio...
[StringTemplate](http://www.stringtemplate.org/) is a more lightweight alternative to Velocity and Freemarker.
JSTL/JSP EL (Expression Language) in a non JSP (standalone) context
[ "", "java", "jsp", "el", "text-formatting", "" ]
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server? I'm not so concerned with browser security issues. etc. as the implementation would be for [HTA](http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx). But is it possible?
I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd\_event API call because SendKeys can't do PrintScreen. Here's the code for that: ``` Declare Sub keybd_event Lib "user32" _ (ByVal bVk As Byte, ByVal bScan As Byte, ByV...
Google is doing this in Google+ and a talented developer reverse engineered it and produced <http://html2canvas.hertzen.com/> . To work in IE you'll need a canvas support library such as <http://excanvas.sourceforge.net/>
Take a screenshot of a webpage with JavaScript?
[ "", "javascript", "hta", "webpage-screenshot", "" ]
**Problem:** Ajax suggest-search on [*n*] ingredients in recipes. That is: match recipes against multiple ingredients. For instance: `SELECT Recipes using "flower", "salt"` would produce: `"Pizza", "Bread", "Saltwater"` and so forth. **Tables:** ``` Ingredients [ IngredientsID INT [PK], IngredientsName VARC...
You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a [table value parameter](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters). If you're using SQL Server 2005, you can use [XML to simulate this capability](http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing...
You could at least parametrize the where clausule to avoid SQL injection, something alike: ``` using System.Data; using System.Data.SqlClient; using System.Text; class Foo { public static void Main () { string[] parameters = {"salt", "water", "flower"}; SqlConnection connection = new SqlConnec...
SQL Server: Dynamic where-clause
[ "", "c#", "sql-server", "performance", "" ]