Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I'm tired of adding ten link libraries into my project, or requiring eight of them to use my own. I'd like to take existing libraries like libpng.a, libz.a, libjpeg.a, and combine them into one single .a library. Is that possible? How about combining .lib libraries?
|
On Unix like systems, the ld and ar utilities can do this. Check out <http://en.wikipedia.org/wiki/Ar_(Unix)> or lookup the man pages on any Linux box or through Google, e.g., 'Unix man ar'.
Please note that you might be better off linking to a shared (dynamic) library. This would add a dependency to your executable, but it will dramatically reduce its size, especially if you're writing a graphic application.
|
You could extract the object files from each library with
```
ar x <library name>
```
and then merge them all into a new library with
```
ar cs <new library name> <list each extracted object file>
```
|
How can I combine several C/C++ libraries into one?
|
[
"",
"c++",
"c",
"archive",
""
] |
I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE.
What are the steps to create such an executable?
|
Single Assembly Deployment of Managed and Unmanaged Code
Sunday, February 4, 2007
.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs.
So here´s what I came up with for a solution:
I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.
Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think.
```
namespace MyLib
{
public class MyClass
{
static MyClass()
{
ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll");
ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll");
}
...
```
In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code.
The code to extract the DLLs into files of their own is simple:
```
public static class ResourceExtractor
{
public static void ExtractResourceToFile(string resourceName, string filename)
{
if (!System.IO.File.Exists(filename))
using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
{
byte[] b = new byte[s.Length];
s.Read(b, 0, b.Length);
fs.Write(b, 0, b.Length);
}
}
}
```
Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource.
For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g.
```
[DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b);
```
That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient.
Enjoy!
<http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx>
|
Try [boxedapp](http://boxedapp.com/ "boxedapp sdk"); it allows to load all DLLs from memory. Also, it seems that you can even embed .net runtime. Good to create a really standalone applications...
|
How can a C++ windows dll be merged into a C# application exe?
|
[
"",
"c#",
"dll",
"merge",
""
] |
```
$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
```
I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma followed by the numerical digits and then the semicolon.
I'll provide an example:
Start:
```
hello world 1007;
```
End:
```
hello world,1007;
```
|
The two `|` at the start and end probably are incorrect - and should both be forward-slashes.
All other forward slashes should be backward slashes (and need escaping).
And since PHP 4.04 `$n` is the preferred way of referring to a capture group.
```
$output = preg_replace("/(\\D)\\s+(\\d+;)/", "$1,$2", $output);
```
If you use single quotes you don't need to escape your backslashes:
```
$output = preg_replace('/(\D)\s+(\d+;)/', '$1,$2', $output);
```
|
Should those forward-slashes be backslashes? You'll need to escape them for PHP too unless you change your double-quotes to single-quotes.
|
What is wrong with this PHP regular expression?
|
[
"",
"php",
"regex",
""
] |
I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom `IEnumerator` interface that iterates through the values.
```
public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
```
|
First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection).
Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.
Raymond Chen's recent series of blog posts ("The implementation of iterators in C# and its consequences") is a good place to get up to speed.
* Part 1: <https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx>
* Part 2: <https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx>
* Part 3: <https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx>
* Part 4: <https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx>
|
Just implement the `IEnumerable<T>` interface. No need to implement the `IEnumerator<T>` unless you want to do some special things in the enumerator, which for your case doesn't seem to be needed.
```
public class Mapper<K,T> : IEnumerable<T> {
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
}
```
and that's it.
|
How would you implement the IEnumerator interface?
|
[
"",
"c#",
".net",
"collections",
"ienumerable",
"ienumerator",
""
] |
What is the reason for the following warning in some C++ compilers?
> No newline at end of file
Why should I have an empty line at the end of a source/header file?
|
Think of some of the problems that can occur if there is no newline. According to the ANSI standard the `#include` of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the `#include <foo.h>` after the contents of the file. So if you include a file with no newline at the end to the parser it will be viewed as if the last line of `foo.h` is on the same line as the first line of `foo.cpp`. What if the last line of foo.h was a comment without a new line? Now the first line of `foo.cpp` is commented out. These are just a couple of examples of the types of problems that can creep up.
---
Just wanted to point any interested parties to James' answer below. While the above answer is still correct for C, the new C++ standard (C++11) has been changed so that this warning should no longer be issued if using C++ and a compiler conforming to C++11.
From C++11 standard via James' post:
> A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file (C++11 §2.2/1).
|
The requirement that every source file end with a non-escaped newline was removed in C++11. The specification now reads:
> A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file (C++11 §2.2/1).
A conforming compiler should no longer issue this warning (at least not when compiling in C++11 mode, if the compiler has modes for different revisions of the language specification).
|
"No newline at end of file" compiler warning
|
[
"",
"c++",
"compiler-construction",
"warnings",
"c-preprocessor",
""
] |
From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:
```
// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
this.mThread.Start(60000);
}
else
{
this.mThread.Start(0);
}
```
So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?
|
The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the details behind the *check* variable, it's impossible to know what might trigger this behavior.
You should reorganize your code so that .Start is guaranteed to only be called on new objects. In short, you should put the Start method into the same if-statement as the one that creates a new thread object.
Personally, I would try to reorganize the entire code so that I didn't need to create another thread, but wrap the code inside the thread object inside a loop so that the thread just keeps on going.
|
It's possible for a thread to be in more than one state at once therefore the ThreadState property is actually a bitmap of possible states. So testing for equality with just one state will not give you the right result. You would need to do something like:
```
if((mThread.ThreadState & ThreadState.Running) != 0)
```
However, checking thread state is the wrong to do anything. I'm not entirely clear what you're trying to achieve but I will guess that you're waiting for a thread to terminate before restarting it. In that case you should do:
```
mThread.Join();
mThread = new Thread(new ParameterizedThreadStart(Monitor));
if(check)
mThread.Start(60000);
else
mThread.Start(0);
```
Although if you describe the problem you're trying to solve in more detail I'm almost certain there will be a better solution. Waiting around for a thread to end just to restart it again doesn't seem that efficient to me. Perhaps you just need some kind of inter-thread communication?
John.
|
A ThreadStateException occures when trying to restart a thread
|
[
"",
"c#",
".net",
"multithreading",
"exception",
""
] |
I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.
The problem is that inside of my "popup" form, I need to `$(function()
{my function here});` syntax to do some stuff when the page loads,
along with registering some `.fn` extensions for some dynamic dropdowns
using ajax calls.
I have created my `<script type="text/javascript" src="jquery.js">` but
I don't think these are being included, and also my `$(function)` is not
being called.
Is this possible to do or do I need to find another way of
accomplishing what I need to do?
|
If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.
So, you load the popup form like this:
```
$.ajax({
//...
success: function(text) {
// insert text into container
// the code from $(function() {});
}
});
```
|
The script isn't getting run because the document's ready event has already been fired. Remove your code from within the
```
$()
```
|
using load() to load page that also uses jQuery
|
[
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-ui-dialog",
"jquery-ui-plugins",
""
] |
Background: At my company we are developing a bunch applications that are using the same core dll's. These dll's are using Spring.net's IoC-container to wire things up (auto-wiring). All applications are using the same spring configuration file, and this configuration file points to many classes in many different dll's. But not all application needs functionality from every dll. But because of the way IoC-containers works, all dll's is loaded for Spring.net to examine the types and check what interfaces they implement and so on.
Core question: I understand that it's better to just load the dll's you really use. But is it really bad for memory usage just to load a managed dll? Or is it first then you are using classes in the dll and they are getting JIT'ed that the most memory are used?
|
If none of the code from the assembly is ever used, then eventually the pages from that assembly will be moved from memory into the page file in favour of actively used pages. In which case, the overall long-term effect is likely to be minor. Although, there will be a negative effect on startup time.
|
I don't think it's so bad. Only problem is that because of large metadata and amount of memory your application takes it's more possible that some parts of application which are in use will be located at different memory pages which can 'cause some performance leaks, but it's very low segment of application where this type of things are critical.
|
Is it bad to load many managed DLL's without using any types in them?
|
[
"",
"c#",
".net",
"dll",
"inversion-of-control",
"spring.net",
""
] |
I want to prevent XSS attacks in my web application. I found that HTML Encoding the output can really prevent XSS attacks. Now the problem is that how do I HTML encode every single output in my application? I there a way to automate this?
I appreciate answers for JSP, ASP.net and PHP.
|
You don't want to encode all HTML, you only want to HTML-encode any user input that you're outputting.
For PHP: [htmlentities](http://us.php.net/htmlentities) and [htmlspecialchars](http://us.php.net/manual/en/function.htmlspecialchars.php)
|
One thing that you **shouldn't** do is filter the input data as it comes in. People often suggest this, since it's the easiest solution, but it leads to problems.
Input data can be sent to multiple places, besides being output as HTML. It might be stored in a database, for example. The rules for filtering data sent to a database are very different from the rules for filtering HTML output. If you HTML-encode everything on input, you'll end up with HTML in your database. (This is also why PHP's "magic quotes" feature is a bad idea.)
You can't anticipate all the places your input data will travel. The safe approach is to prepare the data **just before** it's sent somewhere. If you're sending it to a database, escape the single quotes. If you're outputting HTML, escape the HTML entities. And once it's sent somewhere, if you still need to work with the data, use the original un-escaped version.
This is more work, but you can reduce it by using template engines or libraries.
|
How do I HTML Encode all the output in a web application?
|
[
"",
"php",
"asp.net",
"jsp",
""
] |
I have two elements:
```
<input a>
<input b onclick="...">
```
When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so `document.getElementsByName` is out. Looking into the event object, I thought `event.target.parentNode` would have some function like `getElementsByName`, but this does not seem to be the case with <td>s. Is there any simple way to do this?
|
If `a` and `b` are next to each other and have the same parent, you can use the `prevSibling` property of `b` to find `a`.
|
1. You should be able to find the element that was clicked from the [event object](http://www.w3schools.com/htmldom/dom_obj_event.asp). Depending on your browser you might want `e.target` or `e.srcElement`. The code below is from this [w3schools example](http://www.w3schools.com/js/tryit.asp?filename=try_dom_event_srcelement):
```
function whichElement(e) {
var targ;
if (!e) var e = window.event;
if (e.target) {
targ=e.target;
} else if (e.srcElement) {
targ = e.srcElement;
}
if (targ.nodeType==3) { // defeat Safari bug
targ = targ.parentNode;
}
var tname;
tname = targ.tagName;
alert("You clicked on a " + tname + " element.");
}
```
2. You may then use the `nextSibling` and `prevSibling` DOM traversal functions. [Some more information here](http://www.newearthonline.co.uk/index.php?page=article&article=284). And yet again a w3schools reference for [XML DOM Nodes](http://www.w3schools.com/DOM/dom_node.asp).
|
Getting closest element by id
|
[
"",
"javascript",
"html",
"dom",
""
] |
Am I correct in assuming that the only difference between "windows files" and "unix files" is the linebreak?
We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format.
I need to automate the translation between unix/windows before the files get delivered to the system in our "transportsystem". I'll probably need something to determine the current format and something to transform it into the other format.
If it's just the newline thats the big difference then I'm considering just reading the files with the java.io. As far as I know, they are able to handle both with readLine. And then just write each line back with
```
while (line = readline)
print(line + NewlineInOtherFormat)
....
```
---
## Summary:
> [samjudson](https://stackoverflow.com/users/1908/samjudson):
>
> > *This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.*
>
> to which [Cebjyre](https://stackoverflow.com/users/1612/cebjyre) elaborates:
>
> > *OS X uses LF, the same as UNIX - MacOS 9 and below did use CR though*
>
> [Mo](https://stackoverflow.com/users/1870/mo)
>
> > *There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.*
>
> [McDowell](https://stackoverflow.com/users/304/mcdowell)
>
> > *In addition to the new-line differences, the byte-order mark can cause problems if files are treated as Unicode on Windows.*
>
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
> > *However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.*
>
> [Sadie](https://stackoverflow.com/users/1000/sadie)
>
> > *On unix, files that start with a . are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.*
> >
> > File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use chown/chmod to make sure the correct users have access to them.
There exists tools to help with the problem:
> [pauldoo](https://stackoverflow.com/users/755/pauldoo)
>
> > *If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like dos2unix, it may be of help here.*
>
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
> > *As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as fromdos or tofrodos, or perhaps even as the general purpose toolbox recode.*
Help for java coding
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
> > *When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain*
|
This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.
Binary files there should be no difference (i.e. a JPEG on a windows machine will be byte for byte the same as the same JPEG on a unix box.)
|
There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.
But this could be another source of trouble (apart from the different linebreaks).
What are your problems? The linebreak-related problems can be easily corrected with the programs dos2unix or unix2dos on the unix-machine
|
Differences between unix and windows files
|
[
"",
"java",
"windows",
"unix",
"file",
""
] |
I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.
I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?
(I really want the Cursor Position on that line, not 'column', per se)
|
```
int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);
int column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);
```
|
```
textBox.SelectionStart -
textBox.GetFirstCharIndexFromLine(textBox.GetLineFromCharIndex(textBox.SelectionStart))
```
|
How can I get Column number of the cursor in a TextBox in C#?
|
[
"",
"c#",
"windows",
"user-interface",
""
] |
I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:
```
<p>
<bean:message key="alert" />
</p>
```
and the properties files look like:
```
messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
```
with the appropriate translations in N other languages (messages\_fr.properties, etc).
Problems:
1. ***DRY violation*** - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.
2. ***Mixed concerns*** - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).
3. ***Post-translation markup*** - Anytime I receive newly-translated text, I must decide what to surround with the `<a>...</a>` markup. Easy for English but less so for unfamiliar languages.
I've considered adding placeholders in the messages file, like:
```
alert=Please update your {0} and {1}.
```
but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.
What can I do to improve this?
|
> Avoid creating links within long
> blocks of text. Prefer shorter text
> that can act as a logically complete
> and independent link.
Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to accommodate the UI.
Any time a developer manually manipulates post-translation strings is a source of potentially expensive bugs. Cutting/pasting or string editing can result in character corruption, misplaced strings, etc. A translation defect needs the participation of outside parties to fix which involves cost and takes time.
Thinking on it, something like this might be less ugly:
```
<p>Please update your address and contact information.
<br />
<a href="/address.do">update address</a>
<br />
<a href="/contact.do">update contact information</a></p>
```
...but I'm no UI designer.
|
One approach that comes to mind is that you could store the translated replacement parameters i.e. "address" and "contact information" in a separate properties file, one per locale. Then have your Action class (or probably some helper class) look up the values from the correct ResourceBundle for the current locale and pass them to the message tag.
|
How can I refactor HTML markup out of my property files?
|
[
"",
"java",
"jsp",
"internationalization",
"struts",
""
] |
I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?
I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals.
|
I solved this by writing a SQLCLR-procedure as Eric Z Beard suggested. The assembly must be signed with a strong name key file.
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static int Debug(string s)
{
System.Diagnostics.Debug.WriteLine(s);
return 0;
}
}
}
```
Created a key and a login:
```
USE [master]
CREATE ASYMMETRIC KEY DebugProcKey FROM EXECUTABLE FILE =
'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll'
CREATE LOGIN DebugProcLogin FROM ASYMMETRIC KEY DebugProcKey
GRANT UNSAFE ASSEMBLY TO DebugProcLogin
```
Imported it into SQL Server:
```
USE [mydb]
CREATE ASSEMBLY SqlServerProject1 FROM
'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll'
WITH PERMISSION_SET = unsafe
CREATE FUNCTION dbo.Debug( @message as nvarchar(200) )
RETURNS int
AS EXTERNAL NAME SqlServerProject1.[StoredProcedures].Debug
```
Then I was able to log in T-SQL procedures using
```
exec Debug @message = 'Hello World'
```
|
I think writing to a log table would be my preference.
Alternatively, as you are using 2005, you could write a simple SQLCLR procedure to wrap around the EventLog.
Or you could use **xp\_logevent** if you wanted to write to SQL log
|
How to log in T-SQL
|
[
"",
"sql-server",
"t-sql",
"logging",
"ado.net",
"sql",
""
] |
I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
```
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
```
This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C\* library (In the case of GTK, Tk, wx, QT etc etc)
Shoes takes things from web devlopment (like `#f0c2f0` style colour notation, CSS layout techniques, like `:margin => 10`), and from ruby (extensively using blocks in sensible ways)
Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:
```
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
```
No where near as clean, and wouldn't be *nearly* as flexible, and I'm not even sure if it would be implementable.
Using decorators seems like an interesting way to map blocks of code to a specific action:
```
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
```
Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.
The scope of various stuff (say, the `la` label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..
|
You could actually pull this off, but it would require using metaclasses, which are *deep* magic (there be dragons). If you want an intro to metaclasses, there's a series of [articles from IBM](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which manage to introduce the ideas without melting your brain.
The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.
|
This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new "with" statement.
```
with Shoes():
t = Para("Not clicked!")
with Button("The Label"):
Alert("You clicked the button!")
t.replace("Clicked!")
```
The hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...
Anyway, here's the backend code I ran this with:
```
context = None
class Nestable(object):
def __init__(self,caption=None):
self.caption = caption
self.things = []
global context
if context:
context.add(self)
def __enter__(self):
global context
self.parent = context
context = self
def __exit__(self, type, value, traceback):
global context
context = self.parent
def add(self,thing):
self.things.append(thing)
print "Adding a %s to %s" % (thing,self)
def __str__(self):
return "%s(%s)" % (self.__class__.__name__, self.caption)
class Shoes(Nestable):
pass
class Button(Nestable):
pass
class Alert(Nestable):
pass
class Para(Nestable):
def replace(self,caption):
Command(self,"replace",caption)
class Command(Nestable):
def __init__(self, target, command, caption):
self.command = command
self.target = target
Nestable.__init__(self,caption)
def __str__(self):
return "Command(%s text of %s with \"%s\")" % (self.command, self.target, self.caption)
def execute(self):
self.target.caption = self.caption
```
|
How would you design a very "Pythonic" UI framework?
|
[
"",
"python",
"user-interface",
"frameworks",
""
] |
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").
```
byte a = 23;
byte b = 34;
byte c = a + b;
```
In this example, the compile error is on the third line.
|
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.
To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.
```
byte a = 23;
byte b = 34;
byte c = (byte) (a + b);
```
Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)
Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.
|
The answer to your follow-up question is here:
> operands of type byte and short are automatically promoted to int before being handed to the operators
So, in your example, `a` and `b` are both converted to an `int` before being handed to the + operator. The result of adding two `int`s together is also an `int`. Trying to then assign that `int` to a `byte` value causes the error because there is a potential loss of precision. By explicitly casting the result you are telling the compiler "I know what I am doing".
|
Java: why do I receive the error message "Type mismatch: cannot convert int to byte"
|
[
"",
"java",
"type-conversion",
"byte",
"type-mismatch",
""
] |
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in \*nix anyway so I'm not worried about it being cross platform.
my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.
**edit**: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?
## Here are a few useful links
* [Ubuntu Python Packaging Guide](https://wiki.ubuntu.com/PackagingGuide/Python)
This Guide is ***very*** helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application
* [The Ubuntu MOTU Project](https://wiki.ubuntu.com/MOTU/GettingStarted)
This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.
* ["Python distutils to deb?" - Ars Technica Forum discussion](http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931)
According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh\_make as seen in the Ubuntu Packaging guide
* ["A bdist\_deb command for distutils](http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html)
This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.
* [Description of the deb format and how distutils fit in - python mailing list](http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html)
|
See the [distutils simple example](http://docs.python.org/dist/simple-example.html). That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same.
Here is a real-life (anonymized) example:
```
#!/usr/bin/python
from distutils.core import setup
setup (name = 'Initech Package 3',
description = "Services and libraries ABC, DEF",
author = "That Guy, Initech Ltd",
author_email = "that.guy@initech.com",
version = '1.0.5',
package_dir = {'Package3' : 'site-packages/Package3'},
packages = ['Package3', 'Package3.Queries'],
data_files = [
('/etc/Package3', ['etc/Package3/ExternalResources.conf'])
])
```
|
`apt-get install python-stdeb`
Python to Debian source package conversion utility
This package provides some tools to produce Debian packages from Python packages via a new distutils command, sdist\_dsc. Automatic defaults are provided for the Debian package, but many aspects of the resulting package can be customized via a configuration file.
* pypi-install will query the Python Package Index (PyPI) for a
package, download it, create a .deb from it, and then install
the .deb.
* py2dsc will convert a distutils-built source tarball into a Debian
source package.
|
How to use Python distutils?
|
[
"",
"python",
"linux",
"installation",
"debian",
"distutils",
""
] |
Can anyone provide a good explanation of the [`volatile`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile) keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?
|
I don't think there's a better person to answer this than [Eric Lippert](https://ericlippert.com/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/) (emphasis in the original):
> In C#, "volatile" means not only "make sure that the compiler and the
> jitter do not perform any code reordering or register caching
> optimizations on this variable". It also means "tell the processors to
> do whatever it is they need to do to ensure that I am reading the
> latest value, even if that means halting other processors and making
> them synchronize main memory with their caches".
>
> Actually, that last bit is a lie. The true semantics of volatile reads
> and writes are considerably more complex than I've outlined here; in
> fact **they do not actually guarantee that every processor stops what it
> is doing** and updates caches to/from main memory. Rather, **they provide
> weaker guarantees about how memory accesses before and after reads and
> writes may be observed to be ordered with respect to each other**.
> Certain operations such as creating a new thread, entering a lock, or
> using one of the Interlocked family of methods introduce stronger
> guarantees about observation of ordering. If you want more details,
> read sections 3.10 and 10.5.3 of the C# 4.0 specification.
>
> Frankly, **I discourage you from ever making a volatile field**. Volatile
> fields are a sign that you are doing something downright crazy: you're
> attempting to read and write the same value on two different threads
> without putting a lock in place. Locks guarantee that memory read or
> modified inside the lock is observed to be consistent, locks guarantee
> that only one thread accesses a given chunk of memory at a time, and so
> on. The number of situations in which a lock is too slow is very
> small, and the probability that you are going to get the code wrong
> because you don't understand the exact memory model is very large. I
> don't attempt to write any low-lock code except for the most trivial
> usages of Interlocked operations. I leave the usage of "volatile" to
> real experts.
For further reading see:
* [Understand the Impact of Low-Lock Techniques in Multithreaded Apps](https://learn.microsoft.com/archive/msdn-magazine/2005/october/understanding-low-lock-techniques-in-multithreaded-apps)
* [Sayonara volatile](http://joeduffyblog.com/2010/12/04/sayonara-volatile/)
|
If you want to get slightly more technical about what the volatile keyword does, consider the following program (I'm using DevStudio 2005):
```
#include <iostream>
void main()
{
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
j += i;
}
for (volatile int i = 0 ; i < 100 ; ++i)
{
j += i;
}
std::cout << j;
}
```
Using the standard optimised (release) compiler settings, the compiler creates the following assembler (IA32):
```
void main()
{
00401000 push ecx
int j = 0;
00401001 xor ecx,ecx
for (int i = 0 ; i < 100 ; ++i)
00401003 xor eax,eax
00401005 mov edx,1
0040100A lea ebx,[ebx]
{
j += i;
00401010 add ecx,eax
00401012 add eax,edx
00401014 cmp eax,64h
00401017 jl main+10h (401010h)
}
for (volatile int i = 0 ; i < 100 ; ++i)
00401019 mov dword ptr [esp],0
00401020 mov eax,dword ptr [esp]
00401023 cmp eax,64h
00401026 jge main+3Eh (40103Eh)
00401028 jmp main+30h (401030h)
0040102A lea ebx,[ebx]
{
j += i;
00401030 add ecx,dword ptr [esp]
00401033 add dword ptr [esp],edx
00401036 mov eax,dword ptr [esp]
00401039 cmp eax,64h
0040103C jl main+30h (401030h)
}
std::cout << j;
0040103E push ecx
0040103F mov ecx,dword ptr [__imp_std::cout (40203Ch)]
00401045 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (402038h)]
}
0040104B xor eax,eax
0040104D pop ecx
0040104E ret
```
Looking at the output, the compiler has decided to use the ecx register to store the value of the j variable. For the non-volatile loop (the first) the compiler has assigned i to the eax register. Fairly straightforward. There are a couple of interesting bits though - the lea ebx,[ebx] instruction is effectively a multibyte nop instruction so that the loop jumps to a 16 byte aligned memory address. The other is the use of edx to increment the loop counter instead of using an inc eax instruction. The add reg,reg instruction has lower latency on a few IA32 cores compared to the inc reg instruction, but never has higher latency.
Now for the loop with the volatile loop counter. The counter is stored at [esp] and the volatile keyword tells the compiler the value should always be read from/written to memory and never assigned to a register. The compiler even goes so far as to not do a load/increment/store as three distinct steps (load eax, inc eax, save eax) when updating the counter value, instead the memory is directly modified in a single instruction (an add mem,reg). The way the code has been created ensures the value of the loop counter is always up-to-date within the context of a single CPU core. No operation on the data can result in corruption or data loss (hence not using the load/inc/store since the value can change during the inc thus being lost on the store). Since interrupts can only be serviced once the current instruction has completed, the data can never be corrupted, even with unaligned memory.
Once you introduce a second CPU to the system, the volatile keyword won't guard against the data being updated by another CPU at the same time. In the above example, you would need the data to be unaligned to get a potential corruption. The volatile keyword won't prevent potential corruption if the data cannot be handled atomically, for example, if the loop counter was of type long long (64 bits) then it would require two 32 bit operations to update the value, in the middle of which an interrupt can occur and change the data.
So, the volatile keyword is only good for aligned data which is less than or equal to the size of the native registers such that operations are always atomic.
The volatile keyword was conceived to be used with IO operations where the IO would be constantly changing but had a constant address, such as a memory mapped UART device, and the compiler shouldn't keep reusing the first value read from the address.
If you're handling large data or have multiple CPUs then you'll need a higher level (OS) locking system to handle the data access properly.
|
When should the volatile keyword be used in C#?
|
[
"",
"c#",
"multithreading",
"volatile",
"lock-free",
""
] |
I want to be able to generate PDF output from my (native) C++ Windows application. Are there any free/open source libraries available to do this?
I looked at the answers to [this question](https://stackoverflow.com/questions/177/how-do-i-programmatically-create-a-pdf-in-my-net-application), but they mostly relate to .Net.
|
[LibHaru](https://github.com/libharu/libharu)
> Haru is a free, cross platform,
> open-sourced software library for
> generating PDF written in ANSI-C. It
> can work as both a static-library (.a,
> .lib) and a shared-library (.so,
> .dll).
Didn't try it myself, but maybe it can help you
|
I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:
<http://podofo.sourceforge.net/>
Enjoy!
|
Open source PDF library for C/C++ application?
|
[
"",
"c++",
"c",
"pdf",
"open-source",
""
] |
I'm trying to use some data from a PlanPlusOnline account. They only provide a java web services API. The server for the site where the data will be used does not allow me to install Tomcat (edit: or a JVM for that matter). I'm not going to lie, I am a Java software engineer, and I do some web work on the side. I'm not familiar with web services or servlets, but I was willing to give it a shot. I'd much rather they have JSON access to the data, but as far as I know they don't. Any ideas?
EDIT: to clarify. The web service provided by planplusonline is Java based. I am trying to access the data from this web service without using Java. I believe this is possible now, but I need to do more research. Anyone who can help point me in the right direction is appreciated.
|
To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure out how to traverse the XML returned. If you can't do Java, then I suggest PHP because it could be already installed, and have the proper modules loaded. This link might be helpful:
<http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html>
|
Are you trying to implement a client to a web service hosted somewhere else? If so, Java's not necessary. You can do web service clients in [.NET](http://www.dotnetjunkies.ddj.com/Tutorial/4D13CEFA-D0FD-44BE-8749-8D17B5757564.dcik), [PHP](http://sourceforge.net/projects/nusoap/), [Ruby](http://raa.ruby-lang.org/project/soap4r), or pretty much any modern web technology out there. All you need is a WSDL document to provide metadata about how to invoke the services.
|
Java Web Services API, however I can't run a JVM on my server
|
[
"",
"java",
"json",
"web-services",
""
] |
We have a situation in our product where for a long time some data has been stored in the application's database as SQL string (choice of MS SQL server or sybase SQL anywhere) which was encrypted via the Windows API function [CryptEncrypt.](http://msdn.microsoft.com/en-us/library/aa379924.aspx) (direct and de-cryptable)
The problem is that CryptEncrypt can produce NULL's in the output, meaning that when it's stored in the database, the string manipulations will at some point truncate the CipherText.
Ideally we'd like to use an algo that will produce CipherText that doesn't contain NULLs as that will cause the least amount of change to the existing databases (changing a column from string to binary and code to deal with binary instead of strings) and just decrypt existing data and re-encrypt with the new algorithm at database upgrade time.
The algorithm doesn't need to be the most secure, as the database is already in a reasonably secure environment (not an open network / the inter-webs) but does need to be better than ROT13 (which I can almost decrypt in my head now!)
edit: btw, any particular reason for changing ciphertext to cyphertext? ciphertext seems more widely used...
|
Any semi-decent algorithm will end up with a strong chance of generating a NULL value somewhere in the resulting ciphertext.
Why not do something like [base-64 encode](http://en.wikipedia.org/wiki/Base64) your resulting binary blob before persisting to the DB? ([sample implementation in C++](http://synesis.com.au/software/b64.html)).
|
Storing a hash is a good idea. However, please definitely read Jeff's [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/archives/000953.html).
|
Suitable alternative to CryptEncrypt
|
[
"",
"c++",
"encryption",
"winapi",
""
] |
I am thinking of using a PHP framework called [CodeIgniter](http://codeigniter.com/).
One of the things I am interested in is its speed. I have, however, no way to find out how fast it is, and would rather not simply take the word of their website for it. Does anybody know how I can determine its speed myself, or can someone tell me of a site that can?
|
Code Igniter also has some built-in benchmarking tools:
<http://codeigniter.com/user_guide/general/profiling.html>
|
Yes, the problem is you have to build your application to profile it.
At work we had a couple of projects written outside which we load-tested before putting them on our main boxes. We were quite surprised to find critical performance problems with both; one was written in CakePHP and the other was written using Drupal. I don't think this highlights a problem with any framework or CMS other than the need to do profiling and load-testing on any site which is going to get significant traffic. In both cases it was what the developer had done, rather than the characteristics of the software platform, that caused the problem. For example, there was a recursive function call the developer had created in the Cake project which instantiated the entire Cake object every recursion and this would have taken out the server had it gone live under load.
In my opinion performance should not be a deciding factor in choosing a framework; the objective differences are likely to be marginal and the way you use it is likely to cause far more performance problems than the inherent performance of the framework.
I believe that to scale any PHP application to run under load, you will need an opcode cache and you'll need to write in intelligent content caching using something like memcached or whatever built-in caching your framework supports.
|
How can I determine CodeIgniter speed?
|
[
"",
"php",
"performance",
"codeigniter",
"benchmarking",
""
] |
I want to copy the entire contents of a directory from one location to another in C#.
There doesn't appear to be a way to do this using `System.IO` classes without lots of recursion.
There is a method in VB that we can use if we add a reference to `Microsoft.VisualBasic`:
```
new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
```
This seems like a rather ugly hack. Is there a better way?
|
Much easier
```
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}
```
|
Hmm, I think I misunderstand the question but I'm going to risk it. What's wrong with the following straightforward method?
```
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
```
**EDIT** Since this posting has garnered an impressive number of downvotes for such a simple answer to an equally simple question, let me add an explanation. **Please** *read this before downvoting*.
First of all, **this code is not intendend as a drop-in replacement** to the code in the question. It is for illustration purpose only.
`Microsoft.VisualBasic.Devices.Computer.FileSystem.CopyDirectory` does some additional correctness tests (e.g. whether the source and target are valid directories, whether the source is a parent of the target etc.) that are missing from this answer. That code is probably also more optimized.
That said, the code *works well*. It *has* (almost identically) been used in a mature software for years. Apart from the inherent fickleness present with all IO handlings (e.g. what happens if the user manually unplugs the USB drive while your code is writing to it?), there are no known problems.
In particular, I’d like to point out that the use of recursion here is absolutely not a problem. Neither in theory (conceptually, it’s the most elegant solution) nor in practice: *this code will not overflow the stack*. The stack is large enough to handle even deeply nested file hierarchies. Long before stack space becomes a problem, the folder path length limitation kicks in.
Notice that a *malicious user* might be able to break this assumption by using deeply-nested directories of one letter each. I haven’t tried this. But just to illustrate the point: in order to make this code overflow on a typical computer, the directories would have to be nested a few *thousand* times. This is simply not a realistic scenario.
|
Copy the entire contents of a directory in C#
|
[
"",
"c#",
".net",
"directory",
"copy",
""
] |
I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?
I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?
|
As Google Web Toolkit is a [subset of Java](http://code.google.com/support/bin/answer.py?answer=54830&topic=10208) it works best when you Java at the backend too. Since Google App Engine is currently [Python only](http://code.google.com/appengine/kb/general.html#language) I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.
jQuery seems to be the most popular JavaScript library option in the [AJAX Tag at DjangoSnippets.com](http://www.djangosnippets.org/tags/ajax/?page=1).
**Edit:** The above is only true of Google App Engine applications written in Python. As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end. [Google even have a tutorial showing you how to do it.](http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html)
|
A nice way is to use an AJAX library is to take advantage of [Google's AJAX Libraries API service](http://code.google.com/apis/ajaxlibs/). This is a bit faster and cleaner than downloading the JS and putting it in your `/static/` folder and doesn't eat into your disk quota.
In your javascript you would just put, for example:
```
google.load("jquery", "1.3.2");
```
and/or
```
google.load(google.load("dojo", "1.3.0");
```
Somewhere in your header you would put something like:
```
<script src="http://www.google.com/jsapi?key=your-key-here"></script>
```
And that's all you need to use Google's API libraries.
|
Any good AJAX framework for Google App Engine apps?
|
[
"",
"python",
"ajax",
"google-app-engine",
""
] |
Which parsers are available for parsing C# code?
I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.
|
Works on source code:
* [CSParser](http://www.codeplex.com/csparser):
From C# 1.0 to 2.0, open-source
* [Metaspec C# Parser](http://www.csharpparser.com/csparser.php):
From C# 1.0 to 3.0, commercial product (about 5000$)
* [#recognize!](http://www.sharprecognize.com/):
From C# 1.0 to 3.0, commercial product (about 900€) (answer by [SharpRecognize](https://stackoverflow.com/questions/81406/parser-for-c#185380))
* [SharpDevelop Parser](http://www.icsharpcode.net/OpenSource/SD/) (answer by [Akselsson](https://stackoverflow.com/questions/81406/parser-for-c#81434))
* [NRefactory](https://github.com/icsharpcode/NRefactory/):
From C# 1.0 to 4.0 (+async), open-source, parser used in SharpDevelop. Includes semantic analysis.
* [C# Parser and CodeDOM](http://www.inevitablesoftware.com/Products.aspx):
A complete C# 4.0 Parser, already support the C# 5.0 async feature. Commercial product (49$ to 299$) (answer by [Ken Beckett](https://stackoverflow.com/questions/81406/parser-for-c/7631455#7631455))
* [Microsoft Roslyn CTP](http://msdn.microsoft.com/en-us/roslyn):
Compiler as a service.
Works on assembly:
* System.Reflection
* [Microsoft Common Compiler Infrastructure](http://ccimetadata.codeplex.com/):
From C# 1.0 to 3.0, Microsoft Public License. Used by [Fxcop](http://www.microsoft.com/downloads/details.aspx?FamilyID=9aeaa970-f281-4fb0-aba1-d59d7ed09772&displaylang=en) and [Spec#](http://research.microsoft.com/en-us/projects/specsharp/)
* [Mono.Cecil](http://www.mono-project.com/Cecil):
From C# 1.0 to 3.0, open-source
The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods)
I personnaly recommend **Mono.Cecil** and **NRefactory**.
|
[Mono](http://www.mono-project.com/) (open source) includes C# compiler (and of course parser)
|
Which parsers are available for parsing C# code?
|
[
"",
"c#",
"parsing",
""
] |
I've got a [site](http://notebooks.readerville.com/) that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?
|
you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here's a classic ones to try:
put the javascript in a weird place, like anywhere that executes a URL. for instance:
```
<div style="background:url('javascript:alert(this);');" />
```
sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\nscript, or something similar.
sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters.
sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.
|
From the official [WordPress.com FAQ](http://faq.wordpress.com/2006/05/07/javascript-can-i-use-that-on-my-blog/):
> Javascript can be used for malicious purposes and while what you want to do is okay it does not mean all javascript will be okay.
It goes on to remind the reader that both MySpace and LiveJournal had been affected by malicious Javascript and, therefore, will not be permitted (as it may be exploited by users with poor intentions). They can't risk it with amazingly large sites (think I Can Has Cheezburger, Anderson Cooper 360, Fox, etc.).
If you think you have Javascript that would benefit WordPress.com you can [contact them directly](http://wordpress.com/contact-support/).
|
How do you add a JavaScript widget to a Wordpress.com hosted blog?
|
[
"",
"javascript",
"wordpress",
"widget",
""
] |
I have a UserControl that consists of three TextBoxes. On a form I can have one or more or my UserControl. I want to implement my own tab behavior so if the user presses Tab in the second TextBox I should only move to the third TextBox if the the second TextBox has anything entered. If nothing is entered in the second TextBox the next control of the form should get focus as per the normal tab behavior. If the user hasn't entered anything in the first or second TextBox and the presses tab there is this special case where a control on the form should be skipped.
By using the ProcessDialogKey I have managed to get it work kind of ok but I still have one problem. My question is if there is a way to detect how a WinForms control got focus since I would also like to know if the my UserControl got focus from a Tab or Shift-Tab and then do my weird stuff but if the user clicks the control I don't want to do anything special.
|
As a general rule, I would say overriding the standard behavior of the TAB key would be a bad idea. Maybe you can do something like disabling the 3rd text box until a valid entry is made in the 2nd text box.
*Now, having said this, I've also broken this rule at the request of the customer. We made the enter key function like the tab key, where the enter key would save the value in a text field, and advance the cursor to the next field.*
|
The reason for this odd tab behavior is all about speed in the input process. It was really good to get some input, I hadn't thought about disabling a textbox but that could actually work. But using the Enter key to accept the input hadn't even crossed my mind. That will work so much better. The user can enter the numbers and then press enter to accept the input and the next possible textbox will be the active one. It's like having the cake and eating it too, The speed factor is there since when using the enter key no unnecessary tabing must be done to get to the correct field and using the enter key next to the numeric keyboard makes it really smooth.
Thanks for the input!
|
Override tab behavior in WinForms
|
[
"",
"c#",
".net",
"winforms",
""
] |
here is what a I'm doing:
```
object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
```
However, if obj is a subclass of `type`, it will not match. But I would like the function to return the same way as if I was using the operator `is`.
I tried the following, but it won't compile:
```
if (obj is type) // won't compile in C# 2.0
```
The best solution I came up with was:
```
if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
```
Isn't there a way to use operator `is` to make the code cleaner?
|
I've used the IsAssignableFrom method when faced with this problem.
```
Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
if (theTypeWeWant.IsAssignableFrom(o.GetType))
return o;
}
```
Another approach that may or may not work with your problem is to use a generic method:
```
private T FindObjectOfType<T>() where T: class
{
foreach(object o in myCollection)
{
if (o is T)
return (T) o;
}
return null;
}
```
(Code written from memory and is not tested)
|
Not using the is operator, but the Type.IsInstanceOfType Method appears to be what you're looking for.
<http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx>
|
How to use the "is" operator in System.Type variables?
|
[
"",
"c#",
""
] |
I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.
So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):
```
$("#thediv").scrollTop = $("#thediv").scrollHeight;
```
However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.
The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.
Any ideas guys? This one's got me stumped. Thanks!
|
`scrollHeight` should be the total height of content. `scrollTop` specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
```
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
```
...which will set the scroll offset to the last `clientHeight` worth of content.
|
[`scrollIntoView`](https://developer.mozilla.org/en/DOM/element.scrollIntoView)
> The **scrollIntoView** method scrolls the element into view.
|
Scrolling Overflowed DIVs with JavaScript
|
[
"",
"javascript",
"jquery",
"ajax",
"html",
"scroll",
""
] |
I'm working with a team that's building an engine for a variety of 2D and eventually 3D mini-games. The problem we're facing is a solid, cross-platform, sound API. Obviously, DirectX is out of the question due to our needs for cross-platform capabilities. SDL is nice, and works great, but let's face it SDL\_Mixer is a bit limited in what it can do. We're currently using it, but when we eventually expand to 3D, it's going to be a problem.
I've been messing with OpenAL, but most of the documentation I've found is fairly out of date, and doesn't seem to work all that great. I'm willing to learn OpenAL, and fight my way through it, but I'd like to be a bit more certain that I'm not wasting my time. Other than the DevMaster tutorials though, I haven't seen much documentation that's blown me away. If someone has some better material than I've found, that'd be awesome.
I've also seen projects such as FMOD, which seems decent despite the licensing. However, like OpenAL, they have nearly non-existant documentation. Granted, I can pour over the code to deduce my options, but it seems like a bit of a pain considering I might eventually be paying for it.
Anyways, thoughts, comments, concerns? Thanks a lot!
|
*(note: I have experience with FMOD, BASS, OpenAL and DirectSound; and while I list other libraries below, I haven't used them).*
[BASS](http://www.un4seen.com/) and [FMOD](http://www.fmod.org/) are both good (and actually I liked FMOD's documentation a lot; why would you say it's "non existing"?). There are also [Miles Sound System](http://www.radgametools.com/miles.htm), [Wwise](http://www.audiokinetic.com/), [irrKlang](http://www.ambiera.com/irrklang/) and some more middleware packages.
OpenAL is supposedly cross platform, and on each platform it has it's own quirks. It's not exactly "open", either. And I'm not sure what is the future for it; it seems like it got stuck when Creative got hold of it. There's a recent effort to built the implementation from ground up, though: [OpenAL Soft](http://kcat.strangesoft.net/openal.html).
Then there are native platform APIs, like DirectSound or XAudio2 for Windows, Core Audio for OS X, ALSA for Linux, proprietary APIs for consoles etc. I think using native APIs on each platform makes a lot of sense; you just abstract it under common interface that you need, and have different implementations on each platform. Sure, it's more work than just using OpenAL, but OpenAL is not even available on some platforms, and has various quirks on other platforms that you can't even fix (because there's no source code you can fix). Licensing a commercial library like FMOD or Miles is an option in a sense that all this platform dependent work is already done for you.
We're using OpenAL at work right now, but are considering switching away from it, because it's just not going anywhere and we can't fix the quirks. So while OpenAL is easy to get started, it does not get my vote as a good option.
|
I have used DirectX, FMOD and Wwise on a range of platforms in shipped games. I won't talk about DirectX here since other people will have plenty of feedback here ;-)
Here's what you need to consider:
* License, I put this first because this may make your decision for you. Have your lawyer go over them and make sure you understand the costing and restrictions.
* API - FMOD has a very clean, minimal API that is very easy to grok. Wwise offers a little more in terms of functionality, but its API seems much larger and cumbersome with awkward concepts to get your head around.
* Tools - Wwise has very sophisticated tools, geared very much towards audio-designers rather than programmers, if you want to give audio designers a lot of direct control and room for experimentation, Wwise may be the way to go. FMOD is catching up in the tool department but its tools are more geared towards programmers I feel.
* Performance - This is something you'll need to evaluate for yourself, you can't say any one is better than the other because it depends on your platform and type of game. You may get performance statistics quoted to you - take these with a grain of salt, they may well be idealised in some fashion. Determine your performance budget (eg 2 ms per frame for sound, X number of channels, X number of streams) and do a bunch of tests for different sound formats, sample rates and bit depths - graph those suckers.
* Support - Both FMOD and Wwise have very good support channels, good tech guys. Check if support costs extra though.
If you're asking me to pick one.. FMOD - it really is a very good product, those guys do a great job.
|
Game Development Sound Frameworks
|
[
"",
"c++",
"openal",
"audio",
""
] |
I'm trying to use the following code but it's returning the wrong day of month.
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
```
|
Get the number of days for this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
```
Set the Calendar to the last day of this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
```
|
I would create a date object for the first day of the NEXT month, and then just subtract a single day from the date object.
|
Given a Date Object how do I determine the last day of its month?
|
[
"",
"java",
"date",
""
] |
When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in.
It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie?
Should I add `mysql_real_escape_string` (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?
|
What you *really* need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.:
```
define('COOKIE_SALT', 'secretblahblahlkdsfklj');
$cookie_value = sha1($username.$password.COOKIE_SALT);
```
Then you know the cookie value is always going to be a 40-character hexidecimal string, and can compare the value the user sends back with whatever's in the database to decide whether they're valid or not:
```
if ($user_cookie_value == sha1($username_from_db.$password_drom_db.COOKIE_SALT)) {
# valid
} else {
#not valid
}
```
`mysql_real_escape_string` makes an additional hit to the database, BTW (a lot of people don't realize it requires a DB connection and queries MySQL).
The best way to do what you want if you can't change your app and insist on using hackable cookie values is to use [prepared statements with bound parameters](http://devzone.zend.com/node/view/id/686).
|
The point of mysql\_real\_escape\_string isn't to protect against injection attacks, it's to ensure your data is accurately stored in the database. Thus, it should be called on ANY string going into the database, regardless of its source.
You should, however, *also* be using parameterized queries (via mysqli or PDO) to protect yourself from SQL injection. Otherwise you risk ending up like [little Bobby Tables' school](http://xkcd.com/327/).
|
Should I mysql_real_escape_string all the cookies I get from the user to avoid mysql injection in php?
|
[
"",
"php",
"validation",
""
] |
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:
```
result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`
```
After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:
```
regex = ".*(a_regex_of_pure_awesomeness)"
```
into
```
regex = "a_regex_of_pure_awesomeness"
```
Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.
|
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.
[Python regex docs](http://docs.python.org/lib/module-re.html)
[Matching vs searching](http://docs.python.org/lib/matching-searching.html)
|
```
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(your_html)
for a in soup.findAll('a', href=True):
# do something with `a` w/ href attribute
print a['href']
```
|
Python and "re"
|
[
"",
"python",
"regex",
""
] |
Is it possible to use an **IF** clause within a **WHERE** clause in MS SQL?
Example:
```
WHERE
IF IsNumeric(@OrderNumber) = 1
OrderNumber = @OrderNumber
ELSE
OrderNumber LIKE '%' + @OrderNumber + '%'
```
|
Use a [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx) statement
**UPDATE:** The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:
```
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber) = 1 THEN
@OrderNumber
ELSE
'%' + @OrderNumber
END
```
Or you can use an IF statement like @[N. J. Reed](https://stackoverflow.com/questions/87821/sql-if-clause-within-where-clause#87992) points out.
|
You should be able to do this without any IF or CASE
```
WHERE
(IsNumeric(@OrderNumber) AND
(CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)
OR
(NOT IsNumeric(@OrderNumber) AND
OrderNumber LIKE ('%' + @OrderNumber))
```
Depending on the flavour of SQL you may need to tweak the casts on the order number to an INT or VARCHAR depending on whether implicit casts are supported.
This is a very common technique in a WHERE clause. If you want to apply some "IF" logic in the WHERE clause all you need to do is add the extra condition with an boolean AND to the section where it needs to be applied.
|
SQL: IF clause within WHERE clause
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?
|
Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it.
```
<target name="build.application">
<exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true">
<arg value="${Application.Compiler.Directive}" />
<arg value="-Q" />
<arg value="/B" />
<arg value="/E${Application.Output.Folder}" />
<arg value="/U${Application.Lib.Folder};${Application.Search.Folder}" />
<arg value="${Application.Folder}\${Delphi.Project}" />
</exec>
</target>
```
|
You need to write your own task. [This](http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-custom-nant-tasks.aspx) is a nice reference.
|
How do I use my own compiler with Nant?
|
[
"",
"c++",
"build",
"cross-platform",
"makefile",
"nant",
""
] |
I've kind of backed myself into a corner here.
I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls.
What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me *always* results in a bug).
Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, *that's the point*. I *want* to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input.
I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?
|
Declare the parent method virtual, override it in the child classes and call
```
base.checkReadyness(sender, e);
```
(or derevation thereof) from within the child class. This allows for future design evolution say if you want to do some specific error checking code before calling the parent event handler. You might not need to write millions of event handlers like this for each control, you could just write one, hook all the controls to this event handler which in turn calls the parent's event handler.
One thing that I have noted is that if all this code is being placed within a dll, then you might experience a performance hit trying to call an event handler from within a dll.
|
I've just come across this one as well, I agree that it feels like you're doing everything correctly. Declaring the method virtual is a work-around at best, not a solution.
What is being done is valid - a control which only exists in the derived class, and the derived class is attaching an event handler to one of that control's events. The fact that the method which is handling the event is defined in the base class is neither here nor there, it is available at the point of binding to the event. The event isn't being attached to twice or anything silly like that, it's simply a matter of where the method which handles the event is defined.
Most definitely it is not a virtual method - I don't want the method to be overridable by a derived class. Very frustrating, and in my opinion, a bug in dev-studio.
|
Inheriting Event Handlers in C#
|
[
"",
"c#",
"events",
"inheritance",
""
] |
How would you design a database to support the following tagging features:
* items can have a large number of tags
* searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search)
* creating/writing items may be slower to enable quick lookup/reading
Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical.
Any ideas?
---
Thanks for all the answers so far.
If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.)
|
About ANDing: It sounds like you are looking for the "relational division" operation. [This article](http://www.dbazine.com/ofinterest/oi-articles/celko1) covers relational division in concise and yet comprehendible way.
About performance: A bitmap-based approach intuitively sounds like it will suit the situation well. However, I'm not convinced it's a good idea to implement bitmap indexing "manually", like digiguru suggests: It sounds like a complicated situation whenever new tags are added(?) But some DBMSes (including Oracle) offer bitmap indexes which may somehow be of use, because a built-in indexing system does away with the potential complexity of index maintenance; additionally, a DBMS offering bitmap indexes should be able to consider them in a proper when when performing the query plan.
|
Here's a good article on tagging Database schemas:
<http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/>
along with performance tests:
<http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/>
Note that the conclusions there are very specific to MySQL, which (at least in 2005 at the time that was written) had very poor full text indexing characteristics.
|
Database Design for Tagging
|
[
"",
"sql",
"database-design",
"tags",
"tagging",
""
] |
In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of optimizations turned on.
Why the difference?
|
Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
```
void foo() {
1: int i;
2: for(i = 0; i < 2; )
3: i++;
4: return;
```
In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4
With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)
Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.
Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.
While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.
Here is a simplistic example:
```` ```
int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device
*ptr = 0; // setup hardware device
while(*ptr == 1) { // loop until hardware device is done
// do something
}
``` ````
With optimization off, this is straightforward, and you kinda know what to expect.
However, if you turn optimization on, a couple of things might happen:
* The compiler might optimize the while block away (we init to 0, it'll never be 1)
* Instead of accessing memory, pointer access might be moved to a register->No I/O Update
* memory access might be cached (not necessarily compiler optimization related)
In all these cases, the behavior would be drastically different and most likely wrong.
|
Another crucial difference between debug and release is how local variables are stored. Conceptually local variables are allocated storage in a functions stack frame. The symbol file generated by the compiler tells the debugger the offset of the variable in the stack frame, so the debugger can show it to you. The debugger peeks at the memory location to do this.
However, this means every time a local variable is changed the generated code for that source line has to write the value back to the correct location on the stack. This is very inefficient due to the memory overhead.
In a release build the compiler may assign a local variable to a register for a portion of a function. In some cases it may not assign stack storage for it at all (the more registers a machine has the easier this is to do).
However, the debugger doesn't know how registers map to local variables for a particular point in the code (I'm not aware of any symbol format that includes this information), so it can't show it to you accurately as it doesn't know where to go looking for it.
Another optimization would be function inlining. In optimized builds the compiler may replace a call to foo() with the actual code for foo everywhere it is used because the function is small enough. However, when you try to set a breakpoint on foo() the debugger wants to know the address of the instructions for foo(), and there is no longer a simple answer to this -- there may be thousands of copies of the foo() code bytes spread over your program. A debug build will guarantee that there is somewhere for you to put the breakpoint.
|
Why does a C/C++ program often have optimization turned off in debug mode?
|
[
"",
"c++",
"c",
"compiler-construction",
""
] |
What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type `IEnumerable<T>` and doesn't have a Count property.
Right now I'm tossing up between this:
```
if (myList.Count() == 0) { ... }
```
and this:
```
if (!myList.Any()) { ... }
```
My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.
That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?
**Edit** @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:
```
public static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
return !list.Any();
}
```
|
You could do this:
```
public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
return true; // or throw an exception
return !source.Any();
}
```
**Edit**: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.
|
I would make one small addition to the code you seem to have settled on: check also for `ICollection`, as this is implemented even by some non-obsolete generic classes as well (i.e., `Queue<T>` and `Stack<T>`). I would also use `as` instead of `is` as it's more idiomatic and [has been shown to be faster](http://www.codeproject.com/KB/cs/csharpcasts.aspx).
```
public static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
var genericCollection = list as ICollection<T>;
if (genericCollection != null)
{
return genericCollection.Count == 0;
}
var nonGenericCollection = list as ICollection;
if (nonGenericCollection != null)
{
return nonGenericCollection.Count == 0;
}
return !list.Any();
}
```
|
Checking if a list is empty with LINQ
|
[
"",
"c#",
".net",
"linq",
"list",
""
] |
Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example.
You get a screenful of stackoverflow questions by requesting `/questions ?sort=newest` page. Next page link leads to `/questions?page=2 &sort=newest`. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!)
Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still.
The best idea I have (apart from storing request history per client) is to use `/questions?answer_id=NNN` format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right?
Is it how it usually done? Or there is a better way?
|
This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upvoted post could have been moved to page 1 or 2.
Only way to do it is to load the complete list in someones session. Please don't...
As already mentioned, let's hope people are used to this by now.
|
Most web sites I've seen don't solve this problem - they show you a page including some content you've already seen.
You might consider that a feature - when you click "next" and see some content you're seen before, it's a signal that you want to go back to the front again because there's some new content.
|
How to provide next page of updated content?
|
[
"",
"sql",
"paging",
""
] |
Any suggestions for good open source asp.net (C#) apps out there which meet as many of the following:?
1. Designed well and multi tiered
2. Clean & commented code
3. Good use of several design patterns
4. Web pages display properly in all common browsers
5. Produces valid html and has good use of css
6. Use of css themes. Prefer usage of css than tables
7. NOT dependent on third party components (grids, menus, trees, ...etc)
8. Has good unit tests
9. Web pages are not simplistic and look professional
10. Uses newer technologies like MVC, LINQ.. (not important)
11. (Anything else that matters which I couldn't think of right now)
|
I would have to agree with [BlogEngine](http://www.dotnetblogengine.net/). It implements a ton of different abilities and common needs in asp.net as well as allowing it to be fully customizable and very easy to understand. It can work with XML or SQL (your choice) and has a huge community behind it.
As for your requests (**bold** means yes):
1. **Designed well and multi tiered**
2. **Clean & commented code**
3. **Good use of several design patterns**
4. **Web pages display properly in all common browsers**
5. **Produces valid html and has good use of css**
6. **Use of css themes. Prefer usage of css than tables**
7. **NOT dependent on third party components (grids, menus, trees, ...etc)** - *kind of, still uses some custom dlls*
8. Has good unit tests - *not sure*
9. **Web pages are not simplistic and look professional** - *yes, and there are TONS of free templates out there*
10. Uses newer technologies like MVC, LINQ.. (not important) - *not yet*
11. (Anything else that matters which I couldn't think of right now) - *a ton more stuff like dynamic rss feeds, dynamic sitemaps, data references, etc.*
There is also a bunch more great open source projects available here: <http://www.asp.net/community/projects/>
I know that [dotNetNuke](http://www.asp.net/downloads/starter-kits/dotnetnuke/) is pretty popular as well, and the [Classified Program](http://www.asp.net/downloads/starter-kits/classifieds/) is pretty easy to use.
|
You should have a look at [SharpArchitecture](http://code.google.com/p/sharp-architecture/) which uses ASP.NET MVC, and which is an open source architecture foundation for web applications.
|
Good asp.net (C#) apps?
|
[
"",
"c#",
"asp.net",
"css",
"design-patterns",
""
] |
How best to make the selected date of an ASP.NET Calendar control available to JavaScript?
Most controls are pretty simple, but the calendar requires more than just a simple *document.getElementById().value*.
|
When you click on a date with the calendar, ASP does a postback, you could always put the SelectedDate value of the calendar control into a hidden field on the page during the OnLoad event of the page or the SelectionChanged event of the Calendar control.
|
I'm using Page.ClientScript.RegisterClientScriptBlock() to put a small script on the page that just declare a variable with the desired value. I was hoping for some a little less... clunky.
|
How best to make the selected date of an ASP.NET Calendar control available to JavaScript?
|
[
"",
"asp.net",
"javascript",
"calendar",
""
] |
*(see [here](https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly) for the problem I'm trying to solve)*
How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.
I have the following in my log4j config:
```
log4j.logger.net.sf.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.net.sf.hibernate.type=DEBUG
log4j.logger.org.hibernate.type=DEBUG
```
Which produces output such as:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
```
However you'll note that it never displays `parameter: 3` which is our clob.
What I would really want is something like:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.type.ClobType) binding 'something' to parameter: 3
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
(org.hibernate.type.ClobType) binding 'something else' to parameter: 3
```
How do I get it to show this in the log?
|
Try using:
```
log4j.logger.net.sf.hibernate=DEBUG
log4j.logger.org.hibernate=DEBUG
```
That's the finest level you'll get. If it does not show the information you want, then it's not possible.
|
Well, it looks like you can't. *(Thanks [Marcio](https://stackoverflow.com/questions/53365/getting-hibernate-to-log-clob-parameters#53419) for the suggestion, but sadly that didn't add anything useful)*
|
Getting hibernate to log clob parameters
|
[
"",
"java",
"oracle",
"hibernate",
""
] |
I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment.
For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java.
The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools.
So, any advice on how to blend in to Java-ME?
|
This [guy here](http://crfdesign.net/programming/top-10-differences-between-java-and-c) had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java:
## Gotcha #10 - Give me my standard output!
To print to the standard output in Java:
```
System.out.println("Hello");
```
## Gotcha #9 - Namespaces == Freedom
In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package *org.test* must be in the folder *org/test*
## Gotcha #8 - What happened to super?
In Java to refer to the superclass you use the reserved word `super` instead of `base`
## Gotcha #7 - Chaining constructors to a base constructor
You don't have this in Java. You have to call the constructor by yourself
## Gotcha #6 - Dagnabit, how do I subclass an existing class?
To subclass a class in Java do this:
```
public class A extends B {
}
```
That means class `A` is a subclass of class `B`. In C# would be `class A : B`
## Gotcha #5 - Why don’t constants remain constant?
To define a constant in Java use the keyword `final` instead of `const`
## Gotcha #4 - Where is `ArrayList`, `Vector` or `Hashtable`?
The most used data structures in java are `HashSet`, `ArrayList` and `HashMap`. They implement `Set`, `List` and `Map`. Of course, there is a bunch more. Read more about collections [here](http://java.sun.com/docs/books/tutorial/collections/index.html)
## Gotcha #3 - Of Accessors and Mutators (Getters and Setters)
You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically.
## Gotcha #2 - Can't I override!?
You don't have to declare a method `virtual` in Java. All methods - except those declared `final` - can be overridden in Java.
## And the #1 gotcha…
In Java the primitive types `int`, `float`, `double`, `char` and `long` are not `Object`s like in C#. All of them have a respective object representation, like `Integer`, `Float`, `Double`, etc.
That's it. Don't forget to see [the original link](http://crfdesign.net/programming/top-10-differences-between-java-and-c), there's a more detailed discussion.
|
Java is not significantly different from C#. On a purely syntactic level, here are some pointers that may get you through the day:
1. In Java you have two families of exceptions: `java.lang.Exception` and everything that derives from it, and `RuntimeException`. This is meaningful because in Java exceptions are *checked*; this means that in order to throw any non-runtime exception you also need to add a `throws` annotation to your method declaration. Consequently, any method using yours will have to catch that exception or declare that *it* also throws the same exception. A lot of exceptions you take for granted, such as `NullPointerException` or `IllegalArgumentException`, in fact derive from `RuntimeException` and you therefore don't need to declare them. Checked exceptions are a point of contention between two disciplines, so I'd recommend you try them out for yourself and see if it helps or annoys you. On a personal level, I think checked exceptions improve code factoring and robustness significantly.
2. Although Java has supported autoboxing for quite a while, there are still quite a few differences between the C# and Java implementations that you should be aware of. Whereas in C# you can interchangeably use `int` as both a value type and reference type, in Java they're literally not the same type: you get the primitive value type `int` and the library reference type `java.lang.Integer`. This manifests in two common ways: you can't use the value types as a generic type parameter (so you'll use `ArrayList<Integer>` instead of `ArrayList<int>`), and the utility methods (such as `parse` or `toString`) are statically implemented in the reference type (so it's not `int a; a.toString();` but rather `int a; Integer.toString( a );`).
3. Java has two distinct types of nested classes, C# only has one. In Java a static class that is not declared with the `static` modifier is called an *inner class*, and has implicit access to the enclosing class's instance. This is an important point because, unlike C#, Java has no concept of delegates, and inner classes are very often use to achieve the same result with relatively little syntactic pain.
4. Generics in Java are implemented in a radically different manner than C#; when generics were developed for Java it was decided that the changes will be purely syntactic with no runtime support, in order to retain backwards compatibility with older VMs. With no direct generics support in the runtime, Java implements generics using a technique called [type erasure](http://download.oracle.com/javase/tutorial/java/generics/erasure.html). There are quite a few disadvantages to type erasure over the C# implementation of generics, but the most important point to take from this is that *parameterized generic types in Java do not have different runtime types*. In other words, after compilation the types `ArrayList<Integer>` and `ArrayList<String>` are *equivalent*. If you work heavily with generics you'll encounter these differences a lot sooner than you'd think.
There are, in my opinion, the three hardest aspects of the language for a C# developer to grok. Other than that there's the development tools and class library.
1. In Java, there is a direct correlation between the package (namespace), class name and file name. Under a common root directory, the classes `com.example.SomeClass` and `org.apache.SomeOtherClass` will literally be found in `com/example/SomeClass.class` and `org/apache/SomeOtherClass.class` respectively. Be wary of trying to define multiple classes in a single Java file (it's possible for private classes, but not recommended), and stick to this directory structure until you're more comfortable with the development environment.
2. In Java you have the concepts of class-path and class-loader which do not easily map to C# (there are rough equivalents which are not in common use by most .NET developers). Classpath tells the Java VM where libraries and classes are to be found (both yours and the system's shared libraries!), and you can think of class loaders as the context in which your types live. Class loaders are used to load types (class files) from various locations (local disk, internet, resource files, whatnot) but also constrain access to those files. For instance, an application server such as Tomcat will have a class loader for each registered application, or context; this means that a static class in application A will not be the same as a static class in application B, even if they have the same name and even if they share the same codebase. AppDomains provide somewhat similar functionality in .NET.
3. The Java class library is similar to the BCL; a lot of the differences are cosmetic, but it's enough to get you running for the documentation (and/or Google) over and over again. Unfortunately I don't think there's anything to do here — you'll just build familiarity with the libraries as you go.
Bottom line: the only way to grok Java is to use it. The learning curve isn't steep, but prepare to be surprised and frustrated quite often over the first two or three months of use.
|
Best way to really grok Java-ME for a C# guy
|
[
"",
"c#",
"blackberry",
"java-me",
"migration",
""
] |
How to center text over an image in a table cell using javascript, css, and/or html?
I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.
ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way
|
you could try putting the images in the background.
```
<table>
<tr>
<td style="background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center">
Here is my text
</td>
</tr>
</table>
```
You'll just need to set the height and width on the cell and that should be it.
|
There's no proper way of doing it in CSS (although there should be). But here's a method that works for me.
CSS:
```
#image1, #image1-text, #image1-container {
overflow: hidden;
height: 100px;
width: 100px;
}
#image1 {
top: -100px;
position: relative;
z-index: -1;
}
#image1-text {
text-align: center;
vertical-align: middle;
display: table-cell;
}
```
HTML:
```
<div id="image1-container">
<img src="image.jpeg" id="image1">
<div id="image1-text">
hello
</div>
</div>
```
The order of `image1` and `image1-text` in the container doesn't matter.
It's a bit of a hack but it works anywhere, not just in a table. It doesn't properly work in IE however. It will display it at the top instead. But it works in FF, Safari and Chrome. Haven't tested in IE8.
A hack for IE7 or less, which will only show 1 line, but it will be centred is to add the following inside the `<head>` tag:
```
<!--[if lte IE 7]>
<style>
#image1-text {
line-height: 100px;
}
</style>
<![endif]-->
```
|
How to center text over an image in a table using javascript, css, and/or html?
|
[
"",
"javascript",
"html",
"css",
""
] |
I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.
|
From what I know, you can fire up the dev server from the command prompt with the following path/syntax:
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]
```
...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code.
Naturally you'll want to adjust that version number to whatever is most recent/desired for you.
|
This is what I used that worked:
```
using System;
using System.Diagnostics;
using System.Web;
...
// settings
string PortNumber = "1162"; // arbitrary unused port #
string LocalHostUrl = string.Format("http://localhost:{0}", PortNumber);
string PhysicalPath = Environment.CurrentDirectory // the path of compiled web app
string VirtualPath = "";
string RootUrl = LocalHostUrl + VirtualPath;
// create a new process to start the ASP.NET Development Server
Process process = new Process();
/// configure the web server
process.StartInfo.FileName = HttpRuntime.ClrInstallDirectory + "WebDev.WebServer.exe";
process.StartInfo.Arguments = string.Format("/port:{0} /path:\"{1}\" /virtual:\"{2}\"", PortNumber, PhysicalPath, VirtualPath);
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
// start the web server
process.Start();
// rest of code...
```
|
How can I programmatically run the ASP.Net Development Server using C#?
|
[
"",
"c#",
"asp.net",
""
] |
anyone have any experience using this?
if so, is it worth while?
|
I just used jdb for the first time yesterday and am really pleased with the results. You see, I program in Eclipse on my laptop, then deploy to a VM to make sure the whole shebang still works. Very occasionaly, I'll have to work on something that gets executed standalone, as a commandline. These things sometimes need debugging.
This has always been a problem, because I don't want to go to the trouble of installing Eclipse on the VM (it's slow enough already!), yet I don't know of an easy way to get it to connect to my commandline-running class before it finishes running.
jdb to the rescue! It works a treat - small and functional, almost to the point where it is bare... this forces you to apply your mind more than you apply the tool (like I said [here](https://stackoverflow.com/questions/91527/debugging-techniques#91584)).
Make sure to print out the reference ([solaris](http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/jdb.html), [windows](http://java.sun.com/javase/6/docs/technotes/tools/windows/jdb.html), [java 1.5](http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/jdb.html) - I think they're all about the same, really) and have your source code open and browsable on your second screen. I hope you have a second screen, or you'll be alt-tabbing a lot.
|
Assume your program is started by the following command:
```
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=<port> <class>
```
You can attach to this process by jdb:
```
jdb -attach <port>
```
In some cases you need to use the following command .
```
jdb -sourcepath \.src -connect com.sun.jdi.SocketAttach:hostname=localhost,port= <port>
```
|
Java jdb remote debugging command line tool
|
[
"",
"java",
"jdb",
""
] |
How to implement a web page that scales when the browser window is resized?
I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized
i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way?
* thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread
* using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution
EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling
|
instead of using in css say "width: 200px", use stuff like "width: 50%"
This makes it use 50% of whatever it's in, so in the case of:
```
<body>
<div style="width:50%">
<!--some stuff-->
</div>
</body>
```
The div will now always take up half the window horizontaly.
|
Unless you have some specific requirement here I'm not sure why JS is needed here. Tabular layouts are the easy (and archaic) way to make fluid layouts in html, but div layouts with css allow for fluid layouts as well, see <http://www.glish.com/css/2.asp>
|
How to implement a web page that scales when the browser window is resized?
|
[
"",
"javascript",
"html",
"css",
"ajax",
""
] |
Does anyone have examples of how to use [DBMS\_APPLICATION\_INFO](http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php) package with JBOSS?
We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS\_APPLICATION\_INFO so I can more easily track which sections of the application is causing database issues.
I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.
Has anyone done this before?
|
yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnection(String datasourceName, String module, String action){
OracleConnection conn=getConnection(datasourceName);
CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setString(1,module);
call.setString(2,action);
call.execute();
finally{
call.close();
}
return new WrappedOracleConnection(conn);
}
```
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
```
public class WrappedOracleConnection extends OracleConnection{
public void close(){
CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setNull(1,Types.VARCHAR);
call.setNull(2,Types.VARCHAR);
call.execute();
finally{
call.close();
}
}
// and you need to implement every other method
//for example
public CallableStatement prepareCall(String command){
return super.prepareCall(command);
}
...
}
```
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).
|
If you are using JBoss, you can use a "valid-connection-checker".
This class is normaly used to check the validity of the Connection.
But, as it will be invoked every time the Connection pool gives the user a Connection, you can use it to set the DBMS\_ APPLICATION \_INFO.
You declare such a class in the oracle-ds.xml like this:
```
<local-tx-datasource>
<jndi-name>jdbc/myDS</jndi-name>
<connection-url>jdbc:oracle:thin:@10.10.1.15:1521:SID</connection-url>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<security-domain>MyEncryptDBPassword</security-domain>
<valid-connection-checker-class-name>test.MyValidConn</valid-connection-checker-class-name>
<metadata>
<type-mapping>Oracle9i</type-mapping>
</metadata>
</local-tx-datasource>
```
Your class must implement the org.jboss.resource.adapter.jdbc.ValidConnectionChecker interface.
If you use Maven, you can include this interface with the following dependency:
```
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-common-jdbc-wrapper</artifactId>
<version>3.2.3</version>
<scope>provided</scope>
</dependency>
```
This interface has only one method: isValidConnection.
I copy my implementation:
```
public SQLException isValidConnection(Connection arg0) {
CallableStatement statement;
try {
statement = arg0.prepareCall("call dbms_application_info.set_client_info('"+getInfos()+"')");
statement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
```
Hope it helps !
Benoît
|
using DBMS_APPLICATION_INFO with Jboss
|
[
"",
"java",
"oracle",
"jboss",
""
] |
Hey so what I want to do is snag the content for the first paragraph. The string `$blog_post` contains a lot of paragraphs in the following format:
```
<p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>
```
The problem I'm running into is that I am writing a regex to grab everything between the first `<p>` tag and the first closing `</p>` tag. However, it is grabbing the first `<p>` tag and the **last** closing `</p>` tag which results in me grabbing everything.
Here is my current code:
```
if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph))
echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>";
else
echo $blog_post;
```
|
Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this
```
<p>.*?</p>
```
Placing the `?` after your `*` makes it non-greedy, meaning it will only match as little text as necessary before matching the `</p>`.
|
If you use `preg_match`, use the **"U"** flag to make it un-greedy.
```
preg_match("/<p>(.*)<\/p>/U", $blog_post, &$matches);
```
`$matches[1]` will then contain the first paragraph.
|
How to grab the contents of HTML tags?
|
[
"",
"php",
"html",
"regex",
"html-parsing",
""
] |
I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.
Abstract class:
```
public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
```
Children:
```
public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
```
Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to *ToList* method of the *MyObjects* base class, as we do not specifically know the type of T at this point.
**EDIT**
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.
**EDIT**
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)
@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds
**EDIT** @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.
**EDIT**@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects.
@Rob **Again** Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.
**QUALIFYING EDIT** in case I have been a little confusing
To be more precise, (I may have let my latest implementation of this get it too complex):
lets say I have 2 object types, B and C inheriting from object A.
Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A.
The above example was a watered-down example of the *List Of Less Specific* problem's latest incarnation.
Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand
@Rob **Yet Again** and Sara
Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.
The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).
My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.
I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.
|
If you have
```
class B : A
class C : A
```
And you have
```
List<B> listB;
List<C> listC;
```
that you wish to treat as a List of the parent type
Then you should use
```
List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
```
|
In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for *different* classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call *ToList* in a loop cause it has different signature in different classes. You can create ToList that returns *objects* rather than specific type.
|
Suggestions wanted with Lists or Enumerators of T when inheriting from generic classes
|
[
"",
"c#",
"generics",
""
] |
In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++.
Previous editions of this course were just 1 or 2 half-day sessions and covered topics including:
* new language features, e.g.
+ header vs. implementation
+ pointers and references
+ memory management
+ operator overloading
+ templates
* the standard libraries, e.g.
+ the C library headers
+ basic iostreams
+ basic STL
* using libraries (headers, linking)
* they'll be using Linux, so
+ Basic Linux console commands
+ GCC and how to interpret its error messages
+ Makefiles and Autotools
* basic debugger commands
* any topic they ask about
During the course, each person individually writes, compiles, runs, and debugs simple programs using the newly introduced features. Is this the best way to learn?
1. Which topics do you consider most crucial?
2. Which topics should be added or removed?
3. Which topics just can't be covered adequately in a short time?
|
I can only once again point to [Stroustrup](http://www.research.att.com/~bs/new_learning.pdf) and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++.
Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers.
Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on.
Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++.
I've had quite good experiences with this order of teaching in the past.
/EDIT: If you happen to know any German, take a look at <http://madrat.net/coding/cpp/skript>, part of a *very* short introduction used in one of my courses.
|
If they are coming from a Java world, they are used to garbage collection. As such, I'd probably spend a bit of time talking about smart (reference counted) pointers, and how they compare to garbage collection.
|
How to teach a crash course on C++?
|
[
"",
"c++",
""
] |
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
```
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
```
|
Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.
Additionally, as others have pointed out, setUp is called before each test.
|
From <http://docs.python.org/lib/minimal-example.html> :
> When a setUp() method is defined, the
> test runner will run that method prior
> to each test.
So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.
|
Python's unittest logic
|
[
"",
"python",
"unit-testing",
""
] |
Has anyone else found VIM's syntax highlighting of Javascript sub-optimal? I'm finding that sometimes I need to scroll around in order to get the syntax highlighting adjusted, as sometimes it mysteriously drops all highlighting.
Are there any work-arounds or ways to fix this? I'm using vim 7.1.
|
You might like to try this [improved Javascript syntax highlighter](http://www.vim.org/scripts/script.php?script_id=1491) rather than the one that ships with VIMRUNTIME.
|
Well, I've modified [Yi Zhao's Javascript Syntax](http://www.vim.org/scripts/script.php?script_id=1491), and added Ajax Keywords support, also highlight DOM Methods and others.
Here it is, it is far from being perfect as I'm still new to Vim, but so far it has work for me. [My Javascript Syntax](http://www.vim.org/scripts/script.php?script_id=3425). If you can fix, add features, please do.
UPDATE: I forgot these syntax highlights are only shown if you included them in your own colorscheme, as I did in my `Nazca` colorscheme. I'll test if I could add these line into my modified syntax file.
Follow the new version of the javascript syntax file in [github](https://github.com/jelera/vim-javascript-syntax), for it is no longer required to modify your current colorscheme.
|
Javascript syntax highlighting in vim
|
[
"",
"javascript",
"vim",
"editing",
"vim-syntax-highlighting",
""
] |
My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:
```
select PTNO,PTNM,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
and here it is after the fix:
```
select PTNO,PTNM,PARTS.CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS.
Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity.
Am I wrong, or just not thinking about this problem correctly?
Update:
Here's a revised example, where the ambiguity error is not thrown:
```
CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER);
CREATE TABLE CATEGORIES(CATCD NUMBER);
CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER);
select PTNO,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD)
left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ;
```
Anybody have a clue?
|
I'm afraid I can't tell you why you're not getting an exception, but I can postulate as to why it chose CATEGORIES' version of the column over PARTS' version.
> As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity
It's not clear whether by "main" you mean simply the left table in a left join, or the "driving" table, as you see the query conceptually... But in either case, what you see as the "main" table in the query as you've written it will not necessarily be the "main" table in the actual execution of that query.
My guess is that Oracle is simply using the column from the first table it hits in executing the query. And since most individual operations in SQL do not require one table to be hit before the other, the DBMS will decide at parse time which is the most efficient one to scan first. Try getting an execution plan for the query. I suspect it may reveal that it's hitting CATEGORIES first and then PARTS.
|
> Here's the query (simplified version)
I think by simplifying the query you removed the real cause of the bug :-)
What oracle version are you using? Oracle 10g ( 10.2.0.1.0 ) gives:
```
create table parts (ptno number , ptnm number , catcd number);
create table CATEGORIES (catcd number);
select PTNO,PTNM,CATCD from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
I get ORA-00918: column ambiguously defined
|
Ambiguity in Left joins (oracle only?)
|
[
"",
"sql",
"oracle",
"join",
""
] |
I'm evaluating and looking at using CherryPy for a project that's basically a JavaScript front-end from the client-side (browser) that talks to a Python web service on the back-end. So, I really need something fast and lightweight on the back-end that I can implement using Python that then speaks to the PostgreSQL DB via an ORM (JSON to the browser).
I'm also looking at Django, which I like, since its ORM is built-in. However, I think Django might be a little more than I really need (i.e. more features than I really need == slower?).
Anyone have any experience with different Python ORM solutions that can compare and contrast their features and functionality, speed, efficiency, etc.?
|
SQLAlchemy is more full-featured and powerful (uses the DataMapper pattern). Django ORM has a cleaner syntax and is easier to write for (ActiveRecord pattern). I don't know about performance differences.
SQLAlchemy also has a [declarative layer](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative/index.html) that hides some complexity and gives it a ActiveRecord-style syntax more similar to the Django ORM.
I wouldn't worry about Django being "too heavy." It's decoupled enough that you can use the ORM if you want [without having to import the rest](https://stackoverflow.com/a/2180431/623735).
That said, if I were already using CherryPy for the web layer and just needed an ORM, I'd probably opt for SQLAlchemy.
|
If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee:
<https://github.com/coleifer/peewee>
Example:
```
import datetime
from peewee import *
class Blog(Model):
name = CharField()
class Entry(Model):
blog = ForeignKeyField(Blog)
title = CharField()
body = TextField()
pub_date = DateTimeField(default=datetime.datetime.now)
# query it like django
Entry.filter(blog__name='Some great blog')
# or programmatically for finer-grained control
Entry.select().join(Blog).where(Blog.name == 'Some awesome blog')
```
Check the [docs](http://peewee.readthedocs.org/en/latest/) for more examples.
|
What are some good Python ORM solutions?
|
[
"",
"python",
"orm",
""
] |
I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.
|
*watch* only breaks on write, *rwatch* let you break on read, and *awatch* let you break on read/write.
You can set read watchpoints on memory locations:
```
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
```
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables
in expressions:
```
gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.
```
So you have to expand them yourself:
```
gdb$ print $ebx
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()
```
**Edit:** Oh, and by the way. You need either hardware **or software support**. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the *can-use-hw-watchpoints* environment setting.
```
gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.
```
|
What you're looking for is called a *watchpoint*.
**Usage**
`(gdb) watch foo`: watch the value of **variable** `foo`
`(gdb) watch *(int*)0x12345678`: watch the value pointed by an **address**, casted to whatever type you want
`(gdb) watch a*b + c/d`: watch an arbitrarily **complex expression**, valid in the program's native language
Watchpoints are of three kinds:
* **watch**: gdb will break when a *write* occurs
* **rwatch**: gdb will break wnen a *read* occurs
* **awatch**: gdb will break in *both cases*
You may choose the more appropriate for your needs.
For more information, check [this](https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html) out.
|
Can I set a breakpoint on 'memory access' in GDB?
|
[
"",
"c++",
"debugging",
"gdb",
"breakpoints",
"memory-access",
""
] |
While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).
```
class Foo
{
ArrayList<Bar> bars = new ArrayList<Bar>(10);
}
```
A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?
Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.
|
The `ArrayList` class in Java has only two data members, a reference to an `Object[]` array and a size—which you need anyway if you don't use an `ArrayList`. So the only advantage to not using an `ArrayList` is saving one object allocation, which is unlikely ever to be a big deal.
If you're creating and disposing of many, many instances of your container class (and by extension your `ArrayList` instance) every second, you *might* have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries.
|
For the sake of keeping things simple, I think this is pretty much a non-issue. Your implementation is flexible enough that if the requirements change in the future, you aren't forced into a refactoring. Also, adding more logic to your code for a hybrid solution just isn't worth it taking into account your small data set and the high-quality of Java's Collection API.
|
Using Small (1-10 Items) Instance-Level Collections in Java
|
[
"",
"java",
"collections",
""
] |
Right, I know I am totally going to look an idiot with this one, but my brain is just *not* kicking in to gear this morning.
I want to have a method where I can say "if it goes bad, come back with this type of Exception", right?
For example, something like (**and this doesn't work**):
```
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
```
Now whats confusing me is that we *KNOW* that the generic type is going to be of an Exception type due to the *where* clause. However, the code fails because we cannot implicitly cast *Exception* to *ExType*. We cannot explicitly convert it either, such as:
```
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
```
As that fails too.. So **is this kind of thing possible?** I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P
---
## Update
Thanks for the responses guys, looks like it wasn't me being a *complete* idiot! ;)
OK, so [Vegard](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398) and [Sam](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404) got me on to the point where I could instantiate the correct type, but then obviously got stuck because the *message* param is read-only following instantiation.
[Matt](https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408) hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:
```
static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
```
Sweet! :)
Thanks guys!
|
You can almost do it like this:
```
static void TestException<E>(string message) where E : Exception, new()
{
var e = new E();
e.Message = message;
throw e;
}
```
However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor.
I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this:
```
static void TestException<E>(string message) where E : Exception
{
throw Activator.CreateInstance(typeof(E), message) as E;
}
```
**Edit** Oops just realised you're wanting to *return* the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.
|
The only issue with the solution is that it is possible to create a subclass of Exception which does not implement a constructor with a single string parameter, so the MethodMissingException might be thrown.
```
static void TestException<E>(string message) where E : Exception, new()
{
try
{
return Activator.CreateInstance(typeof(E), message) as E;
}
catch(MissingMethodException ex)
{
return new E();
}
}
```
|
Asking a Generic Method to Throw Specific Exception Type on FAIL
|
[
"",
"c#",
"generics",
"exception",
""
] |
I am looking to do this in C/C++. I came across [**Variable Length Arguments**](http://www.swig.org/Doc1.3/Varargs.html), but this suggests a solution with Python and C using [libffi](http://sourceware.org/libffi/).
Now, if I want to wrap the `printf` function with `myprintf`.
I do it like below:
```
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
```
But the results are not as expected!
```
This is a number: 1244780 and
this is a character: h and
another number: 29953463
```
What did I miss?
|
The problem is that you cannot use 'printf' with *va\_args*. You must use **vprintf** if you are using variable argument lists. *vprint*, *vsprintf*, *vfprintf*, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)
You sample works as follows:
```
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
```
|
In [C++11](https://en.wikipedia.org/wiki/C%2B%2B11), this is one possible solution using [variadic templates](http://en.cppreference.com/w/cpp/language/parameter_pack):
```
template<typename... Args>
void myprintf(const char* fmt, Args... args)
{
std::printf(fmt, args...);
}
```
As [rubenvb points out](https://stackoverflow.com/questions/41400/how-can-i-wrap-a-function-with-variable-length-arguments#comment26036756_41400), there are trade-offs to consider. For example, you will be generating code for each instance which will lead to code bloat.
|
How can I wrap a function with variable length arguments?
|
[
"",
"c++",
"c",
"variadic-functions",
""
] |
Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process.
Soon the update frequency will increase by an order of magnitude (maybe two).
Someone suggested that committing every N updates instead of after every update will help performance.
I have a few questions:
* Will that be faster or slower or it depends (planning to benchmark both way as soon as can get a decent simulation of the new load)
* Why will it help / hinder performance.
* If "it depends ..." , on what ?
* If it helps what's the best value of N ?
* Why can't my local DBA have an helpful straight answer when I need one?
(Actually I know the answer to that one) :-)
> EDIT:
>
> @codeslave : Thanks, btw losing
> uncommited changes is not a problem, I
> don't delete the original data used
> for updating till I am sure everything
> is fine , btw cleaning lady did
> unplugs the server, TWICE :-)
>
> Some googling showed it might help
> because of issue related to rollback
> segments, but I still don't know a
> rule of thumb for N every few tens ?
> hundreds? thousand ?
>
> @diciu : Great info, I'll definitely
> look into that.
|
A commit results in Oracle writing stuff to the disk - i.e. in the redo log file so that whatever the transaction being commited has done can be recoverable in the event of a power failure, etc.
Writing in file is slower than writing in memory so a commit will be slower if performed for many operations in a row rather then for a set of coalesced updates.
In Oracle 10g there's an asynchronous commit that makes it much faster but less reliable: <https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6158695.html>
PS I know for sure that, in a scenario I've seen in a certain application, changing the number of coalesced updates from 5K to 50K makes it faster by an order of magnitude (10 times faster).
|
Reducing the frequency of commits will certainly speed things up, however as you are reading and writing to this table frequently there is the potential for locks. Only you can determine the likelihood of the same data being updated at the same time. If the chance of this is low, commit every 50 rows and monitor the situation. Trial and error I'm afraid :-)
|
When to commit changes?
|
[
"",
"sql",
"oracle",
"commit",
""
] |
Given a declaration like this:
```
class A {
public:
void Foo() const;
};
```
What does it mean?
Google turns up this:
> Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.
But I find that somewhat confusing; can anyone out there put it in better terms?
Thanks.
|
Consider a variation of your class `A`.
```
class A {
public:
void Foo() const;
void Moo();
private:
int m_nState; // Could add mutable keyword if desired
int GetState() const { return m_nState; }
void SetState(int val) { m_nState = val; }
};
const A *A1 = new A();
A *A2 = new A();
A1->Foo(); // OK
A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK
```
The `const` keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of `A`. Thus you are unable to call non-`const` functions within `A::Foo` nor change the value of member variables.
To illustrate, *Foo()* may not invoke `A::SetState` as it is declared non-`const`, `A::GetState` however is ok because it is explicitly declared `const`. The member `m_nState` may not be changed either unless declared with the keyword `mutable`.
One example of this usage of `const` is for 'getter' functions to obtain the value of member variables.
> @1800 Information: I forgot about mutable!
The `mutable` keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.
|
This is not an answer, just a side comment. It is **highly** recommended to declare variables and constants `const` as much as possible.
1. This communicates your intent to users of your class (even/especially yourself).
2. The compiler will keep you honest to those intentions. -- i.e., it's like compiler checked documentation.
3. By definition, this prevents state changes you weren't expecting and can, possibly, allow you to make reasonable assumptions while in your methods.
4. `const` has a funny way of propagating through your code. Thus, it's a really good idea to start using `const` as early and as often as possible. Deciding to start `const`-ifying your code late in the game can be painful (easy, but annoying).
If you're using a language with static, compile time checks it's a great idea to make as much use of them as possible... it's just another kind of testing really.
|
What does the const operator mean when used with a method in C++?
|
[
"",
"c++",
""
] |
I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say.
The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)
Below is the code: (Alternatively someone could send me to a good example)
```
$img = imagecreatefromgif("./unit.gif");
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die("Unable to flip image");
}
header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
```
|
Shouldn't this:
```
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);
```
...be this:
```
imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
```
Note you should be calling these functions for the $temp image you have created, not the source image.
|
Final Results:
```
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die("Unable to flip image");
}
header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
```
|
Flip an Image horizontally
|
[
"",
"php",
""
] |
I have an Enumerable array
```
int meas[] = new double[] {3, 6, 9, 12, 15, 18};
```
On each successive call to the mock's method that I'm testing I want to return a value from that array.
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
```
Does anyone have an idea how I can do this?
|
There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it.
The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.
```
var meas = new int[] { 3, 6, 9, 12, 15, 18 };
using (mocks.Record())
{
int forMockMethod = 0;
SetupResult.For(mocked_class.GetValue()).Do(
new Func<int>(() => meas[forMockMethod++])
);
}
using(mocks.Playback())
{
foreach (var i in meas)
Assert.AreEqual(i, mocked_class.GetValue());
}
```
|
If the functionality is the GetValue() returns each array element in succession then you should be able to set up multiple expectations eg
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(3);
Expect.Call(mocked_class.GetValue()).Return(6);
Expect.Call(mocked_class.GetValue()).Return(9);
Expect.Call(mocked_class.GetValue()).Return(12);
Expect.Call(mocked_class.GetValue()).Return(15);
Expect.Call(mocked_class.GetValue()).Return(18);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
```
The mock repository will apply the expectations in order.
|
Rhino Mocks: How do I return numbers from a sequence
|
[
"",
"c#",
".net",
"rhino-mocks",
""
] |
Why does `n` not equal to `8` in the following function?
```
void foo(char cvalue[8])
{
int n = sizeof (cvalue);
}
```
But `n` *does* equal to `8` in this version of the function:
```
void bar()
{
char cvalue[8];
int n = sizeof (cvalue);
}
```
|
Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.
```
// These all do the same thing
void foo(char cvalue[8])
void foo(char cvalue[])
void foo(char *cvalue)
```
|
C and C++ arrays are not first class objects; you cannot pass arrays to functions, they always decay to pointers.
You can, however, pass pointers and references to arrays. This prevents the array bounds from decaying. So this is legal:
```
template<typename T, size_t N>
void foo(const T(&arr)[N])
{
int n = sizeof(arr);
}
```
|
Different sizeof results
|
[
"",
"c++",
"c",
"sizeof",
""
] |
What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module?
I'm interested in using [OSGi](http://en.wikipedia.org/wiki/OSGi) in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) Service Platforms](http://www.springframework.org/osgi). I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls?
@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.
@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?
|
Well, since you can not have one part OSGi and one part non-OSGi you'll need to make your entire app OSGi. In its simplest form you make a single OSGi bundle out of your entire application. Clearly this is not a best practice but it can be useful to get a feel for deploying a bundle in an OSGi container (Equinox, Felix, Knoplerfish, etc).
To take it to the next level you'll want to start splitting your app into components, components should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies. Identifying these purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.
Some help can come from tools like [JDepend](http://clarkware.com/software/JDepend.html) which can show you the coupling of Java packages against other packages/classes in your system. A package with low efferent coupling should be easier to extract into an OSGi bundle than one with high efferent coupling. Even more architectural insight can be had with pro tools like [Structure 101](http://www.headwaysoftware.com/products/structure101/index.php).
Purely on a technical level, working daily with an application that consists of 160 OSGi bundles and using Spring DM I can confirm that the transition from "normal" Spring to Spring DM is largely pain free. The extra namespace and the fact that you can (and should) isolate your OSGi specific Spring configuration in separate files makes it even easier to have both with and without OSGi deployment scenarios.
OSGi is a deep and wide component model, documentation I recommend:
* [OSGi R4 Specification](http://www.osgi.org/Release4/Download): Get the PDFs of the Core and Compendium specification, they are canonical, authoritative and very readable. Have a shortcut to them handy at all times, you will consult them.
* Read up on OSGi best practices, there is a large set of things you **can** do but a somewhat smaller set of things you **should** do and there are some things you should **never do** (DynamicImport: \* for example).
Some links:
* [OSGi best practices and using Apache Felix](http://felix.apache.org/site/presentations.data/best-practices-apachecon-20060628.pdf)
* [Peter Kriens and BJ Hargrave in a Sun presentation on OSGi best practices](http://www.osgi.org/wiki/uploads/CommunityEvent2007/OSGiBestPractices.pdf)
* one key OSGi concept are Services, learn why and how they supplant the Listener pattern with the [Whiteboard pattern](http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf)
* [The Spring DM Google Group](http://groups.google.com/group/spring-osgi) is very responsive and friendly in my experience
[The Spring DM Google Group](http://groups.google.com/group/spring-osgi) is [no longer active](https://groups.google.com/forum/#!topic/spring-osgi/e-3gVCgl-_M) and has moved to Eclipse.org as the Gemini Blueprint project which has a forum [here](http://www.eclipse.org/forums/index.php?t=thread&frm_id=153).
|
When learning a new technology rich tooling gets you into things without big headaches.
At this point the community at [ops4j.org](http://wiki.ops4j.org/confluence/x/Bg/) provides a rich toolset called "PAX" which includes:
* **Pax Runner**: Run and switch between Felix, Equinox, Knopflerfish and Concierge easily
* **Pax Construct**: Construct, Organize & Build OSGi projects with maven easily
* **Pax Drone**: Test your OSGi bundles with Junit while being framework independent (uses PaxRunner)
Then there are many implementations of OSGi compendium services:
* **Pax Logging** (logging),
* **Pax Web** (http service),
* **Pax Web Extender** (war support),
* **Pax Coin** (configuration),
* **Pax Shell** (shell implementation, part of the next osgi release)
* and much more.
.. and there is a helpful, framework independend community, - but thats now advertisement ;-)
|
What's the best way to get started with OSGI?
|
[
"",
"java",
"spring",
"osgi",
""
] |
Why do we need to use:
```
extern "C" {
#include <foo.h>
}
```
**Specifically:**
* When should we use it?
* What is happening at the compiler/linker level that requires us to use it?
* How in terms of compilation/linking does this solve the problems which require us to use it?
|
C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data.
(To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling `printf()` without flagging the prototype as a C function, the C++ will actually generate code calling `_Zprintf`, plus extra crap at the end.)
So: use `extern "C" {...}` when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the `extern` because most system C headers will already account for the fact that they might be included by C++ code and already `extern "C"` their code.
|
extern "C" determines how symbols in the generated object file should be named. If a function is declared without extern "C", the symbol name in the object file will use C++ name mangling. Here's an example.
Given test.C like so:
```
void foo() { }
```
Compiling and listing symbols in the object file gives:
```
$ g++ -c test.C
$ nm test.o
0000000000000000 T _Z3foov
U __gxx_personality_v0
```
The foo function is actually called "\_Z3foov". This string contains type information for the return type and parameters, among other things. If you instead write test.C like this:
```
extern "C" {
void foo() { }
}
```
Then compile and look at symbols:
```
$ g++ -c test.C
$ nm test.o
U __gxx_personality_v0
0000000000000000 T foo
```
You get C linkage. The name of the "foo" function in the object file is just "foo", and it doesn't have all the fancy type info that comes from name mangling.
You generally include a header within extern "C" {} if the code that goes with it was compiled with a C compiler but you're trying to call it from C++. When you do this, you're telling the compiler that all the declarations in the header will use C linkage. When you link your code, your .o files will contain references to "foo", not "\_Z3fooblah", which hopefully matches whatever is in the library you're linking against.
Most modern libraries will put guards around such headers so that symbols are declared with the right linkage. e.g. in a lot of the standard headers you'll find:
```
#ifdef __cplusplus
extern "C" {
#endif
... declarations ...
#ifdef __cplusplus
}
#endif
```
This makes sure that when C++ code includes the header, the symbols in your object file match what's in the C library. You should only have to put extern "C" {} around your C header if it's old and doesn't have these guards already.
|
Why do we need extern "C"{ #include <foo.h> } in C++?
|
[
"",
"c++",
"linkage",
"name-mangling",
"extern-c",
""
] |
I have a a property defined as:
```
[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
```
If the List<> Delete has no items
```
<delete />
```
is emitted. If the List<> Delete is set to null
```
<delete xsi:nil="true" />
```
is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?
[Greg](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407) - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.
[Rob Cooper](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518) - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.
|
If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.
My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter.
|
I've had the same issue where I did not want an element outputted if the field is empty or 0.
The XML outputted could not use xsi:null="true" (by design).
I've read somewhere that if you include a property of type bool with the same name as the field you want to control but appended with 'Specified', the XMLSerializer will check the return value of this property to determine if the corresponding field should be included.
To achieve this without implementing IXMLSerializer:
```
public List<Event> Delete { get; set; }
[XMLIgnore]
public bool DeleteSpecified
{
get
{
bool isRendered = false;
if (Delete != null)
{
isRendered = (Delete.Count > 0);
}
return isRendered;
}
set
{
}
}
```
|
XML Serialization and empty collections
|
[
"",
"c#",
"xml-serialization",
""
] |
I'm trying to find a way to fake the result of a method called from within another method.
I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result).
So I have code like this:
```
public class MyClass(){
public void LoadData(){
SomeProperty = Helper.GetSomeData();
}
public object SomeProperty {get;set;}
}
```
I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?
\*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.
|
As far as I know, you should create an interface or a base abstract class for the Helper object. With Rhino Mocks you can then return the value you want.
Alternatively, you can add an overload for LoadData that accepts as parameters the data that you normally retrieve from the Helper object. This might even be easier.
|
You have a problem there. I don't know if thats a simplified scenario of your code, but if the Helper class is used that way, then your code is not testable. First, the Helper class is used directly, so you **can't replace it with a mock**. Second, you're calling a static method. I don't know about C#, but in Java you **can't override static methods**.
You'll have to do some refactoring to be able to inject a mock object with a dummy GetSomeData() method.
In this simplified version of your code is difficult to give you a straight answer. You have some options:
* Create an interface for the Helper class and provide a way for the client to inject the Helper implementation to the MyClass class. But if Helper is just really a utility class it doesn't make much sense.
* Create a protected method in MyClass called getSomeData and make it only call Helper.LoadSomeData. Then replace the call to Helper.LoadSomeData in LoadData with for getSomeData. Now you can mock the getSomeData method to return the dummy value.
---
**Beware of simply creating an interface to Helper class** and inject it via method. This can expose implementation details. Why a client should provide an implementation of a **utility** class to call a simple operation? This will increase the complexity of MyClass clients.
|
Mocking method results
|
[
"",
"c#",
"mocking",
"rhino-mocks",
""
] |
I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).
|
As long as there are no identity columns you can just
```
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
```
|
Alternative syntax:
```
INSERT tbl (Col1, Col2, ..., ColN)
SELECT Col1, Col2, ..., ColN
FROM Tbl2
WHERE ...
```
The select query can (of course) include expressions, case statements, constants/literals, etc.
|
How to copy a row from one SQL Server table to another
|
[
"",
"sql",
"sql-server",
""
] |
Most mature C++ projects seem to have an own **reflection and attribute system**, i.e for defining attributes which can be accessed by string and are automatically serializable. At least many C++ projects I participated in seemed to **reinvent the wheel**.
Do you know any **good open source libraries** for C++ which support reflection and attribute containers, specifically:
* Defining RTTI and attributes via macros
* Accessing RTTI and attributes via code
* Automatic serialisation of attributes
* Listening to attribute modifications (e.g. OnValueChanged)
|
You could have a look at the two tools below. I've never used either of them, so I can't tell you how (im)practical they are.
**[XRTTI](http://www.ischo.com/xrtti/)**:
> Xrtti is a tool and accompanying C++ library which extends the standard runtime type system of C++ to provide a much richer set of reflection information about classes and methods to manipulate these classes and their members.
**[OpenC++](http://opencxx.sourceforge.net/)**:
> OpenC++ is C++ frontend library (lexer+parser+DOM/MOP) and source-to-source translator. OpenC++ enables development of C++ language tools, extensions, domain specific compiler optimizations and runtime metaobject protocols.
|
There is a new project providing reflection in C++ using a totally different approach: **CAMP**.
<https://github.com/tegesoft/camp>
CAMP doesn't use a precompiler, the classes/properties/functions/... are declared manually using a syntax similar to boost.python or luabind. Of course, people can use a precompiler like gccxml or open-c++ to generate this declaration if they prefer.
It's based on pure C++ and boost headers only, and thanks to the power of template meta-programming it supports any kind of bindable entity (inheritance and strange constructors are not a problem, for example).
It is distributed under the MIT licence (previously LGPL).
|
Attribute & Reflection libraries for C++?
|
[
"",
"c++",
"reflection",
"attributes",
""
] |
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.
I has used the auto-complete plugin provided with Notepad++, which presented me with `onClick`.
When I changed the capital `C` to a small `c`, it did work.
So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.
But when you change `getElementById` to `getelementbyid`, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.
So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?
|
Javascript is **ALWAYS** case-sensitive, html is not.
It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is.
So, you can do this:
```
<div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C'
```
or:
```
<div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C'
```
but through the DOM you must use the correct case. So this works:
```
getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C'
```
but you cannot do this:
```
getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C'
```
EDIT: CMS makes a great point that most DOM methods and properties are in [camelCase](http://www.perlmonks.org/?node_id=45213). The one exception that comes to mind are event handler properties and these are generally accepted to be [the wrong way to attach to events](http://javascript.about.com/library/blonclick.htm) anyway. Prefer using [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) as in:
```
document.getElementById('divYo').addEventListener('click', modifyText, false);
```
|
A few objects is IE aren't always case-sensitive, including some/most/all ActiveX -- why both **XHR.onReadyStateChange** and **XHR.onreadystatechange** would work fine in IE5 or IE6, but only the latter would work with the native **XMLHttpRequest** object in IE7, FF, etc.
But, a quick reference for "*standard*" API casing:
* **UPPERCASE** - Constants (generally symbolic, since **const** isn't globally supported)
* **Capitalized** - Classes/Object functions
* **lowercase** - Events
* **camelCase** - everything else
No 100% guarantees. But, majority-wise, this is accurate.
|
JavaScript and why capital letters sometimes work and sometimes don't
|
[
"",
"javascript",
"html",
"dom",
"case-sensitive",
""
] |
Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
```
public DerivedClass : BaseClass {}
```
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
|
**It's not possible, why?**
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow this on purpose so that you use inheritance more properly.
For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations.
So they don't allow it to protect you from bad inheritance hierarchies.
**What should you do instead?**
Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.
**Other languages:**
In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.
**The restructured code:**
```
interface I
{
void C();
}
class BaseClass
{
public void A() { MessageBox.Show("A"); }
public void B() { MessageBox.Show("B"); }
}
class Derived : I
{
public void C()
{
b.A();
b.B();
}
private BaseClass b;
}
```
I understand the names of the above classes are a little moot :)
**Other suggestions:**
Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
|
When you, for instance, try to inherit from a `List<object>`, and you want to hide the direct `Add(object _ob)` member:
```
// the only way to hide
[Obsolete("This is not supported in this class.", true)]
public new void Add(object _ob)
{
throw NotImplementedException("Don't use!!");
}
```
It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:
> error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'
|
C# - Can publicly inherited methods be hidden (e.g. made private to derived class)
|
[
"",
"c#",
"class",
"derived",
""
] |
At the company I work for we have a "Utility" project that is referenced by pretty much ever application we build. It's got lots of things like NullHelpers, ConfigSettingHelpers, Common ExtensionMethods etc.
The way we work is that when we want to make a new project, we get the latest version of the project from source control add it to the solution and then reference the project from any new projects that get added to the solution.
This has worked ok, however there have been a couple of instances where people have made "breaking changes" to the common project, which works for them, but doesn't work for others.
I've been thinking that rather than adding the common library as a project reference perhaps we should start developing the common library as a standalone dll and publish different versions and target a particular version for a particular project so that changes can be made without any risk to other projects using the common library.
Having said all that I'm interested to see how others reference or use their common libraries.
|
That's exactly what we're doing. We have a Utility project which has some non project specific useful functions. We increase the version manually (minor), build the project in Release version, sign it and put it to a shared location.
People then use the specific version of the *library*.
If some useful methods are implemented in some specific projects which could find their way into main Utility project, we put the to a special helper class in the project, and mark them as a possible Utility candidate (simple //TODO). At the end of the project, we review the candidates and if they stick, we move them to the main *library*.
Breaking changes are a no-no and we mark methods and classes as [Obsolete] if needed.
But, it doesn't really matter because we increase the version on every publish.
Hope this helps.
|
We use branching in source control; everyone uses the head branch until they make a release. When they branch the release, they'll branch the common utilities project as well.
Additionally, our utilities project has its own unit tests. That way, other teams can know if they would break the build for other teams.
Of course, we still have problems like you mention occasionally. But when one team checks in a change that breaks another team's build, it usually means the contract for that method/object has been broken somewhere. We look at these as opportunities to improve the design of the common utilities project... or at least to write more unit tests :/
|
Working with Common/Utility Libraries
|
[
"",
"c#",
"visual-studio",
"api",
""
] |
I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.
How could I go about doing this?
|
You can use the [eval](http://php.net/manual/en/function.eval.php) command for this. **I would recommend against this though, because there's a lot of pitfalls using this approach.** Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).
See [When is eval evil in php?](https://stackoverflow.com/questions/951373/when-is-eval-evil-in-php) for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution.
Addition: Another good article with some references to exploits is [this blogpost](http://www.sitepoint.com/blogs/2005/02/27/eval-is-dead-long-live-eval/). Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
|
Easy:
```
$x // your variable with the data from the DB
<?php echo eval("?>".$x."<?") ?>
```
Let me know, works great for me in MANY applications, can't help but notice that everyone is quick to say how bad it is, but slow to actually help out with a straight answer...
|
How do I execute PHP that is stored in a MySQL database?
|
[
"",
"php",
"mysql",
""
] |
I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:
```
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+)
```
The log format (which I use for testing the parser) is this:
```
07/23/08 14:17:31,321 log
message
spanning
multiple
lines
07/23/08 14:17:31,321 log message on one line
```
When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).
---
@samjudson:
*You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).*
I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).
The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.
---
I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.
```
(?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
```
|
This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group:
```
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/
\d{2}))+)
```
Note that this requires the use of the RegexOptions.MultiLine flag.
|
You obviously need that "messages lines" can be distinguished from "log lines"; if you allow the message part to start with date/time after a new line, then there is simply no way to determine what is part of a message and what not. So, instead of using the dot, you need an expression that allows anything that does not include a newline followed by a date and time.
Personally, however, I would not use a regular expression to parse the whole log entry. I prefer using my own loop to iterate over each line and use one simple regular expression to determine whether a line is the start of a new entry or not. Also from the point of readability this would have my preference.
|
Parsing a log file with regular expressions
|
[
"",
"c#",
"regex",
""
] |
In Oracle, what is the difference between :
```
CREATE TABLE CLIENT
(
NAME VARCHAR2(11 BYTE),
ID_CLIENT NUMBER
)
```
and
```
CREATE TABLE CLIENT
(
NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11)
ID_CLIENT NUMBER
)
```
|
Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.
If you define the field as `VARCHAR2(11 BYTE)`, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.
By defining the field as `VARCHAR2(11 CHAR)` you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
|
One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.
See also <http://www.joelonsoftware.com/articles/Unicode.html>
|
Difference between BYTE and CHAR in column datatypes
|
[
"",
"sql",
"oracle",
"unicode",
"varchar",
""
] |
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`.
I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
|
Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.
A few things to notice:
1. This code uses the [BlobStore API](http://code.google.com/appengine/docs/python/blobstore/)
2. The purpose of this line in the
ServeHandler class is to "fix" the
key so that it gets rid of any name
mangling that may have occurred in
the browser (I didn't observe any in
Chrome)
```
blob_key = str(urllib.unquote(blob_key))
```
3. The "save\_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens.
```
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
```
Good Luck!
```
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")
for b in blobstore.BlobInfo.all():
self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/')
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
blob_key = str(urllib.unquote(blob_key))
if not blobstore.get(blob_key):
self.error(404)
else:
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
```
|
In fact, this question is answered in the App Egnine documentation. See an example on [Uploading User Images](http://code.google.com/appengine/docs/images/usingimages.html#Uploading).
HTML code, inside <form></form>:
```
<input type="file" name="img"/>
```
Python code:
```
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get("content")
avatar = self.request.get("img")
greeting.avatar = db.Blob(avatar)
greeting.put()
self.redirect('/')
```
|
Upload files in Google App Engine
|
[
"",
"python",
"google-app-engine",
""
] |
In how many languages is Null not equal to anything not even Null?
|
It's this way in SQL (as a logic language) because null means unknown/undefined.
However, in programming languages (like say, C++ or C#), a null pointer/reference is a specific value with a specific meaning -- nothing.
Two nothings are equivilent, but two unknowns are not. The confusion comes from the fact that the same name (null) is used for both concepts.
|
In VB6 the expression `Null = Null` will produce `Null` instead of `True` as you would expect.
This will cause a runtime error if you try to assign it to a Boolean, however if you use it
as the condition of "`If ... Then`" it will act like `False`. Moreover `Null <> Null` will **also**
produce `Null`, so:
**In VB6 you could say that `Null` is neither equal to itself (or anything else), nor unequal!**
You're supposed to test for it using the `IsNull()` function.
VB6 also has other special values:
* `Nothing` for object references. `Nothing = Nothing` is a compile error. (you're supposed to compare it using "`is`")
* `Missing` for optional parameters which haven't been given. It has no literal representation so you can't even write `Missing = Missing`. (the test is `IsMissing(foo)`)
* `Empty` for uninitialized variables. This one does test equal to itself although there's **also** a function `IsEmpty()`.
* ... let me know if I've forgotten one
I remember being a bit disgusted with VB.
|
In how many languages is Null not equal to anything not even Null?
|
[
"",
"sql",
"ruby",
"oracle",
"language-agnostic",
"vb6",
""
] |
The built-in `PHP` extension for `SOAP` doesn't validate everything in the incoming `SOAP` request against the `XML Schema` in the `WSDL`. It does check for the existence of basic entities, but when you have something complicated like `simpleType` restrictions the extension pretty much ignores their existence.
What is the best way to validate the `SOAP` request against `XML Schema` contained in the `WSDL`?
|
Been digging around on this matter a view hours.
Neither the native PHP SoapServer nore the NuSOAP Library does any Validation.
PHP SoapServer simply makes a type cast.
For Example if you define
```
<xsd:element name="SomeParameter" type="xsd:boolean" />
```
and submit
```
<get:SomeParameter>dfgdfg</get:SomeParameter>
```
you'll get the php Type boolean (true)
NuSOAP simply casts everthing to string although it recognizes simple types:
from the nuSOAP debug log:
```
nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean
```
So the best way is joelhardi solution to validate yourself or use some xml Parser like XERCES
|
Besides the native PHP5 SOAP libs, I can also tell you that neither the PEAR nor Zend SOAP libs will do schema validation of messages at present. (I don't know of any PHP SOAP implementation that does, unfortunately.)
What I would do is load the XML message into a [DOMDocument](http://www.php.net/manual/en/class.domdocument.php) object and use DOMDocument's methods to validate against the schema.
|
Validate an incoming SOAP request to the WSDL in PHP
|
[
"",
"php",
"soap",
"wsdl",
"xsd",
""
] |
I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.
For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:
```
int[] IntArray = {1,2,3};
```
Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.
|
Array list has ctor which accepts ICollection, which is implemented by the Array class.
```
object[] myArray = new object[] {1,2,3,"string1","string2"};
ArrayList myArrayList = new ArrayList(myArray);
```
|
Depending on the version of C# you are using, you have different options.
C# 3.0 has collection initializers, detail at [Scott Gu's Blog](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx)
Here is an example of your problem.
```
ArrayList list = new ArrayList {1,2,3};
```
And if you are initializing a collection object, most have constructors that take similar components to AddRange, although again as you mentioned this may not be an option.
|
C#: Is Implicit Arraylist assignment possible?
|
[
"",
"c#",
"arraylist",
""
] |
I just installed Java 1.6\_07 so I could try profiling with VisualVM. It tells me that my app is spending 60% of its time in `sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run`
How do I find out what it was doing during that time? How much of the time was it waiting for something to call it, or doing something else? What was calling it and what was it calling? I just can't seem to find any way to drill down to deeper levels like there is in Quantify or the Perl profiler.
|
I don't have experience with VisualVM -- but JRockit's profiler *does* provide this information; you may consider using it instead.
**Update:** a question with a list of java profilers can be found [here](https://stackoverflow.com/questions/14762/please-recommend-a-java-profiler), for users with sufficient rep to view deleted questions.
|
Does your App use RMI over TCP? If not, is it possible that this is a heisenbug, caused by instrumenting the VM? I assume VisualVM must use RMI calls to figure out what's going on in the JVM....
|
Drilling down in VisualVM
|
[
"",
"java",
"visualvm",
""
] |
I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?
|
You can call the command-line version of inkscape to do this:
<http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx>
Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:
**Original Project**
<http://www.codeplex.com/svg>
**Fork with fixes and more activity:** (added 7/2013)
<https://github.com/vvvv/SVG>
|
There is a much easier way using the library <http://svg.codeplex.com/> (Newer version @[GIT](https://github.com/vvvv/SVG), @[NuGet](https://www.nuget.org/packages/Svg/)). Here is my code
```
var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(path, ImageFormat.Png);
}
```
|
Converting SVG to PNG using C#
|
[
"",
"c#",
".net",
"png",
"svg",
""
] |
I'm handling the `onSelectIndexChanged` event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for `SelectedValue` and `SelectedIndex`. What am I doing wrong?
Here is the DropDownList definition from the aspx file:
```
<div style="margin: 0px; padding: 0px 1em 0px 0px;">
<span style="margin: 0px; padding: 0px; vertical-align: top;">Route:</span>
<asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true">
</asp:DropDownList>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
```
Here is the DropDownList `OnSelectedIndexChanged` event handler:
```
protected void index_changed(object sender, EventArgs e)
{
decimal d = Convert.ToDecimal( Select1.SelectedValue );
Literal1.Text = d.ToString();
}
```
|
Do you have any code in page load that is by chance re-defaulting the value to the first value?
When the page reloads do you see the new value?
|
If you are using AJAX you may also be doing a callback, not a full postback. In that case you may want to use this in your page load method:
```
if (!IsCallback && !IsPostBack)
{
// Do your page setup here
}
```
|
SelectedIndexChanged event handler getting old index
|
[
"",
"c#",
"asp.net",
"webforms",
""
] |
In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed.
A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble getting this to work in practice.
|
gcc -E will output the preprocessed source to stdout.
|
For MSVC users, you can right-click on the file/project, view the settings and change the file properties to output preprocessed source (which typically in the obj directory).
|
Is there a good general method for debugging C++ macros?
|
[
"",
"c++",
"debugging",
"gcc",
"macros",
""
] |
I have a winforms application where users will be creating stock items, and a time of creation there are a number of different things that need to happen.
I think the UI for this should probably be a wizard of some kind, but I'm unsure as to the best way to achieve this. I have seen a couple of 3rd party Wizard controls, and I have also seen manual implementations of making panel visible/invisible.
What are the best ways that people have used in the past, that are easy to implement, and also make it easy to add "pages" to the wizard later on if needed?
|
Here are a few more resources you should check out:
1. This DevExpress WinForms control: <http://www.devexpress.com/Products/NET/Controls/WinForms/Wizard/>
2. A home-grown wizards framework: <http://weblogs.asp.net/justin_rogers/articles/60155.aspx>
3. A wizard framework by Shawn Wildermut part of the Chris Sells's Genghis framework: <http://www.sellsbrothers.com/tools/genghis/>
|
I know this answer has already been accepted, but I just found a better Wizard control that's free, and of course, since it's on CodeProject, includes the source, so you can modify it if it's not exactly what you want. I'm adding this as an answer for the next person to stumble across this question looking for a good Wizard control.
<http://www.codeproject.com/KB/miscctrl/DesignTimeWizard.aspx>
|
What is the best way to create a wizard in C# 2.0?
|
[
"",
"c#",
"visual-studio",
"winforms",
"user-interface",
"wizard",
""
] |
Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?
Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.
Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?
|
The code will look something like this:
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
```
|
You can use the UploadValues method on WebClient - all it requires is passing a URL and a NameValueCollection. It is the easiest approach that I have found, and the MS documentation has a nice example:
<http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx>
Here is a simple version with some error handling:
```
var webClient = new WebClient();
Debug.Info("PostingForm: " + url);
try
{
byte [] responseArray = webClient.UploadValues(url, nameValueCollection);
return new Response(responseArray, (int) HttpStatusCode.OK);
}
catch (WebException e)
{
var response = (HttpWebResponse)e.Response;
byte[] responseBytes = IOUtil.StreamToBytes(response.GetResponseStream());
return new Response(responseBytes, (int) response.StatusCode);
}
```
The Response class is a simple wrapper for the response body and status code.
|
How do you programmatically fill in a form and 'POST' a web page?
|
[
"",
"c#",
"asp.net",
""
] |
I'm trying to get an event to fire whenever a choice is made from a `JComboBox`.
The problem I'm having is that there is no obvious `addSelectionListener()` method.
I've tried to use `actionPerformed()`, but it never fires.
Short of overriding the model for the `JComboBox`, I'm out of ideas.
How do I get notified of a selection change on a `JComboBox`?\*\*
**Edit:** I have to apologize. It turns out I was using a misbehaving subclass of `JComboBox`, but I'll leave the question up since your answer is good.
|
It should respond to [ActionListeners](http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html), like this:
```
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
doSomething();
}
});
```
[@John Calsbeek](https://stackoverflow.com/a/58965/1429387) rightly points out that `addItemListener()` will work, too. You may get 2 `ItemEvents`, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!
|
Code example of `ItemListener` implementation
```
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
```
Now we will get only selected item.
Then just add listener to your JComboBox
```
addItemListener(new ItemChangeListener());
```
|
JComboBox Selection Change Listener?
|
[
"",
"java",
"swing",
"jcombobox",
"itemlistener",
""
] |
I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?
```
CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
```
I need to be able to iterate through both result sets individually.
EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.
The result sets returned by the procedures are not the same data types or number of columns.
|
The short answer is: you can't do it.
From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.
To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:
```
INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
```
You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
|
I was easily able to do this by creating a SQL2005 CLR stored procedure which contained an internal dataset.
You see, a new SqlDataAdapter will .Fill a multiple-result-set sproc into a multiple-table dataset by default. The data in these tables can in turn be inserted into #Temp tables in the calling sproc you wish to write. **dataset.ReadXmlSchema** will show you the schema of each result set.
**Step 1: Begin writing the sproc which will read the data from the multi-result-set sproc**
a. Create a separate table for each result set according to the schema.
```
CREATE PROCEDURE [dbo].[usp_SF_Read] AS
SET NOCOUNT ON;
CREATE TABLE #Table01 (Document_ID VARCHAR(100)
, Document_status_definition_uid INT
, Document_status_Code VARCHAR(100)
, Attachment_count INT
, PRIMARY KEY (Document_ID));
```
b. At this point you may need to declare a cursor to repetitively call the CLR sproc you will create here:
**Step 2: Make the CLR Sproc**
```
Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub usp_SF_ReadSFIntoTables()
End Sub
End Class
```
a. Connect using `New SqlConnection("context connection=true")`.
b. Set up a command object (cmd) to contain the multiple-result-set sproc.
c. Get all the data using the following:
```
Dim dataset As DataSet = New DataSet
With New SqlDataAdapter(cmd)
.Fill(dataset) ' get all the data.
End With
'you can use dataset.ReadXmlSchema at this point...
```
d. Iterate over each table and insert every row into the appropriate temp table (which you created in step one above).
**Final note:**
In my experience, you may wish to enforce some relationships between your tables so you know which batch each record came from.
That's all there was to it!
~ Shaun, Near Seattle
|
Access to Result sets from within Stored procedures Transact-SQL SQL Server
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
Can anyone tell me what exactly does this Java code do?
```
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
```
---
Step by step explanation will be useful so that I can recreate this code in VB. Thanks
|
Using code snippets you can get to something like this
```
Dim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()
Dim randomBytes(20) As Byte
randomNumGen.GetBytes(randomBytes)
return Convert.ToBase64String(randomBytes)
```
|
This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and populates it with random data.
This is then encoded using BASE64 and returned.
So, in a nutshell,
1. Generate 20 random bytes
2. Encode using Base 64
|
equivalent vb code for a java code
|
[
"",
"java",
"vba",
"random",
""
] |
How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.
|
### 2015 Update
[Content security policy](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy) will prevent this from working in many sites now. For example, the code below won't work on Facebook.
### 2008 answer
Use a bookmarklet that creates a script tag which includes your external JS.
As a sample:
```
javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
```
|
Firefox and perhaps others support multiline bookmarklets, no need for one liner. When you paste in the code it just replaces newlines with spaces.
```
javascript:
var q = document.createElement('script');
q.src = 'http://svnpenn.github.io/bm/yt.js';
document.body.appendChild(q);
void 0;
```
[Example](http://github.com/svnpenn/bm/blob/ad7e0c6/index.htm#L27-L32)
|
Load external JS from bookmarklet?
|
[
"",
"javascript",
"load",
"external",
"bookmarklet",
""
] |
I am working on designing and building a desktop application. I am thinking about using eclipse or netbeans for the base of this application. However, I have never built on either of these platforms. I am personally leaning to using netbeans because it seams like that platform is an easer learning curve. But, I wanted to ask people that have actually build on these platforms before which one is easier to use?
My personal definition of easer is as follows:
* Easy to get started with
* Consistent and logical API
* Good documentation
* Easy to build and deploy
Thanks very much,
Josh
|
I can't say enough about the Eclipse RCP platform. I would recommend it for any Java desktop app development.
It's free, has great tutorials, and allows cross-platform development of rich desktop applications that use native OS windowing toolkit, meaning that your application will look native in any platform. It also has a clean API that stays out of your way, and makes deploying to any platform a piece of cake.
If your interested check out this book: [http://www.amazon.com/Eclipse-Rich-Client-Platform-Applications/dp/0321334612](https://rads.stackoverflow.com/amzn/click/com/0321334612)
|
* **Easy to use**: I have experience developing on Eclipse and I have to say it's not easy to understand its development model. Sure for basic stuff it has some wizards that make easier, but for something a little more complex it's just difficult. I don't know about Netbeans, but I heard its easier.
* **Consistent API**: I think Eclipse wins in this aspect. It runs over OSGI (brings some complexity though) and has plugins extensions for pretty much everything. It seems to be the platform of choice for plugin development, so I can assume it's reliable.
* **Documentation**: Eclipse wins by far. The help from eclipse site is excelent and the mailing list has plenny of users questions.
|
Java Desktop application framework
|
[
"",
"java",
"eclipse",
"netbeans",
"desktop",
"platform",
""
] |
I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?
|
My preference is to have classes that use time actually rely on an interface, such as
```
interface IClock
{
DateTime Now { get; }
}
```
With a concrete implementation
```
class SystemClock: IClock
{
DateTime Now { get { return DateTime.Now; } }
}
```
Then if you want, you can provide any other kind of clock you want for testing, such as
```
class StaticClock: IClock
{
DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }
}
```
There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a [Static Gateway Pattern](http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/10/15/the-static-gateway-pattern.aspx)).
Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels.
Also, using `DateTime.Now` and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want.
|
Ayende Rahien [uses](http://www.ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx) a static method that is rather simple...
```
public static class SystemTime
{
public static Func<DateTime> Now = () => DateTime.Now;
}
```
|
What's a good way to overwrite DateTime.Now during testing?
|
[
"",
"c#",
"unit-testing",
"datetime",
"testing",
""
] |
Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:
```
Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
```
How would you go about finding the best combination programmatically?
My best attempt so far (third or fourth algorithm) is:
1. Find the longest shipper for each leg
2. Eliminate the most "expensive" one
3. Find the cheapest shipper for each leg
4. Calculate the total cost & days
5. If days are acceptable, finish, else, goto 1
Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):
```
$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " <?> " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
```
I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....
EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.
The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A\* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.
So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.
|
Could alter some of the [shortest path algorithms](http://en.wikipedia.org/wiki/Shortest_path_problem), like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way
|
Sounds like what you have is called a "linear programming problem". It also sounds like a homework problem, no offense.
The classical solution to a LP problem is called the "Simplex Method". Google it.
However, to use that method, you must have the problem correctly formulated to describe your requirements.
Still, it may be possible to enumerate all possible paths, since you have such a small set. Such a thing won't scale, though.
|
Find the best combination from a given set of multiple sets
|
[
"",
"php",
"algorithm",
"puzzle",
"combinations",
"np-complete",
""
] |
I am looking into game programming in Java to see if it is feasible. When googling for it I find several old references to Java2D, Project Darkstar (Sun's MMO-server) and some books on Java game programming. But alot of the information seems to be several years old.
So the question I am asking, is anyone creating any games in Java SE 1.5 or above?
If so, what frameworks are used and are there any best practices or libraries available?
|
there is the excellent open source 3d engine called jMonkey (<http://www.jmonkeyengine.com>) which is being used for a few commercial projects as well as hobby developers...
there is also at a lower level the lwjgl library which jmonkeyengine is built on which is a set of apis to wrap opengl as well as provide other game specific libs...
|
<http://www.javagaming.org/> is a good source for up-to-date information.
Another framework not mentioned yet is [Xith3D](http://xith.org/)
|
Game programming in Java?
|
[
"",
"java",
""
] |
EDIT: Learned that Webmethods actually uses NLST, not LIST, if that matters
Our business uses the WebMethods integration server to handle most of our outbound communications, and its FTP functionality leaves something to be desired. We are having a problem that may be specific to WebMethods, but if anyone can point me in a direction of what kinds of things might cause this I'd appreciate it.
When polling two of our partners' FTP servers, we connect without issue but, when doing a NLST on a directory that is empty (no files and no subdirectories) it's timing out. The actual error is:
> com.wm.net.ftpCException: [ISC.0064.9010] java.net.SocketTimeoutException: Accept timed out
It's being thrown during the invocation of the pub.client.ftp:ls service. I've logged in with a number of FTP clients without a problem to the same sites. I've used whatever the default FTP client is in windows, FileZilla and lftp. All without issue. The servers themselves aren't the same FTP server software from what I can tell. One is Microsoft FTP, the other I'm uncertain on but is definitely not Microsoft.
Any idea what could cause an FTP client to timeout when waiting for a NLST response on an empty directory? The visible responses from the FTP server appear to be the same, but is there a difference in how NLST responds for an empty directory that I'm unaware of?
This problem is consistent on these two servers. Everything functions fine on directories with files or subdirectories within it, but not when empty.
Any thoughts or directions would be appreciated.
Thanks!
Eric Sipple
|
I tried this in WebMethods IS Version 6.5 Updates WmPRT\_6-5-1\_SP1, IS\_6-5\_SP3.
It worked perfectly first time.
I turned on debugging on the FTP server (Debian's default ftpd). WebMethods' NLST honours the active/passive parameter passed to it.
There's nothing special about the NLST command, nor its correct behaviour with an empty directory -- if LIST works, then so should RETR, STOR and NLST. If NLST works with a non-empty directory, it should work with an empty one.
So my guess is that either:
* Your version of WM has a bug mine doesn't
* Your FTP server has a bug mine doesn't
* There's a wacky protocol-aware firewall in your system that doesn't like FTP data sockets with no data in them.
Firewall vendors are a bit wayward when it comes to FTP...
When testing with other clients, make sure it's from the same machine on which WebMethods Integration Server is running.
Just for the record, here's what should happen for an active NLST
* client opens a listening socket, and sends a PORT command with that socket's details
* client sends NLST command
* server connects to client's listening socket (this is the data socket)
* server transmits listing over data socket (in this case, zero bytes)
* server closes data socket
... and in passive mode
* client sends PASV command
* server opens a listening socket, and replies with PASV response containing its details
* client connects to listening socket (this is the data socket)
* client sends NLST command
* server transmits listing over data socket (zero bytes again)
* server closes data socket
|
I am not sure if it was the same problem but I had similar symptoms a while ago using another FTP client in Java (commons.net). The problem turned out to be caused by the active/passive mode of the connection.
I am sorry I can't give you more details, that's all I can remember... hope that help.
|
FTP Timeout on NLST when directory is empty
|
[
"",
"java",
"ftp",
"webmethods",
""
] |
I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created.
How can I make the dialog box show something like this:
```
There was an error. Go to this page to fix it.
wwww.TheWebPageToFix.com
```
Thanks.
|
You could try asking them if they wish to visit via window.prompt:
```
if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))
location.href='http://www.google.ca/';
```
Also, Internet Explorer supports modal dialogs so you could try showing one of those:
```
if (window.showModalDialog)
window.showModalDialog("mypage.html","popup","dialogWidth:255px;dialogHeight:250px");
else
window.open("mypage.html","name","height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes");
```
|
You can't. Alert boxes don't support html. You should display the error as part of the page, it's nicer than JS alerts anyway.
|
How do I put a link to a webpage in a JScript Alert dialog box?
|
[
"",
"javascript",
"alert",
""
] |
How can you implement trackbacks on a custom-coded blog (written in C#)?
|
The TrackBack specification was created by Six Apart back in the day for their [Movable Type](http://www.movabletype.org/) blogging system. After some corporate changes it seems to be no longer available, but here's an archived version:
<http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/trackback_spec>
|
Personally, I wouldn't. Trackbacks became completely unusable years ago from all the spammers and even Akismet hasn't been enough to drag them back to usable (obviously IMO). The best way I've seen to handle trackbacks any more is to have a function that will turn an article's "referrer" (you are tracking those, right?) into a trackback (probably as a customized comment type). This leverages the meat-space processing that guarantees that no spam gets through and still allows you to easily recognize and enable further discussion.
|
How can you implement trackbacks on a custom-coded blog (written in C#)?
|
[
"",
"c#",
"blogs",
"trackback",
""
] |
I am working on an application for college music majors. A feature i am considering is slowing down music playback without changing its pitch. I have seen this done in commercial software, but cannot find any libraries or open source apps that do anything like this.
1. Are there libraries out there?
2. How could this be done from scratch from various file formats?
Note: I am working in java but am not oppossed to changing languages.
|
Timestretching is quite hard. The more you slow down or speed up the sound the more artifacts you get. If you want to know what they sound like listen to "The Rockafeller Skank" by Fat Boy Slim. There are a lot of ways to do it that all have their own strengths and weaknesses. The math can get really complex. That's why there are so many proprietary algorithms.
This page explains things a bit clearer than I can and links to the Dirac library.
<http://www.dspdimension.com/admin/time-pitch-overview/>
I found this link for java code to do pitch shifting/timestretching
[http://www.adetorres.com/keychanger/KeyChangerReadme.html](http://web.archive.org/web/20081103052639/http://www.adetorres.com/keychanger/KeyChangerReadme.html)
|
I use [soundstretch](http://www.iki.fi/oparviai/soundtouch) to speed up podcasts which is works quite well, haven't tried it on music though.
|
Slowing down the playback of an audio file without changing its pitch?
|
[
"",
"java",
"audio",
"media",
""
] |
I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?
I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class?
|
To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.
What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this...
```
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
public override string Text
{
get { return _string; }
set { _string = value; }
}
```
Another nice one they provide for you is the ability to edit an array of strings...
```
[Editor("System.Windows.Forms.Design.StringArrayEditor,
System.Design, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor))]
public string[] Lines
{
get { return _lines; }
set { _lines = value; }
}
```
|
You can control whether the PropertyGrid displays a simple edit box, a drop-down arrow, or an ellipsis control.
Look up EditorAttribute, and follow it on from there. I did have a sample somewhere; I'll try to dig it out.
|
How do I change the type of control that is used in a .NET PropertyGrid
|
[
"",
"c#",
".net",
"windows",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.