Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Does anybody know of anything that exists in the Java world to map midi note numbers to specific note names and octave numbers. For example, see the reference table:
<http://www.harmony-central.com/MIDI/Doc/table2.html>
I want to map a midi note number 60 to it's corresponding note name (MiddleC) in octave 4. I could write a utility class/enum for this, but it would be rather tedious. Does anybody know of anything?
I'm specifically using this to write a Tenori-On/Monome clone in Java, so far so good...
**Solution**
This was what I ended up using:
```
String[] noteString = new String[] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
int octave = (initialNote / 12) - 1;
int noteIndex = (initialNote % 12);
String note = noteString[noteIndex];
``` | I'm not convinced your suggestion is *that* tedious. It's really just a divide-and-modulo operation, one gets the octave, the other gets the note.
```
octave = int (notenum / 12) - 1;
note = substring("C C#D D#E F F#G G#A A#B ",(notenum % 12) * 2, 2);
```
In real Java, as opposed to that pseudo-code above, you can use something like:
```
public class Notes {
public static void main(String [] args) {
String notes = "C C#D D#E F F#G G#A A#B ";
int octv;
String nt;
for (int noteNum = 0; noteNum < 128; noteNum++) {
octv = noteNum / 12 - 1;
nt = notes.substring((noteNum % 12) * 2, (noteNum % 12) * 2 + 2);
System.out.println("Note # " + noteNum + " = octave " + octv + ", note " + nt);
}
}
}
``` | In [JFugue](http://www.JFugue.org), the `Note` class has a utility method that does exactly this - see `public static String getStringForNote(byte noteValue)`.
**EDIT:** As of JFugue 5.0 and later, the `Note` class has several utility methods for getting a string representation from a MIDI note value:
* `getToneString(byte noteValue)` converts a value of
`60` to the string `C5`
* `getToneStringWithoutOctave(byte noteValue)` converts a value of `60` to the string `C`
* `getPercussionString(byte noteValue)` converts a
value of `60` to the string `"[AGOGO]"`
These replace the original `getStringForNote()` method. | Convert Midi Note Numbers To Name and Octave | [
"",
"java",
"audio",
"midi",
"javasound",
""
] |
I’m moving some old code over to the new msqli interface using prepared statements, I’m having trouble with SQL statements containing the IN clause. I would just normally do this:
```
$ids = '123,535,345,567,878'
$sql = "SELECT * FROM table WHERE id IN ($ids)";
$res = mysql_query($sql);
```
Converting this to mysqli and prepared statements I have tried a number of solutions:
```
$ids = '123,535,345,567,878'
$ids = implode($ids,',');
$result = $msqli->prepare("SELECT foo,blar FROM table WHERE id IN (?));
$result->bind_param("i", $ids);
$result->execute();
```
The above fails and calculating the number of elements in the array and altering number of question marks in the SQL string and calling bind\_parm for each element in the array also fails. Just using the comma separated string also fails.
I can find no good documentation in Google on this, so how have you solved the problem? | Look at the answer to a similar question that has been asked here before (second code sample):
[I have an array of integers, how do I use each one in a mysql query (in php)?](https://stackoverflow.com/questions/330268/i-have-an-array-of-integers-how-do-i-use-each-one-in-a-mysql-query-in-php)
It boils down to:
* create the SQL string with the right amount of question marks
* use `call_user_func_array()` to bind your array to the query string | It's not possible to bind a list of variable length to a single bound variable.
Similarly, if you were to bind the string `$ids` you'll actually end up with:
```
SELECT foo,blar FROM table WHERE id IN ('123,535,345,567,878')
```
(Note the quotes around the list of IDs).
Creating your own query with the right number of question marks and bound parameters should have actually worked - you may need to try that again and report on the actual error.
Alternatively, this may be one of those occasions where it's unfortunately necessary to hand-craft your own SQL and not use bound parameters. | How do you use IN clauses with mysqli prepared statements | [
"",
"php",
"mysqli",
"sql-in",
""
] |
Named [local classes](http://java.sun.com/docs/books/jls/third_edition/html/statements.html#247766) are very rarely used, usually local classes are anonymous. Does anybody know why the code below generates a compiler warning?
```
public class Stuff<E> {
Iterator<E> foo() {
class InIterator implements Iterator<E> {
@Override public boolean hasNext() { return false; }
@Override public E next() { return null; }
@Override public void remove() { }
}
return new InIterator();
}
}
```
The warning is in `new InIterator()` and it says
```
[unchecked] unchecked conversion
found : InIterator
required: java.util.Iterator<E>
```
If the class, unchanged, is made anonymous, or if it is made a member, the warning goes away. However, as a named local class, it requires a declaration `class InIterator<E> implements ...` for the warning to go away.
What's going on? | I am now convinced that it's a javac bug. The solutions above that add a generic parameter to InIterator that either hides or replaces E aren't helpful, because they preclude the iterator from doing something useful, like returning an element of type E - Stuff's E.
However this compiles with no warnings (thanks Jorn for the hint):
```
public class Stuff<E> {
E bar;
Iterator<E> foo() {
class InIterator<Z> implements Iterator<E> {
@Override public boolean hasNext() { return false; }
@Override public E next() { return bar; }
@Override public void remove() { }
}
return new InIterator<Void>();
}
}
```
Definitely a bug. | I believe what's happening is you are ignoring the generic type argument by naming `InIterator` without a reference to the generic in the signature (even though it is present in the interface).
This falls into the category of silly compiler warnings: you've written the class so that 100% `InIterator` instances will implement `Iterator<E>`, but the compiler doesn't recognize it. (I suppose this depends on the compiler. I don't see the warning in my Eclipse compiler, but I know that the Eclipse compiler handles generics slightly differently than the JDK compiler.)
I argue that this is less clear, and less close to what you mean, but perhaps more compiler friendly, and ultimately equivalent:
```
public class Stuff<E> {
Iterator<E> foo() {
class InIterator<F> implements Iterator<F> {
@Override public boolean hasNext() { return false; }
@Override public E next() { return null; }
@Override public void remove() { }
}
return new InIterator<E>();
}
}
``` | Java - local class and generics, why compiler warning? | [
"",
"java",
"generics",
"inner-classes",
""
] |
I'm using
`echo date('H:i:s')." this step time\n";`
in order to know how much time needs for each function in order to be executed.
How can I know the time with microseconds also? | Just to add, there's PHP's [microtime()](http://www.php.net/microtime) function, which can be used like this:
```
$time_start = microtime(true);
//do stuff here
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "It took $time seconds\n";
``` | ```
u Microseconds (added in PHP 5.2.2)
```
Take a look at [<http://no.php.net/manual/en/function.date.php>](http://no.php.net/manual/en/function.date.php) for more information. | php microseconds | [
"",
"php",
"datetime",
""
] |
I'm currently trying to use the YouTube API as part of a jQuery plugin and I've run into a bit of a problem.
The way the YT api works is that you load the flash player and, when it's ready it will send a call back to a global function called `onYouTubePlayerReady(playerId)`. You can then use that id combined with `getElementById(playerId)` to send javascript calls into the flash player (ie, `player.playVideo();`).
You can attach an event listener to the player with `player.addEventListener('onStateChange', 'playerState');` which will send any state changes to another global function (in this case `playerState`).
The problem is I'm not sure how to associate a state change with a specific player. My jQuery plugin can happily attach more than one video to a selector and attach events to each one, but the moment a state actually changes I lose track of which player it happened in.
I'm hoping some example code may make things a little clearer. The below code should work fine in any html file.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="application/text+html;utf-8"/>
<title>Sandbox</title>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.0");
</script>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/tags/rc3/swfobject/src/swfobject.js"></script>
<script type="text/javascript">
(function($) {
$.fn.simplified = function() {
return this.each(function(i) {
var params = { allowScriptAccess: "always" };
var atts = { id: "ytplayer"+i };
$div = $('<div />').attr('id', "containerplayer"+i);
swfobject.embedSWF("http://www.youtube.com/v/QTQfGd3G6dg&enablejsapi=1&playerapiid=ytplayer"+i,
"containerplayer"+i, "425", "356", "8", null, null, params, atts);
$(this).append($div);
});
}
})(jQuery);
function onYouTubePlayerReady(playerId) {
var player = $('#'+playerId)[0];
player.addEventListener('onStateChange', 'playerState');
}
function playerState(state) {
console.log(state);
}
$(document).ready(function() {
$('.secondary').simplified();
});
</script>
</head>
<body>
<div id="container">
<div class="secondary">
</div>
<div class="secondary">
</div>
<div class="secondary">
</div>
<div class="secondary">
</div>
</div>
</body>
</html>
```
You'll see the console.log() outputtin information on the state changes, but, like I said, I don't know how to tell which player it's associated with.
Anyone have any thoughts on a way around this?
EDIT:
Sorry, I should also mentioned that I have tried wrapping the event call in a closure.
```
function onYouTubePlayerReady(playerId) {
var player = $('#'+playerId)[0];
player.addEventListener('onStateChange', function(state) {
return playerState(state, playerId, player); } );
}
function playerState(state, playerId, player) {
console.log(state);
console.log(playerId);
}
```
In this situation `playerState` never gets called. Which is extra frustrating. | Edit:
Apparently calling `addEventListener` on the `player` object causes the script to be used as a string in an XML property that's passed to the flash object - this rules out closures and the like, so it's time for an old-school ugly hack:
```
function onYouTubePlayerReady(playerId) {
var player = $('#'+playerId)[0];
player.addEventListener('onStateChange', '(function(state) { return playerState(state, "' + playerId + '"); })' );
}
function playerState(state, playerId) {
console.log(state);
console.log(playerId);
}
```
Tested & working! | Im Using Jquery SWFobject plugin, [SWFobject](http://jquery.thewikies.com/swfobject/)
It is important to add &enablejsapi=1 at the end of video
HTML:
```
<div id="embedSWF"></div>
```
Jquery:
```
$('#embedSWF').flash({
swf: 'http://www.youtube.com/watch/v/siBoLc9vxac',
params: { allowScriptAccess: "always"},
flashvars: {enablejsapi: '1', autoplay: '0', allowScriptAccess: "always", id: 'ytPlayer' },
height: 450, width: 385 });
function onYouTubePlayerReady(playerId) {
$('#embedSWF').flash(function(){this.addEventListener("onStateChange", "onPlayerStateChange")});
}
function onPlayerStateChange(newState) {
alert(newState);
}
```
onYouTubePlayerReady must be outside of $(document).ready(function() to get fired | Using Youtube's javascript API with jQuery | [
"",
"javascript",
"jquery",
"api",
"events",
"youtube",
""
] |
A friend of mine was talking about a word game she liked to play where you try to convert one word to another (they have the same number of letters) by switching one letter at a time, where each iteration produces a real word.
Example:
> MOON --> WOLF
> GOON
> GOOF
> GOLF
> WOLF
I figured it'd be a fun little project to write a program to generate solutions, and taking it further, given 2 words, determine if a solution exists and the number of iterations in optimal solution.
Problem is I'm having trouble finding free word lists that I can easily access programmatically. I'm also thinking about using this as an excuse to learn Python, so it'd be great if anyone knows of free word lists and pointers on how to parse and access it from Python. The algorithm for figuring out how to find an optimal path I'll work on my own. | Options:
1. Look for /usr/share/dict/words on your common or garden variety Unix install.
2. <http://www.ibiblio.org/webster/>
3. <http://wordlist.sourceforge.net/>
4. <http://svnweb.freebsd.org/csrg/share/dict/> (click the 'revision' tag of the file 'words')
`#4` is the one I used for my own [Python experiment](https://stackoverflow.com/questions/746082/how-to-find-list-of-possible-words-from-a-letter-matrix-boggle-solver) into word games, and it worked nicely.
For bonus points, here's something to get you started on your word program:
```
import re
startwith = "MOON"
endwith = "GOLF"
cklength = re.compile('.{' + str(len(startwith)) + '}(\n)?$', re.I)
filename = "C:/dict.txt"
words = set(x.strip().upper() for x in open(filename) if x.match(cklength))
```
Words will then be a set of all 4 letter words in the dictionary. You can do your logic from there. | Most unix (which includes osx) have a file `/usr/share/dict/words`. | Free word list for use programmatically? | [
"",
"python",
"dictionary",
"word-list",
""
] |
I'm playing around with Reflection and I thought I'd make something which loads a class and prints the names of all fields in the class.
I've made a small hello world type of class to have something to inspect:
```
kent@rat:~/eclipsews/SmallExample/bin$ ls
IndependentClass.class
kent@rat:~/eclipsews/SmallExample/bin$ java IndependentClass
Hello! Goodbye!
kent@rat:~/eclipsews/SmallExample/bin$ pwd
/home/kent/eclipsews/SmallExample/bin
kent@rat:~/eclipsews/SmallExample/bin$
```
Based on the above I draw two conclusions:
* It exists at /home/kent/eclipsews/SmallExample/bin/IndependentClass.class
* It works! (So it must be a proper .class-file which can be loaded by a class loader)
Then the code which is to use Reflection: (Line which causes an exception is marked)
```
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class InspectClass {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
URL classUrl;
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/IndependentClass.class");
URL[] classUrls = { classUrl };
URLClassLoader ucl = new URLClassLoader(classUrls);
Class c = ucl.loadClass("IndependentClass"); // LINE 14
for(Field f: c.getDeclaredFields()) {
System.out.println("Field name" + f.getName());
}
}
}
```
But when I run it I get:
```
Exception in thread "main" java.lang.ClassNotFoundException: IndependentClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at InspectClass.main(InspectClass.java:14)
```
My questions:
1. What am I doing wrong above? How do I fix it?
2. Is there a way to load several class files and iterate over them? | From the [Javadocs for the `URLClassLoader(URL[])` constructor](http://docs.oracle.com/javase/6/docs/api/java/net/URLClassLoader.html#URLClassLoader%28java.net.URL%5B%5D%29):
> Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader. The URLs will be searched in the order specified for classes and resources after first searching in the parent class loader. **Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed.**
So you have two options:
1. Refer to the directory that the .class file is in
2. Put the .class file into a JAR and refer to that
(1) is easier in this case, but (2) can be handy if you're using networked resources. | You must provide the directories or the jar files containing your .class files to the URLClassLoader:
```
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/");
```
And yes, you can load as many classes as you like | How to use URLClassLoader to load a *.class file? | [
"",
"java",
"reflection",
""
] |
Just finished a little app that I want to distribute and at the moment for windows platform it is just an executable jar. Is there anyway to give this jar another image than the java cup?
Thanks | I think you're referring to the way that the jar file shows up in Windows Explorer? If so, it's probably an OS setting (needing intervention on a machine-by-machine basis). | If you are talking about the image in whatever file manager you are using, then it is provider by your OS. If you are talking about the icon in the application's window, you can change it with Window.setIconImage | Give an Executable Jar a Custom Image | [
"",
"java",
"jar",
"executable-jar",
""
] |
I have an application that I'm working on and I allow the user to select a printer to use as their printer while printing forms from the application. I'm using .NET 2.0
In the settings screen, I call
```
System.Drawing.Printing.PrinterSettings.InstalledPrinters
```
to get the list of available printers.
On a client's machine, the property throws an exception:
```
System.ComponentModel.Win32Exception: The RPC server is unavailable
```
The client is reporting that windows shows his printer as 'ready', and the client can print test pages from the printer. But, I have not been able to reproduce this issue locally and I'm running out of ideas. Does anyone have any ideas what could cause this issue? Any ideas or directions to look would be helpful. Thanks | If you can print, most likely a security issue. Otherwise I would have voted "dead spooler service" but more likely your app doesn't have the rights to communicate with the spooler service... | This same thing is happening to me in Windows 7. Stopping and starting the print spooler in **services** fixes until it happens again.
The following commands make it quick to do this:
```
net stop "print spooler"
net start "print spooler"
```
Note: Run the command prompt as Admin. I made a batch file to do this because it happens 4-5 times a day during development. | What causes System.Drawing.Printing.PrinterSettings.InstalledPrinters to throw Win32Exception "RPC server not available"? | [
"",
"c#",
".net",
"printing",
""
] |
Why must I initialize variables inside methods?
```
int test1; // Not initialized, but OK
public int Foo()
{
int test2; // Not initialized
int test3 = test1; // OK
int test4 = test2; // An error
}
``` | Fields are automatically initialized to the logical zero for the type; this is implicit. Variables must obey "definite assignment", so **must** be assigned before they can be read.
ECMA 334v4
> §17.4.4 Field initialization
>
> The initial value of a field, whether
> it be a static field or an instance
> field, is the default value (§12.2) of
> the field’s type. It is not possible
> to observe the value of a field before
> this default initialization has
> occurred, and a field is thus never
> "uninitialized".
and
> §12. Variables
>
> ...
> A variable shall be definitely assigned (§12.3) before its
> value can be obtained.
> ... | Extending Mark's answer, local variable initialization is also related to the **verification process**.
The CLI requires that in any verifiable code (that is, modules that didn't explicitly asked to skip the verification process using the SkipVerfication property from the [SecurityPermission](http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermissionattribute%28VS.80%29.aspx) attribute), all local variables must be initialized before their usage. Failing to do so will result in a [VerficationException](http://msdn.microsoft.com/en-us/library/system.security.verificationexception.aspx) being thrown.
More interestingly, is that the compiler automatically adds the `.locals init` flag on every method that uses local variables. This flag causes the JIT compiler to generate code that initializes all of the local variables to their default values. Meaning, even though you have already initialized them in your own code, the JIT will comply with the `.locals init` flag and generate the proper initialization code. This "duplicate initialization" doesn't effect performance since in configurations that allow optimizations, the JIT compiler will detect the duplication and effectively treat it as "dead code" (the auto-generated initialization routine will not appear in the generated assembler instructions).
According to Microsoft (also, backed up by [Eric Lippert](https://stackoverflow.com/users/88656/eric-lippert) in response to a question on his blog), on most occasions, when programmers don't initialize their local variable, they don't do so because they rely on the underlying environment to initialize their variable to their default values, but only because they "forgot", thus, causing sometimes-illusive logical bugs.
So in order to reduce the probability for bugs of this nature to appear in C# code, the compiler still insists you will initialize your local variables. Even though it's going to add the `.locals init` flag to the generated [CIL](https://en.wikipedia.org/wiki/Common_Intermediate_Language) code.
A more comprehensive explanation on this subject can be found here: [Behind The .locals init Flag](http://www.liranchen.com/2010/07/behind-locals-init-flag.html) | Why must local variables have initial values? | [
"",
"c#",
""
] |
Is there a smart way to check whether output has already been sent to the browser and sending a header would generate a PHP\_WARNING?
Obviously there's the alternative of using an output buffer, but that's not always an option. | You can use the headers\_sent() method. This because before anything is outputted, the headers will be send first. | [headers\_sent()](https://www.php.net/manual/en/function.headers-sent.php) does a poor job and doesn't always return TRUE in case the output has been sent (e.g. notices and warnings).
As an alternative, I use this:
```
<?php
$obStatus = ob_get_status();
if ($obStatus['buffer_used'] > 0) {
echo 'Content was sent';
} else {
echo 'Content was NOT sent';
}
``` | Check whether content already sent in PHP | [
"",
"php",
"http-headers",
""
] |
I understand the advantages of using the EventHandler/EventArgs pattern for events, it does however add a lot of overhead.
```
public class FooBarEventArgs : EventArgs
{
public int Arg1 { get; set; }
public string Arg2 { get; set; }
}
public event EventHandler<FooBarEventArgs> FooBar;
```
Would you break the event pattern for internal events?
```
internal event Action<int, string> FooBar;
```
Or would it be better to expose the delegate directly?
```
internal Action<int, string> FooBar;
``` | Consider it isn't really that much overhead. Also note that the property names will provide extra information for the caller, which is something you don't have when using the Action delegate like that. | I think sticking to common patterns is always the best option. Even if it introduces an overhead, it will be easier to understand and maintain the code in the future. You never know who will end up maintaining your code, and you'll do him/her a favor by not using such "shortcuts". | Should I follow the Event Pattern for internal events? | [
"",
"c#",
".net",
""
] |
From what I understand there is no SMTP server in IIS on Vista. I am working on a project which will require me to send email. I'd like to start with some simple prototypes on my development box which is running Vista Ultimate. I'm not connected to a corporate network where I can just use an exchange server someplace.
I realize that there are several smtp servers that I can install, but I'm not sure what to do once I install one. I know how to write the code to send the email, but I don't know what kind of configuration needs to be done to use the smtp server.
What I'd like is a clear description of what to do once I get an smtp server installed on my Vista box.
Thanks!
UPDATE: I downloaded this smtp server: <http://softstack.com/freesmtp.html>
Here's what my code looks like:
```
class Program
{
static void Main(string[] args)
{
MailMessage message = new MailMessage();
message.From = new MailAddress("tad@myconsoleapp.com");
message.To.Add(new MailAddress("terry.donaghe@gmail.com"));
//message.To.Add(new MailAddress("recipient3@foo.bar.com"));
//message.CC.Add(new MailAddress("carboncopy@foo.bar.com"));
message.Subject = "This is my subject";
message.Body = "This is the content";
SmtpClient client = new SmtpClient("localhost");
client.Send(message);
Console.ReadLine();
}
}
```
When I have this smtp server running and I execute my console app, it hands on the client.send line. The smtp server looks like this:
<http://screencast.com/t/2B7jv0bE14>
After a while the client.send times out.
Any ideas what's going wrong now?
Thanks! | As you know SMTP no longer ships with Vista (Which is one of my biggest complaints about Vista). As you already know there are many options out there, and if you found a good free one post a link to it. How you configure it will probally depend on the server you install.
I played around with some trial smtp servers, and all the ones I used started listening on the standard SMTP ports on the loopback IP Address. I believe this is the default MailSettings, and shouldn't require any changes.
I no longer have any SMTP server and am using the Pickup Directory mode. This causes the mail library to output a file which I can then inspect.
To configure this use the following in your config file:
```
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory
pickupDirectoryLocation="c:\maildrop"/>
</smtp>
</mailSettings>
</system.net>
```
If you want to configure it to connect to port 25 on your local host you would this for the SMTP section:
```
<smtp deliveryMethod="Network">
<network defaultCredentials="true" host="localhost" port="25"/>
</smtp>
```
# Edit
Terry asked a good question about using the drop location. I only use this for testing, as our production server has an SMTP server which I connect to, and send the email through; however, some SMTP servers can be configured to watch a directory and will pick up and mail anything in there.
I don't think this feature was meant to be used only for testing but it works nicely. The files that get generated can be opened in various mail clients so you can see how they would render them. I belive they .eml files but I can't remember. | You could use an externally hosted SMTP server. I have found that a lot of email system will block access if the originating SMTP server is behind a dynamic IP address (like most residential systems).
I had to do this recently.
```
SmtpClient smtp = new SmtpClient("smtp.myserver.com");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("Username", "Password");
```
Using the "SendCompleted" event, you can send the email in the background without delaying the application. | How do I set up smtp on Vista so I can use System.Net.Mail? | [
"",
"c#",
".net",
"email",
"windows-vista",
"smtp",
""
] |
If you have the following class as a network packet payload:
class Payload
{
char field0;
int field1;
char field2;
int field3;
};
Does using a class like Payload leave the recipient of the data susceptible to alignment issues when receiving the data over a socket? I would think that the class would either need to be reordered or add padding to ensure alignment.
Either reorder:
```
class Payload
{
int field1;
int field3;
char field0;
char field2;
};
```
or add padding:
```
class Payload
{
char field0;
char pad[3];
int field1;
char field2;
char pad[3];
int field3;
};
```
If reordering doesn't make sense for some reason, I would think adding the padding would be preferred since it would avoid alignment issues even though it would increase the size of the class.
What is your experience with such alignment issues in network data? | You should look into [Google protocol buffers](http://code.google.com/apis/protocolbuffers/docs/overview.html), or Boost::serialize like another poster said.
If you want to roll your own, please do it right.
If you use types from stdint.h (ie: `uint32_t, int8_t,` etc.), and make sure every variable has "native alignment" (meaning its address is divisible evenly by its size (`int8_t`s are anywhere, `uint16_t`s are on even addresses, `uint32_t`s are on addresses divisble by 4), you won't have to worry about alignment or packing.
At a previous job we had all structures sent over our databus (ethernet or CANbus or byteflight or serial ports) defined in XML. There was a parser that would validate alignment on the variables within the structures (alerting you if someone wrote bad XML), and then generate header files for various platforms and languages to send and receive the structures. This worked *really* well for us, we *never* had to worry about hand-writing code to do message parsing or packing, and it was guaranteed that all platforms wouldn't have stupid little coding errors. Some of our datalink layers were pretty bandwidth constrained, so we implemented things like bitfields, with the parser generating the proper code for each platform. We also had enumerations, which was very nice (you'd be surprised how easy it is for a human to screw up coding bitfields on enumerations by hand).
Unless you need to worry about it running on 8051s and HC11s with C, or over data link layers that are very bandwidth constrained, you are not going to come up with something better than protocol buffers, you'll just spend a lot of time trying to be on par with them. | Correct, blindly ignoring alignment can cause problems. Even on the same operating system if 2 components were compiled with different compilers or different compiler versions.
It is better to...
1) Pass your data through some sort of serialization process.
2) Or pass each of your primitives individually, while still paying attention to byte ordering == [Endianness](http://en.wikipedia.org/wiki/Endianness)
A good place to start would be [Boost Serialization](http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html). | Should network packet payload data be aligned on proper boundries? | [
"",
"c++",
"c",
"network-programming",
"sockets",
"payload",
""
] |
### Duplicate:
> [Is it possible to make a parameter implement two interfaces?](https://stackoverflow.com/questions/772053/is-it-possible-to-make-a-parameter-implement-two-interfaces)
---
Looking for a way to do this :
```
public interface INumber1 {}
public interface INumber2 {}
public class TestObject : INumber1, INumber2 {}
public static class TestClass
{
public static void TestMethod(INumber1&INumber2 testobject)
{
...
}
}
```
Calling the TestMethod :
```
TestClass.TestMethod(new TestObject());
```
The thing is that I need a parameter to contain methods from both INumber1 and INumber2.
Tips? | Try this one:
```
public static void TestMethod<T>(T testObject) Where T:INumber,INumber2
{
}
``` | Create a common interface. | C# Accept object with Interface1 and Interface2 | [
"",
"c#",
"interface",
""
] |
What is the difference between `a.Equals(b)` and `a == b` for value types, reference types, and strings? It would seem as though a == b works just fine for strings, but I'm trying to be sure to use good coding practices. | From [**When should I use Equals and when should I use ==**](https://blogs.msdn.microsoft.com/csharpfaq/2004/03/29/when-should-i-use-and-when-should-i-use-equals/):
> The Equals method is just a virtual
> one defined in System.Object, and
> overridden by whichever classes choose
> to do so. The == operator is an
> operator which can be overloaded by
> classes, but which usually has
> identity behaviour.
>
> For reference types where == has not
> been overloaded, it compares whether
> two references refer to the same
> object - which is exactly what the
> implementation of Equals does in
> System.Object.
>
> Value types do not provide an overload
> for == by default. However, most of
> the value types provided by the
> framework provide their own overload.
> The default implementation of Equals
> for a value type is provided by
> ValueType, and uses reflection to make
> the comparison, which makes it
> significantly slower than a
> type-specific implementation normally
> would be. This implementation also
> calls Equals on pairs of references
> within the two values being compared.
```
using System;
public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}
```
The result of this short sample program is
```
True
True
False
True
``` | [Here is a great blog post about *WHY* the implementations are different](http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx).
Essentially == is going to be bound at compile time using the types of the variables and .Equals is going to be dynamically bound at runtime. | What is the difference between .Equals and == | [
"",
"c#",
".net",
"string",
""
] |
I frequently hear/read the following advice:
Always make a copy of an event before you check it for `null` and fire it. This will eliminate a potential problem with threading where the event becomes `null` at the location right between where you check for null and where you fire the event:
```
// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;
if (copy != null)
copy(this, EventArgs.Empty); // Call any handlers on the copied list
```
*Updated*: I thought from reading about optimizations that this might also require the event member to be volatile, but Jon Skeet states in his answer that the CLR doesn't optimize away the copy.
But meanwhile, in order for this issue to even occur, another thread must have done something like this:
```
// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...
```
The actual sequence might be this mixture:
```
// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;
// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...
if (copy != null)
copy(this, EventArgs.Empty); // Call any handlers on the copied list
```
The point being that `OnTheEvent` runs after the author has unsubscribed, and yet they just unsubscribed specifically to avoid that happening. Surely what is really needed is a custom event implementation with appropriate synchronisation in the `add` and `remove` accessors. And in addition there is the problem of possible deadlocks if a lock is held while an event is fired.
So is this [Cargo Cult Programming](http://en.wikipedia.org/wiki/Cargo_cult_programming)? It seems that way - a lot of people must be taking this step to protect their code from multiple threads, when in reality it seems to me that events require much more care than this before they can be used as part of a multi-threaded design. Consequently, people who are not taking that additional care might as well ignore this advice - it simply isn't an issue for single-threaded programs, and in fact, given the absence of `volatile` in most online example code, the advice may be having no effect at all.
(And isn't it a lot simpler to just assign the empty `delegate { }` on the member declaration so that you never need to check for `null` in the first place?)
*Updated:* In case it wasn't clear, I did grasp the intention of the advice - to avoid a null reference exception under all circumstances. My point is that this particular null reference exception can only occur if another thread is delisting from the event, and the only reason for doing that is to ensure that no further calls will be received via that event, which clearly is NOT achieved by this technique. You'd be concealing a race condition - it would be better to reveal it! That null exception helps to detect an abuse of your component. If you want your component to be protected from abuse, you could follow the example of WPF - store the thread ID in your constructor and then throw an exception if another thread tries to interact directly with your component. Or else implement a truly thread-safe component (not an easy task).
So I contend that merely doing this copy/check idiom is cargo cult programming, adding mess and noise to your code. To actually protect against other threads requires a lot more work.
**Update in response to Eric Lippert's blog posts:**
So there's a major thing I'd missed about event handlers: "event handlers are required to be robust in the face of being called even after the event has been unsubscribed", and obviously therefore we only need to care about the possibility of the event delegate being `null`. *Is that requirement on event handlers documented anywhere?*
And so: "There are other ways to solve this problem; for example, initializing the handler to have an empty action that is never removed. But doing a null check is the standard pattern."
So the one remaining fragment of my question is, *why is explicit-null-check the "standard pattern"?* The alternative, assigning the empty delegate, requires only `= delegate {}` to be added to the event declaration, and this eliminates those little piles of stinky ceremony from every place where the event is raised. It would be easy to make sure that the empty delegate is cheap to instantiate. Or am I still missing something?
Surely it must be that (as Jon Skeet suggested) this is just .NET 1.x advice that hasn't died out, as it should have done in 2005?
---
**UPDATE**
As of C# 6, [the answer](https://stackoverflow.com/a/45949862/3195477) to this question is:
```
SomeEvent?.Invoke(this, e);
``` | The JIT isn't allowed to perform the optimization you're talking about in the first part, because of the condition. I know this was raised as a spectre a while ago, but it's not valid. (I checked it with either Joe Duffy or Vance Morrison a while ago; I can't remember which.)
Without the volatile modifier it's possible that the local copy taken will be out of date, but that's all. It won't cause a `NullReferenceException`.
And yes, there's certainly a race condition - but there always will be. Suppose we just change the code to:
```
TheEvent(this, EventArgs.Empty);
```
Now suppose that the invocation list for that delegate has 1000 entries. It's perfectly possible that the action at the start of the list will have executed before another thread unsubscribes a handler near the end of the list. However, that handler will still be executed because it'll be a new list. (Delegates are immutable.) As far as I can see this is unavoidable.
Using an empty delegate certainly avoids the nullity check, but doesn't fix the race condition. It also doesn't guarantee that you always "see" the latest value of the variable. | I see a lot of people going toward the extension method of doing this ...
```
public static class Extensions
{
public static void Raise<T>(this EventHandler<T> handler,
object sender, T args) where T : EventArgs
{
if (handler != null) handler(sender, args);
}
}
```
That gives you nicer syntax to raise the event ...
```
MyEvent.Raise( this, new MyEventArgs() );
```
And also does away with the local copy since it is captured at method call time. | C# Events and Thread Safety | [
"",
"c#",
"multithreading",
"events",
""
] |
Is there a more elegant way of doing this in Java?
```
String value1 = "Testing";
String test = "text goes here " + value1 + " more text";
```
Is it possible to put the variable directly in the string and have its value evaluated? | ```
String test = String.format("test goes here %s more text", "Testing");
```
is the closest thing that you could write in Java | A more elegant way might be:
```
String value = "Testing";
String template = "text goes here %s more text";
String result = String.format(template, value);
```
Or alternatively using MessageFormat:
```
String template = "text goes here {0} more text";
String result = MessageFormat.format(template, value);
```
---
Note, if you're doing this for logging, then you can avoid the cost of performing this when the log line would be below the threshold. For example with [SLFJ](http://www.slf4j.org/faq.html#logging_performance):
> The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.
```
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
``` | Inserting a Java string in another string without concatenation? | [
"",
"java",
"string",
""
] |
In a Winforms application (C#2, FX2.0, VC2008) I am using a Panel derived Control to display custom controls. The controls are arranged vertically and there are usually more than fit in the visible area of the panel.
I have drawn a litte sketch of it:
[Panel http://www.ericschaefer.org/Panel.png](http://www.ericschaefer.org/Panel.png)
Sometimes (usually after scrolling inside the panel) rectangular areas appear to have their colors inverted (green part in sketch). These areas are random in size but seem always to be at the right edge of the panel. As you can see in the sketch the arrow buttons of the panels scrollbar are also inverted, but not the thumbslider and the scroll area.
By inverted colors I mean black becomes white, white becomes black, blue becomes brown, etc...
I am out of ideas.
* Can this be caused by my application?
* Is it even possible to draw into the scrollbar arrow buttons?
* Any ideas?
**EDIT**: "[Screenshot](http://www.ericschaefer.org/Foto119.jpg)"
**EDIT**: I was wrong about the Panel. It has been a Panel in the past but it is now a UserControl. Like this:
```
public class MyPanel : UserControl
{
public MyPanel()
{
DoubleBuffered = true;
BorderStyle = BorderStyle.Fixed3D;
BackColor = Color.DarkBlue;
VScroll = true;
HScroll = false;
AutoScroll = true;
AutoScrollMargin = new Size( 0, 4 );
}
}
``` | **Solved:**
Apparently it was the fault of the touch screen driver. I can now reproduce the behaviour. If you click the "scroll down" button on any scroll bar via touch screen and hold it down for a while it keeps scrolling when you release it (the button stays pushed). After that you can click whereever you want, there will always be the "inverted colors" on the left side of the scroll bar. It happens with any application (explorer.exe!). Now it gets even better: Generally in Windows if you drag a scroll bar thumb button you can drift off of the scroll bar if you keep the mouse button pressed. But if you drift away too far the button will snap back to its original position (where you started dragging). Try it! The inverted colors rectangles are exactly as wide as the area where you can drift off without the button snapping back. I don't even try to understand this.
We installed a newer driver for the touch screen which does not keep scrolling even after you released the "scroll down" button and the issue disappeared. My blood pressure is back to normal but all the grey hair is probably not turning black I guess...
Thanks anyways... | Are you using the System.Windows.Forms.Panel ? What did you meant when u said Panel derived control ?
If you are using System.Windows.Forms.Panel then, this looks like a problem with the custom control and not the panel.
could you provide more info on the custom control, if possible ? | Winforms UserControl shows rectangles with Inverted Colors | [
"",
"c#",
".net",
"winforms",
".net-2.0",
"c#-2.0",
""
] |
I am working on a building a gallery and the goal is a low barrier of entry. My user is someone who takes pictures using their digital camera so file size would be between 200 - 400 KB per image.
The problem I am running into using the GD library is that each image when resized and uploaded use about 90MB of memory+ when the server has a 64 MB limit.
When I use ImageMagick it times out and throws an internal server error.
I am wondering if anyone has any experience with uploading/resizing such large image sizes and could give me some pointers.
Thanks,
Levi
edit: Here is my code to upload
```
/** Begin Multiple Image Upload**/
$numberImages = count($_FILES['galFile']['name'])-1;
for($i=1;$i<=$numberImages;$i++)
{
$imageName = $_FILES['galFile']['name'][$i];
$imageType = $_FILES['galFile']['type'][$i];
$imageSize = $_FILES['galFile']['size'][$i];
$imageTemp = $_FILES['galFile']['tmp_name'][$i];
$imageError = $_FILES['galFile']['error'][$i];
//Make sure it is an image
if(in_array(end(explode(".", $imageName)), $allowed))
{
//Where to upload image to
$uploadFile = $uploadDir . $imageName;
if (file_exists($uploadFile))
{
//What to do if file already exists
//Append random number to the end
$front = explode(".", $imageName);
$randomNum = rand(1,100);
$front[0] = $front[0].$randomNum;
$imageName = $front[0].".".$front[1];
$uploadFile = $uploadDir . $imageName;
}
if(move_uploaded_file($imageTemp,$uploadFile))
{
//Add $imageName to DB
$query = "INSERT INTO galleryImages VALUES(\"0\",\"$lastInsert\",\"$imageName\",\"$i\")";
mysql_query($query);
reSizePic($uploadFile);
}
}
}
```
Here is the GD code I had been using to resize:
```
function reSizePic($image)
{
$source_pic = $image;
$destination_pic = $image;
$max_width = 660;
$max_height = 500;
$src = imagecreatefromjpeg($source_pic);
list($width,$height)=getimagesize($source_pic);
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if(($width <= $max_width) && ($height <= $max_height))
{
$tn_width = $width;
$tn_height = $height;
}
elseif (($x_ratio * $height) < $max_height)
{
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
}
else
{
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
$tmp = imagecreatetruecolor($tn_width,$tn_height);
imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
imagejpeg($tmp,$destination_pic,100);
imagedestroy($src);
imagedestroy($tmp);
}
```
And this is the ImageMagick code I am using to resize:
```
$resource = NewMagickWand();
MagickReadImage($resource,$image);
MagickSetImageCompressionQuality( $resource, 100);
$resource = MagickTransformImage($resource,'0x0','660x500');
MagickWriteImage($resource, $image);
DestroyMagickWand($resource);
``` | <http://pl.php.net/imagecreatefromjpeg>
> The memory required to load an image
> using imagecreatefromjpeg() is a
> function of the image's dimensions and
> the images's bit depth, multipled by
> an overhead. It can calculated from
> this formula: Num bytes = Width \*
> Height \* Bytes per pixel \* Overhead
> fudge factor Where Bytes per pixel =
> Bit depth/8, or Bits per channel \* Num
> channels / 8.
That's about the GD part. Now the ImageMagick: have you tried a simpler approach:
```
$thumb = new Imagick('image.jpg');
$thumb->resizeImage($w,$h,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('thumb.jpg');
$thumb->destroy();
``` | Please put up the following code on the top of your php file.
ini\_set("memory\_limit","500M"); | How can I upload/resize images taken with a digital camera? | [
"",
"php",
"image",
"gd",
"imagemagick",
""
] |
I can't fetch text value with `Node.getNodeValue()`, `Node.getFirstChild().getNodeValue()` or with `Node.getTextContent()`.
My XML is like
```
<add job="351">
<tag>foobar</tag>
<tag>foobar2</tag>
</add>
```
And I'm trying to get *tag* value (non-text element fetching works fine). My Java code sounds like
```
Document doc = db.parse(new File(args[0]));
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes())
System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes())
System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
```
It prints out
```
tag type (1):
tag1
tag1
tag1
null
#text type (3):
_blank line_
_blank line_
...
```
Thanks for the help. | I'd print out the result of `an2.getNodeName()` as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.
Other than that, the javadoc for Node defines "[getNodeValue](http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html#getNodeValue())()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.
Perhaps iterate the children of your tag node and see what types are there?
Tried this code and it works for me:
```
String xml = "<add job=\"351\">\n" +
" <tag>foobar</tag>\n" +
" <tag>foobar2</tag>\n" +
"</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
```
Output was:
```
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2
``` | If your XML goes quite deep, you might want to consider using XPath, which comes with your JRE, so you can access the contents far more easily using:
```
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
```
Full example:
```
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XPathTest {
private Document document;
@Before
public void setup() throws Exception {
String xml = "<add job=\"351\"><tag>foobar</tag><tag>foobar2</tag></add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(new InputSource(new StringReader(xml)));
}
@Test
public void testXPath() throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
assertEquals("foobar", text);
}
}
``` | Getting XML Node text value with Java DOM | [
"",
"java",
"xml",
"dom",
""
] |
I'm writing a WinForms based application for Windows Mobile, targeting the CompactFramework 2.0 and coding in C#.
My application has a menu which the user can select severeral job functions from.
My question is this:
For the job specific screens, should I load a UserControl into a panel in the main form, or is it better to open a new form on top of the main form?
They both seem to meet my needs, and I don't know if there is a "right" answer here.
Is one method more correct than the other? | Forms are Controls (just look at the inheritance chain), and a Form itself doesn't have a whole lot of overhead in and of itself. It creates a native Window, but that's about it.
What should drive your decision is how you use and display your UI elements in your solution. Forms are conducive to many UI architectures, and they're what most developers are familiar with. The designer supports them well, and creating, showing, hiding and closing Forms is a well documented, often used paradigm that works just fine. Yes, you have the load penalty whenever a Form is created as it creates all of its contained controls, but you're going to pay that even if it's a UserControl. The child controls have to be created in either case.
One might argue that Forms require that you recreate them every time, but that's not true. If you use ShowDialog or Hide instead of Close, you can reuse your Forms and pay the price once. The advantage here is that the Form holds your Controls in teh collection and manages all of that for you, so you have little to worry about with the GC and remembering what roots you have alive.
The UserControl paradigm is more complex - you have to manage loading and unloading controls yourself to keep memory pressure low. Complexity also increases cost - cost to maintain, cost to support, and likely cost to develop. However there are some clear advantages to UserControls in some scenarios too. If you use an MVC/MVP pattern and some form of framework that handlesyour Views, a USerControl makes a really good View with the Form becoming the Workspace (the [SCSF for the desktop](http://msdn.microsoft.com/en-us/library/aa480482.aspx) is a classic example of this, and so is the [OpenNETCF.IoC framework](http://ioc.codeplex.com/) for the CF).
So which is "better"? It depends on how and where you're using the elements, how your team is already doing development, and how you've architected the solution you're plugging in to. In short, the is no one right answer. | In my experience, depending on your hardware, loading controls far outperforms launching distinct forms. Our devices (Motorola WT4090 with 32meg) have no hardware acceleration, and drawing complete forms seems to really tax them. There is as much as 4-6 second delay any time a form is launched; controls, however, are almost instantaneous. | CompactFramework 2.0 - forms vs. loading conrols into a panel | [
"",
"c#",
"compact-framework",
"panel",
""
] |
This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the [Wikipedia API](http://en.wikipedia.org/wiki/Wikipedia:API). I have posted my code below if anyone can help me see my problem.
```
string pgTitle = txtPageTitle.Text;
Uri address = new Uri("http://en.wikipedia.org/w/api.php");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string action = "query";
string query = pgTitle;
StringBuilder data = new StringBuilder();
data.Append("action=" + HttpUtility.UrlEncode(action));
data.Append("&query=" + HttpUtility.UrlEncode(query));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream.
StreamReader reader = new StreamReader(response.GetResponseStream());
divWikiData.InnerText = reader.ReadToEnd();
}
``` | You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:
> <http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page>
Here's the code:
```
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page");
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
string ResponseText;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ResponseText = reader.ReadToEnd();
}
}
```
**Edit:** The other problem he was experiencing on the POST request was, `The exception is : The remote server returned an error: (417) Expectation failed.` It can be solved by setting:
```
System.Net.ServicePointManager.Expect100Continue = false;
```
(This is from: [HTTP POST Returns Error: 417 "Expectation Failed."](https://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c-resolved)) | I'm currently in the final stages of implementing an C# MediaWiki API which allows the easy scripting of most MediaWiki viewing and editing actions.
The main API is here: <http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs> and here is an example of the API in use:
```
var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php");
wiki.login(userName, password);
var page = "Test"; // "Main_Page";
wiki.editPage(page,"Test content2");
var rawWikiText = wiki.raw(page);
var htmlText = wiki.html(page);
return rawWikiText.line().line() + htmlText;
``` | WebRequest to connect to the Wikipedia API | [
"",
"c#",
"mediawiki",
"webrequest",
"wikipedia",
"wikipedia-api",
""
] |
I've seen web apps with limitations for user login attempts.
Is it a security necessity and, if so, why?
For example: *you had three failed login attempts, let's try again in 10 minutes!!* | **Clarification** *This is a completion to the other answers. Using a good implemented captcha alongside an anti-bruteforce mechanism using sessions for example.
The questioner marked this as accepted assuming that captchas are unreadable by machines (she's **almost** right) and so it's getting negative points, because people think it's not a complete answer & they're right.*
---
Also using a good implemented CAPTCHA could be an alternative way to enpower your application security against brute-force attacks. there's a [wide variety of captcha providers](http://woork.blogspot.com/2009/02/10-free-captcha-scripts-and-services.html) available for free, let's try the easy way if you're in a hurry. Also please consider that there's [people](http://www.google.com/search?q=captcha+is+not+safe) outta here saying that *"oh, no! this captcha thing is not secure enough and they're right sometimes!"*.
*> "For those of you who don't know, a CAPTCHA is program that can tell whether its user is a human or another computer. They're those little images of distorted text that you translate when you sign up for Gmail or leave a comment on someone's blog. Their purpose is to make sure that someone doesn't use a computer to sign up for millions of online accounts automatically, or.." [ref](http://billthelizard.blogspot.com/2009/03/worst-captcha-ever.html).* | I saw a creative approach to this once...
For each login attempt, that fails, the lockout time increases... exponentially.
```
attempt | lockout time
======================
1 | 2s
2 | 4s
3 | 8s
4 | 16s
5 | 32s
6 | 64s
7 | 128s
8 | 256s
9 | 512s
10 | 1024s
```
In theory, it lets user make a mistake or two, but as soon as it appears to become a "hacking" attempt, the hacker gets locked out for longer and longer time periods.
I haven't used this myself (yet), but conceptually I quite like the idea. Of course on successful login, the counter is reset. | Limiting user login attempts in PHP | [
"",
"php",
"security",
"authentication",
"captcha",
"brute-force",
""
] |
I have a class that my client uses to Get() a packet. The packet contains a std::vector whose type is not known until the packet is generated internally in my Interface class (in this example, it depends on the Packet::type variable).
I was wondering if template could be used for this since the Packet class is just a generic class whose type can be pretty much anything.
The problem with it, as far as I can think of, is that the client has no clue what type of packet it is until he gets the packet and look at the Packet::type member. So, this wouldnt work because he wouldnt be able to declare a variable that Get() would return (?)
Could template be used elegantly in this case?
One alternative I could think of is to define a base class, and create a child class for each type. Then, the Get() method could return a pointer to the base class. Then client can simply look at the Packet::type (packet->type) and cast it to be the appropriate child class. But that's a bit messy? Is there a more elegant solution?
The code below demonstrates the scenario roughly:
```
enum
{
T_FLOAT,
T_COMPLEX
} TYPE_ENUM;
// T can either be of type float or std::complex
template<typename T>
class Packet
{
public:
TYPE_ENUM type;
std::vector<T> data;
};
class Interface
{
public:
// Method that client calls to obtain the packet
Packet<> Get()
{
return queue.pop(); // return current packet in queue
}
private:
Queue<Packet> queue;
};
``` | You would want to create a base class, and keep the template Packet class that you have. Call this base class PacketBase. Your Packet class would derive from the new PacketBase class. That is to say each Packet<> type that is generated at compile time, will derive from PacketBase.
```
class PacketBase
{
};
// T can either be of type float or std::complex or ...
template<typename T>
class Packet : public PacketBase
{
public:
std::vector<T> data;
//Put other members you need here
//Note you don't need the type member that you had before.
};
```
Interface::Get would return a PacketBase\*. Here PacketBase is just used as a generic name that holds any Packet<> type. The queue would store a collection of PacketBase\*.
```
class Interface
{
public:
// Method that client calls to obtain the packet
PacketBase* Get()
{
return queue.pop(); // return current packet in queue
}
private:
Queue<PacketBase*> queue;
};
```
To figure out which type of Packet you have you can use RTTI with dynamic\_cast.
```
InterfaceObject o;
//fill the queue
PacketBase *pPacket = o.Get();
if(dynamic_cast<Packet<float> * >(pPacket) != NULL)
;//You have a Packet<float>
else if(dynamic_cast<Packet<std::complex> * >(pPacket) != NULL)
;//You have a Packet<std::complex>
//... for each Packet<> type you have
```
You can also beef up your PacketBase with some virtual methods. Then you can call those directly instead of the RTTI dynamic\_cast stuff. | Templates are all about **compile time** type resolution ... if you can't determine the type until runtime then you don't have a good fit for applying templates.
You will need to have the runtime switch on the final packet type as you've described. | Should C++ template be used in this case? | [
"",
"c++",
"templates",
""
] |
I'm trying to write a regular expression for my html parser.
I want to match a html tag with given attribute (eg. `<div>` with `class="tab news selected"` ) that contains one or more `<a href>` tags. The regexp should match the entire tag (from `<div>` to `</div>`). I always seem to get "memory exhausted" errors - my program probably takes every tag it can find as a matching one.
I'm using boost regex libraries. | You may also find these questions helpful:
[Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege)
[Can you provide an example of parsing HTML with your favorite parser?](https://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser) | You should probably look at [this question](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not) re. regexps and HTML. The gist is that using regular expressions to parse HTML is not by any means an ideal solution. | How to write a regular expression for html parsing? | [
"",
"c++",
"html",
"regex",
"boost",
"html-content-extraction",
""
] |
I received a request to create a Music Player with specific features.
This Music Player will Play music in modality "Random" (first request) downloading songs from a folder and one more request is to change "Genre" of music each 4 hours for example:
* from 8am to 12am :it plays "Romantic" songs;
* from 12am to 4pm :it plays "Latin" songs;
* from 4pm to 8pm : it plays "Rock" songs;
* from 8pm to midnight : it plays "Dance" music;
My purpose is to create different song's folder for each Genre and give respective TitleName (Romantic, Latin, Rock, etc.) and when start the music player will automatic download the song's folder following the time slot.
So I ask you some advice about the code how organize these features because I don't know how change the Genre Music for hours and put the music player in modality Random. | Here's an approach.
Read all the ID3 tags for the MP3 files enqued in the playlist or folder using [C# ID3 Library](http://sourceforge.net/projects/csid3lib/) or any other ID3 tag reader for MP3 files. Probe the playlist, read ID3 tags, create a repo. Set the timer & pick a genre from your already read repo | You say that you are downloading songs from a folder, which leads me to believe that there is a server that is shuttling information to the media player.
I'd put the logic for this onto the server side. Just use whatever regular media player is out there.
Then, on the server side, generate a feed of some sort which feeds the URLs of the songs to download depending on the time of day on the server (adjusted by an offset if the client supplies one).
Then, your program would read the feed and get the urls of the songs to play, and just feed the playlist to the media player (or download the songs and feed them to the media player) based on what the server tells you. | WPF and MusicPlayer | [
"",
"c#",
".net",
"wpf",
"linq",
""
] |
I'm taking a Masters capstone course early and doing my project in C# while everyone else is doing theirs in Java. The project has 4 services and requires a name server that maps service names to sockets. The instructor is suggesting that the students use RMI to build this registry. Since I'm not very familiar with Java, and the instructor is not very familiar with .NET, we weren't able to come up with an equivalent in C#. Anyone out there aware of one?
Update:
I'm looking for a way to discover a WCF service without explicitly knowing its socket.
Update 2:
I will be demoing the project on my XP laptop using VS 2008/WebDev server. | RMI Registery in java works as a container where you can lookup services by a key. This mechanism is similar to resolving services/objects via ServiceLocator (e.g. ServiceLocator pattern) where you use a dependency injection engine, and ask it to resolve an instance of the service (i.e. by a known name, by interface, etc.):
```
IMyService service = ServiceLocator.Resolve<IMyService>();
```
or
```
IMyService service = (IMyService)ServiceLocator.Resolve(typeof(IMyservice));
```
WCF works only in a single service vs. single service host fashion, meaning each single service requires a separate service host. You can write a service container that aggregates the service hosts, opens the port, and registers them in DI container, and later simply ask for an instance of the service as mentioned above. | You can use the UDDI server that comes with Windows Server 2K3/8. This will give you discovery of your services. Other than that you would need a 3rd party package or roll your own. | Service Host Resolving - C# Equivalent to RMI Registry? | [
"",
"c#",
"service",
"rmi",
"resolution",
"registry",
""
] |
Add method Adds an object to the end of the `List<T>`
What would be a quick and efficient way of adding object to the beginning of a list? | Well, `list.Insert(0, obj)` - but that has to move everything. If you need to be able to insert at the start efficiently, consider a `Stack<T>` or a `LinkedList<T>` | ```
List<T> l = new List<T>();
l.Insert(0, item);
``` | Adding object to the beginning of generic List<T> | [
"",
"c#",
".net",
""
] |
Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?
I know it would work if they were a style attribute with `attr()`, but all of my styles are in an external style sheet. | A couple years late, but here is a solution that retrieves both inline styling and external styling:
```
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
```
Pass a jQuery object into `css()` and it will return an object, which you can then plug back into jQuery's `$().css()`, ex:
```
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
```
:) | Two years late, but I have the solution you're looking for. Not intending to take credit form the [original author](http://upshots.org/?p=192), here's a plugin which I found works exceptionally well for what you need, but gets **all** possible styles in all browsers, even IE.
**Warning:** This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
`jquery.getStyleObject.js:`
```
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
```
Basic usage is pretty simple, but he's written a function for that as well:
```
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
``` | Can jQuery get all CSS styles associated with an element? | [
"",
"javascript",
"jquery",
"css",
""
] |
I am working on a little Hardware interface project based on the Velleman k8055 board.
The example code comes in VB.Net and I'm rewriting this into C#, mostly to have a chance to step through the code and make sense of it all.
One thing has me baffled though:
At one stage they read all digital inputs and then set a checkbox based on the answer to the read digital inputs (which come back in an Integer) and then they AND this with a number:
```
i = ReadAllDigital
cbi(1).Checked = (i And 1)
cbi(2).Checked = (i And 2) \ 2
cbi(3).Checked = (i And 4) \ 4
cbi(4).Checked = (i And 8) \ 8
cbi(5).Checked = (i And 16) \ 16
```
I have not done Digital systems in a while and I understand what they are trying to do but what effect would it have to AND two numbers? Doesn't everything above 0 equate to true?
How would you translate this to C#? | I think you 'll have to translate it to this:
```
i & 1 == 1
i & 2 == 2
i & 4 == 4
```
etc...
This is using the bitwise AND operator.
When you use the bitwise AND operator, this operator will compare the binary representation of the two given values, and return a binary value where only those bits are set, that are also set in the two operands.
For instance, when you do this:
2 & 2
It will do this:
```
0010 & 0010
```
And this will result in:
```
0010
0010
&----
0010
```
Then if you compare this result with 2 (0010), it will ofcourse return true. | This is doing a [bitwise AND](http://msdn.microsoft.com/en-us/library/sbf85k1c%28VS.71%29.aspx), not a logical AND.
Each of those basically determines whether a single bit in `i` is set, for instance:
```
5 AND 4 = 4
5 AND 2 = 0
5 AND 1 = 1
```
(Because 5 = binary 101, and 4, 2 and 1 are the decimal values of binary 100, 010 and 001 respectively.) | Why AND two numbers to get a Boolean? | [
"",
"c#",
"vb.net",
"digital",
""
] |
I'm writing java application that is using both **SQLite** and **MySQL** using **JDBC.**
Are there any differences in **SQL** for those databases? Can I use same queries for both **SQLite** and **MySQL**, or is there any db specific stuff, that doesn't work on the other one?
As far I've worked only with **MySQL**, so I don't really know much about **SQLite**. | If you stick to [ANSI SQL92](http://en.wikipedia.org/wiki/SQL-92), you'll should be fine.
There are some SQL92 features missing from both MySQL and SQLite (e.g. FULL OUTER JOIN).
MySQL has both RIGHT JOIN, and LEFT JOIN, SQLite only the LEFT JOIN. SQLite doesn't support FOREIGN KEY constraints, neither does MySQL with MyISAM tables.
SQLite of course doesn't have GRANT/REVOKE, as permission system is based on underlying OS's file permissions. | I'm doing something similar. There are a few differences in addition to the ones mentioned that I ran into:
* in the newer versions of SQLite3 with the Xerial JDBC driver, foreign keys are indeed supported. SQLite supports inline foreign key constraint definition:
CREATE TABLE Blah (foreignId Integer REFERENCES OtherTable (id));
MySQL (with InnoDB) will *accept* the same syntax, but won't actually enforce the constraint unless you use a separate FOREIGN KEY clause which explicitly names the foreign table and key column(s):
CREATE TABLE Blah (foreignId INTEGER, FOREIGN KEY foreignId REFERENCES OtherTable (id));
* old versions of the SQLite JDBC driver don't support Statement.RETURN\_GENERATED\_KEYS; fixed in newer Xerial drivers.
* the syntax for auto-incrementing keys differs; SQLite: (id INTEGER PRIMARY KEY ASC, ...); MySQL: (id INTEGER PRIMARY KEY AUTO\_INCREMENT, ...)
* SQLite accepts n-way comma-delimited joins:
SELECT \* FROM A, B, C ON (A.x = B.y AND B.y = C.z);
MySQL does not; the following works in both:
SELECT \* FROM A INNER JOIN B ON A.x = B.y INNER JOIN C ON B.y = C.z;
* With respect to the type differences, a related annoyance with SQLite's JDBC drivers is that the same column can produce different types via ResultSet.getObject(.); for example, an Integer or a Long depending on the magnitude of the number contained.
* auto-incrementing keys in SQLite MUST be declared type INTEGER; in MySQL any numeric integer type works. | MySQL and SQLite differences in SQL | [
"",
"java",
"mysql",
"sqlite",
"jdbc",
""
] |
Needs to be padded to this: str\_pad($Month, 2, "0", STR\_PAD\_LEFT)
but how/where???
```
/*******creates the month selection dropdown array****/
function createMonths($id='month_select', $selected=null)
{
/*** array of months ***/
$months = array(
1=>'Jan',
2=>'Feb',
3=>'Mar',
4=>'Apr',
5=>'May',
6=>'Jun',
7=>'Jul',
8=>'Aug',
9=>'Sep',
10=>'Oct',
11=>'Nov',
12=>'Dec');
/*** current month ***/
$selected = is_null($selected) ? date('m') : $selected;
$select = '<select name="'.$id.'" id="'.$id.'">'."\n";
foreach($months as $key=>$mon)
{
$select .= "<option value=\"$key\"";
$select .= ($key==$selected) ? ' selected="selected"' : '';
$select .= ">$mon</option>\n";
}
$select .= '</select>';
return $select;
}
/********displays the month selection with current month selected/*******</br>
echo createMonths('Month', date ('m'));
/******DISPLAYS MONTH AS (4) INSTEAD OF REQUIRED (O4) --- @:( /*****</br>
echo $_POST['Month'];
``` | Well, assuming it's the value you want to be padded, it's here:
```
$select .= "<option value=\"$key\"";
```
becomes
```
$select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';
```
This assumes that you don't want it padded when you're doing the check against `$selected`, if you do, you need to do it at the beginning of the loop, overwriting the value in `$key`, and then you can use your original code, like so:
```
foreach($months as $key=>$mon)
{
$key = str_pad($key, 2, "0", STR_PAD_LEFT);
$select .= "<option value=\"$key\"";
$select .= ($key==$selected) ? ' selected="selected"' : '';
$select .= ">$mon</option>\n";
}
``` | You can use [`printf()`](http://uk.php.net/printf) or [`sprintf()`](http://uk.php.net/sprintf) with a format string:
```
$m = sprintf('%02d', (int) $_POST['Month']);
``` | How to str_pad this PHP date selection month array? | [
"",
"php",
"arrays",
"date",
"padding",
""
] |
Compiling the following code gives the error message: `type illegal`.
```
int main()
{
// Compilation error - switch expression of type illegal
switch(std::string("raj"))
{
case"sda":
}
}
```
You cannot use string in either `switch` or `case`. Why? Is there any solution that works nicely to support logic similar to switch on strings? | The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.
In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal. For items like ints and enums, this is a trivial bit comparison. But how should the compiler compare 2 string values? Case sensitive, insensitive, culture aware, etc ... Without a full awareness of a string this cannot be accurately answered.
Additionally, C/C++ switch statements are typically generated as [branch tables](http://en.wikipedia.org/wiki/Branch_table). It's not nearly as easy to generate a branch table for a string style switch. | As mentioned previously, compilers like to build lookup tables that optimize `switch` statements to near O(1) timing whenever possible. Combine this with the fact that the C++ Language doesn't have a string type - `std::string` is part of the Standard Library which is not part of the Language per se.
I will offer an alternative that you might want to consider, I've used it in the past to good effect. Instead of switching over the string itself, switch over the result of a hash function that uses the string as input. Your code will be almost as clear as switching over the string if you are using a predetermined set of strings:
```
enum string_code {
eFred,
eBarney,
eWilma,
eBetty,
...
};
string_code hashit (std::string const& inString) {
if (inString == "Fred") return eFred;
if (inString == "Barney") return eBarney;
...
}
void foo() {
switch (hashit(stringValue)) {
case eFred:
...
case eBarney:
...
}
}
```
There are a bunch of obvious optimizations that pretty much follow what the C compiler would do with a switch statement... funny how that happens. | Why can't the switch statement be applied to strings? | [
"",
"c++",
"string",
"switch-statement",
""
] |
We have a team on vs 2005. We want to upgrade to vs 2008 but want to do it incrementally. If we have a few folks on the team upgrade to 2008 (still targetting the 2.0 framework) while others working on the same solutions stay on vs 2005, would this cause any issues .
* Do solution or project files change due to this?
* Are there any backward compatibility issues to deal with or other conflicts that is going to force a big bang upgrade for the team? | Why do you want to upgrade incrementatlly? You can still target .NET 2.0 while working with Visual Studio 2008. | Won't work. 2k8 upgrades your solutions.
---
Let me qualify that. Solutions, once upgraded, can't be opened in 2005. I believe individual projects can be.
So, one solution might be to make a copy of the solution, call it project.2005.sln, then upgrade the original solution and call it project.2008.sln.
I don't have 2k5 on my box, so I can't test this. It would be simple and, as long as you check in fully beforehand, non-destructive to test this. | Using visual studio 2008 and 2005 in one group | [
"",
"c#",
"visual-studio",
""
] |
I have the following code:
```
try
{
//Create connection
SQLiteConnection conn = DBConnection.OpenDB();
//Verify user input, normally you give dbType a size, but Text is an exception
var uNavnParam = new SQLiteParameter("@uNavnParam", SqlDbType.Text) { Value = uNavn };
var bNavnParam = new SQLiteParameter("@bNavnParam", SqlDbType.Text) { Value = bNavn };
var passwdParam = new SQLiteParameter("@passwdParam", SqlDbType.Text) {Value = passwd};
var pc_idParam = new SQLiteParameter("@pc_idParam", SqlDbType.TinyInt) { Value = pc_id };
var noterParam = new SQLiteParameter("@noterParam", SqlDbType.Text) { Value = noter };
var licens_idParam = new SQLiteParameter("@licens_idParam", SqlDbType.TinyInt) { Value = licens_id };
var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" +
"VALUES ('@uNameParam', '@bNavnParam', '@passwdParam', '@pc_idParam', '@noterParam', '@licens_idParam')", conn);
insertSQL.Parameters.Add(uNavnParam); //replace paramenter with verified userinput
insertSQL.Parameters.Add(bNavnParam);
insertSQL.Parameters.Add(passwdParam);
insertSQL.Parameters.Add(pc_idParam);
insertSQL.Parameters.Add(noterParam);
insertSQL.Parameters.Add(licens_idParam);
insertSQL.ExecuteNonQuery(); //Execute query
//Close connection
DBConnection.CloseDB(conn);
//Let the user know that it was changed succesfully
this.Text = "Succes! Changed!";
}
catch(SQLiteException e)
{
//Catch error
MessageBox.Show(e.ToString(), "ALARM");
}
```
It executes perfectly, but when I view my "brugere" table, it has inserted the values: '@uNameParam', '@bNavnParam', '@passwdParam', '@pc\_idParam', '@noterParam', '@licens\_idParam' literally. Instead of replacing them.
I have tried making a breakpoint and checked the parameters, they do have the correct assigned values. So that is not the issue either.
I have been tinkering with this a lot now, with no luck, can anyone help?
Oh and for reference, here is the OpenDB method from the DBConnection class:
```
public static SQLiteConnection OpenDB()
{
try
{
//Gets connectionstring from app.config
const string myConnectString = "data source=data;";
var conn = new SQLiteConnection(myConnectString);
conn.Open();
return conn;
}
catch (SQLiteException e)
{
MessageBox.Show(e.ToString(), "ALARM");
return null;
}
}
``` | You should remove the quotes around your parameter names in the INSERT statement.
So instead of
```
VALUES ('@uNameParam', '@bNavnParam', '@passwdParam', '@pc_idParam',
'@noterParam', '@licens_idParam')
```
use
```
VALUES (@uNameParam, @bNavnParam, @passwdParam, @pc_idParam,
@noterParam, @licens_idParam)
``` | Thanks to rwwilden and Jorge Villuendas, the answer is:
```
var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" +
" VALUES (@uNavnParam, @bNavnParam, @passwdParam, @pc_idParam, @noterParam, @licens_idParam)", conn);
insertSQL.Parameters.AddWithValue("@uNavnParam", uNavn);
insertSQL.Parameters.AddWithValue("@bNavnParam", bNavn);
insertSQL.Parameters.AddWithValue("@passwdParam", passwd);
insertSQL.Parameters.AddWithValue("@pc_idParam", pc_id);
insertSQL.Parameters.AddWithValue("@noterParam", noter);
insertSQL.Parameters.AddWithValue("@licens_idParam", licens_id);
insertSQL.ExecuteNonQuery(); //Execute query
``` | System.Data.SQLite parameter issue | [
"",
"c#",
"parameters",
"system.data.sqlite",
""
] |
Would it be better to learn **C** before learning any type of WEB and desktop programming?
I don't know how to program, I want to learn Javascript and my friends suggested to me that I should learn **C** first. | No.
JavaScript may be one of the klunkiest languages ever, but it has one huge advantage over C: You can *play* with it. (I spent 10+ years coding in C. I had some fun, but I'd never call what I did "playing".)
My suggestion: Open up your favorite Web page, save it to disk, open up the JavaScript (or download it, if need be), and play. You'll learn a lot that way.
**EDIT**: Downvoters: Yes, there is a lot to like about JavaScript. But there's also a lot *not* to like. | If your intent is to learn Javascript, start with Javascript now.
The C language brings you a lot of general knowledge, but for Web programming it's better to start with HTML and Javascript. You need to answer yourself this question: 'how much time I can spend before be able to make money with programming?' | Should I learn C before learning Javascript? | [
"",
"javascript",
"c",
""
] |
My extension method is:
```
public static IEnumerable<T> FilterCultureSubQuery<T>(this Table<T> t)
where T : class
{
return t;
}
```
I tried to use it in this query
```
var test = from p in t.Products
select new
{
Allo = p,
Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
select pl)
};
```
What is supposed to be the signature of my method extension? I always get this error:
```
Method 'System.Collections.Generic.IEnumerable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' has no supported translation to SQL.
```
I also tried this signature:
```
public static IQueryable<T> FilterCultureSubQuery<T>(this Table<T> t)
where T : class
{
return t;
}
```
And I got this error:
```
Method 'System.Linq.IQueryable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' has no supported translation to SQL.
```
Thanks | When i use my extension method in a simple query, it's working, but when i use it in a sub query it's not working. Any solutions ?
Working
```
var test = from pl in t.ProductLocales.FilterCultureSubQuery() select pl;
```
Not Working
```
var test = from p in t.Products
select new
{
Allo = p,
Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
select pl)
};
```
I create a new extension method and rewrite the expression tree of the query.
```
var test = (from p in t.Products
select new
{
Allo = p,
Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery()
select pl)
}).ArrangeExpression();
```
LINQ-TO-SQL have difficulty to use extension method in subquery. With a rewrite expression extension method everyting working fine.
Any other solutions ? | The signature of your method is fine. The problem is, as stated, it "has no supported translation to SQL".
DLINQ is attempting to convert that statement into a line of SQL which it will send to the database. That method has no translation.
I'd suggest rewriting the filter using a Where clause. | LINQ-to-SQL and Extension method in subQuery | [
"",
"c#",
"linq",
"linq-to-sql",
"extension-methods",
""
] |
Can a Spring form command be a Map? I made my command a Map by extending HashMap and referenced the properties using the `['property']` notation but it didn't work.
Command:
```
public class MyCommand extends HashMap<String, Object> {
}
```
HTML form:
```
Name: <form:input path="['name']" />
```
Results in the error:
```
org.springframework.beans.NotReadablePropertyException: Invalid property '[name]' of bean class [com.me.MyCommand]: Bean property '[name]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
```
Is this not allowed or do I have incorrect syntax? | Springn MVC commands need to use JavaBeans naming conventins (ie getXXX() and setXXX()) so no you can't use a map for that.
One alternative is to have a bean with a single Map property ie:
```
public class MyCommand {
private final Map<String, Object> properties = new HashMap<String, Object>();
public Map<String, Object> getProperties() { return properties; }
// setter optional
}
```
Then you can do something like this (not 100% sure on the syntax but it is possible):
```
Name: <form:input path="properties['name']" />
``` | Combining the answer of cletus and dbell I could actually make it work and would like to share the solution with you (including binding of values when submitting the form, a flaw reported for cletus solution)
You cannot use directly a map as command, however have another domain object that needs to wrap a lazy map
```
public class SettingsInformation {
private Map<String, SettingsValue> settingsMap= MapUtils.lazyMap(new HashMap<String, SettingsValue>(),FactoryUtils.instantiateFactory(SettingsValue.class));
public Map<String, SettingsValue> getSettingsMap() {
return settingsMap;
}
public void setSettingsMap(Map<String, SettingsValue > settingsMap) {
this.settingsMap = settingsMap;
}
}
```
SettingsValue is a class that actually wraps the value.
```
public class SettingsValue {
private String value;
public SettingsValue(String value) {
this.value = value;
}
public SettingsValue() {
}
public String getValue() {
return value;
}
public void setValue(String propertyValue) {
this.value = propertyValue;
}
```
The controller method providing the model looks like this:
```
@RequestMapping(value="/settings", method=RequestMethod.GET)
public ModelAndView showSettings() {
ModelAndView modelAndView = new ModelAndView("settings");
SettingsDTO settingsDTO = settingsService.getSettings();
Map<String, String> settings = settingsDTO.getSettings();
SettingsInformation settingsInformation = new SettingsInformation();
for (Entry<String, String> settingsEntry : settings.entrySet()) {
SettingsValue settingsValue = new SettingsValue(settingsEntry.getValue());
settingsInformation.getSettingsMap().put(settingsEntry.getKey(), settingsValue);
}
modelAndView.addObject("settings", settingsInformation);
return modelAndView;
}
```
Your form should look like this
```
<form:form action="${actionUrl}" commandName="settings">
<form:input path="settingsMap['exampleKey'].value"/>
<input type="submit" value="<fmt:message key="settings.save"/>"/>
</form:form>
```
The controller method handling form submission works as usual
```
@RequestMapping(value="/settings", method=RequestMethod.POST)
public ModelAndView updateSettings(@ModelAttribute(value="settings") SettingsInformation settings) {
[...]
}
```
I verified the SettingsInformation bean is actually filled with the values in the form.
Thanks for helping me with this one; If you have any questions feel free to ask. | Can a Spring form command be a Map? | [
"",
"java",
"spring",
"spring-mvc",
""
] |
Is this the proper way to iterate over a `read` on a socket? I am having a hard time getting this to work properly. `data.size` is an `unsigned int` that is populated from the socket as well. It is correct. `data.data` is an `unsigned char *`.
```
if ( data.size > 0 ) {
data.data = (unsigned char*)malloc(data.size);
memset(&data.data, 0, data.size);
int remainingSize = data.size;
unsigned char *iter = data.data;
int count = 0;
do {
count = read(connect_fd, iter, remainingSize);
iter += count;
remainingSize -= count;
} while (count > 0 && remainingSize > 0);
}
else {
data.data = 0;
}
```
Thanks in advance. | You need to check the return value from read before you start adding it to other values.
You'll get a zero when the socket reports EOF, and -1 on error. Keep in mind that for a socket EOF is not the same as closed. | Put the read as part of the while condition.
```
while((remainingSize > 0) && (count = read(connect_fd, iter, remainingSize)) > 0)
{
iter += count;
remainingSize -= count;
}
```
This way if it fails you immediately stop the loop.
It is very common pattern to use the read as part of the loop condition otherwise you need to check the state inside the loop which makes the code uglier.
Personally:
I would move the whole above test into a separate function for readability but your milage may very.
Also using malloc (and company) is going to lead to a whole boat of memory management issues. I would use a std::vector. This also future proofs the code when you modify it to start throwing exceptions, now it will also be exception safe.
So assuming you change data.data to have a type of std::vector<unsigned char> then
```
if ( data.size > 0 )
{
std::vector<unsigned char> buffer(data.size);
unsigned char *iter = &buffer[0];
while(... read(connect_fd, iter, remainingSize) )
{
.....
}
... handle error as required
buffer.resize(buffer.size() - remainingSize);
data.data.swap(buffer);
}
``` | Iterating a read() from a socket | [
"",
"c++",
"c",
"sockets",
"tcp",
""
] |
Can someone share their experiences with s#arp architecture. we have decided to follow mvp pattern for the project. Is this okay to go with it ? The size of the project is medium. we are going to follow the tdd and ddd.
Can anybody explain how to use this architecture means explain about the layers. we don't have enough time to go through with entire documentation. if anybody expalin particle with small example in short.
please help me out!!!
Thanks,
Milind | The [S#arp Architecture](http://code.google.com/p/sharp-architecture/) combines ASP.NET MVC with other frameworks and tools like
* [NHibernate](http://www.nhibernate.org/) 2.0.1
* NHibernate.Validator
* [Fluent NHibernate](http://fluentnhibernate.org/) and
* [Castle Windsor](http://www.castleproject.org/container/index.html) (IoC).
It also makes use of the [T4 templating engine](http://msdn2.microsoft.com/en-us/library/bb126445.aspx) of Visual Studio to create view scaffolds.
So you could also ask yourself whether you would like to use these tools, libraries and frameworks in your project.
Frankly, if you don't have the time to read the S#arp documentation, then building a project on top of it is probably not a good idea.
One could also say the S#arp arch doesn't hide the complexity of each of the above library and framework from you, so you have to be prepared to look into each of these as well.
The S#arp documentation and the enclosing sample app explains the purpose and structure of the different layers quite well. | The [S#arp Architecture](http://code.google.com/p/sharp-architecture/) project home page links to an active [discussion group](http://groups.google.com/group/sharp-architecture). I suggest you browse the group messages and ask any questions you have there. | S#arp Architecture | [
"",
"c#",
"asp.net",
"s#arp-architecture",
""
] |
In [an answer](https://stackoverflow.com/questions/791498/how-to-steal-private-data-in-net/791506#791506) to his own [controversial question](https://stackoverflow.com/questions/791498/how-to-steal-private-data-in-net/), [Mash](https://stackoverflow.com/users/33854/mash) has illustrated that you don't need the "unsafe" keyword to read and write directly to the bytes of any .NET object instance. You can declare the following types:
```
[StructLayout(LayoutKind.Explicit)]
struct MemoryAccess
{
[FieldOffset(0)]
public object Object;
[FieldOffset(0)]
public TopBytes Bytes;
}
class TopBytes
{
public byte b0;
public byte b1;
public byte b2;
public byte b3;
public byte b4;
public byte b5;
public byte b6;
public byte b7;
public byte b8;
public byte b9;
public byte b10;
public byte b11;
public byte b12;
public byte b13;
public byte b14;
public byte b15;
}
```
And then you can do things like change an "immutable" string. The following code prints "bar" on my machine:
```
string foo = "foo";
MemoryAccess mem = new MemoryAccess();
mem.Object = foo;
mem.Bytes.b8 = (byte)'b';
mem.Bytes.b10 = (byte)'a';
mem.Bytes.b12 = (byte)'r';
Console.WriteLine(foo);
```
You can also trigger an [AccessViolationException](http://msdn.microsoft.com/en-us/library/system.accessviolationexception.aspx) by corrupting object references with the same technique.
Question: I thought that (in pure managed C# code) the [unsafe](http://msdn.microsoft.com/en-us/library/chfa2zb8(VS.71).aspx) keyword was necessary to do things like this. Why is it not necessary here? **Does this mean that pure managed "safe" code is not really safe at all?** | OK, that is nasty... the dangers of using a union. That may work, but isn't a very good idea - I guess I'd compare it to reflection (where you can do most things). I'd be interested to see if this works in a constrained access environment - if so, it may represent a bigger problem...
---
I've just tested it without the "Full Trust" flag, and the runtime rejects it:
> Could not load type 'MemoryAccess'
> from assembly 'ConsoleApplication4,
> Version=1.0.0.0, Culture=neutral,
> PublicKeyToken=null' because objects
> overlapped at offset 0 and the
> assembly must be verifiable.
And to have this flag, you already need high trust - so you can already do more nasty things. Strings are a slightly different case, because they aren't normal .NET objects - but there are other examples of ways to mutate them - the "union" approach is an interesting one, though. For another hacky way (with enough trust):
```
string orig = "abc ", copy = orig;
typeof(string).GetMethod("AppendInPlace",
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(string), typeof(int) }, null)
.Invoke(orig, new object[] { "def", 3 });
Console.WriteLine(copy); // note we didn't touch "copy", so we have
// mutated the same reference
``` | Whoops, I've muddled `unsafe` with `fixed`. Here's a corrected version:
The reason that the sample code does not require tagging with the `unsafe` keyword is that it does not contain *pointers* (see below quote for why this is regarded as unsafe). You are quite correct: "safe" might better be termed "run-time friendly". For more information on this topic I refer you to Don Box and Chris Sells *Essential .NET*
To quote MSDN,
> In the common language runtime (CLR),
> unsafe code is referred to as
> unverifiable code. Unsafe code in C#
> is not necessarily dangerous; it is
> just code whose safety cannot be
> verified by the CLR. The CLR will
> therefore only execute unsafe code if
> it is in a fully trusted assembly. If
> you use unsafe code, it is your
> responsibility to ensure that your
> code does not introduce security risks
> or pointer errors.
The difference between fixed and unsafe is that fixed stops the CLR from moving things around in memory, so that things outside the run-time can safely access them, whereas unsafe is about exactly the opposite problem: while the CLR can guarantee correct resolution for a dotnet reference, it cannot do so for a pointer. You may recall various Microsofties going on about how a reference is not a pointer, and this is why they make such a fuss about a subtle distinction. | Why does this code work without the unsafe keyword? | [
"",
"c#",
".net",
"unsafe",
""
] |
This is my query
```
update b
set b.col1 = if(1) <= 0
begin
select 1 as bal
end
else
select 0 as bal
from
dbo.table1 b
inner join dbo.table1 a
on b.id = a.id
and b.date = a.date
```
The "IF" part works great by itself. Puting it in this query form throws
Incorrect syntax near the keyword 'if'.
am I missing something other than sleep. | You need to use a CASE WHEN statement within queries
```
update b
set b.col1 = CASE WHEN 1 <= 0 THEN 1 ELSE 0 END
``` | "if" is a statement, so you can't use it as an expression. You can use "case" instead:
```
update b
set b.col1 = case when 1 <= 0 then 1 else 0 end
from dbo.table1 b
inner join dbo.table1 a on b.id = a.id and b.date = a.date
```
(The expression in your if doesn't make much sense though, as the condition always has the same value.) | What's with the IF in this query | [
"",
"sql",
""
] |
Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
```
$number = 0;
echo myArray[$number];
``` | I'm not sure what you mean. What you have isn't working because you're missing a `$` in `myArray`:
```
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
```
Unlike other languages, [all PHP variable types are preceded by a dollar sign](http://us.php.net/manual/en/language.variables.basics.php). | Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
```
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
```
To display the values, you can use:
```
echo $arrayStates['NY']; //prints New York
```
or, you can also use its numeric index
```
echo $arrayStates[1]; //prints California
```
To iterate all values of an array, use foreach or for.
```
foreach($arrayStates as $state) {
echo $state;
}
```
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
```
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
```
Hope that helps! | Make array value variable (PHP) | [
"",
"php",
"arrays",
"variables",
""
] |
I want to notify users when he receives a certain Email with a specific sound. So I need to detect the title of Email.
I can use MailMessage in framework 2.0, but this class is not supported in compact framework on Windows Mobile. Any suggestion about which class can I use? Or is it impossible? | Another option is to use [POP3](http://en.wikipedia.org/wiki/Pop3).
Use an ordinary socket-connection and connect to your user's mail-account (normally port 110). You can then execute some POP3-commands such as TOP which retrieves a part of the message. For instance:
**Example 1 - Return headers only:**
```
TOP 1 0
+OK Top of message follows
--- all message headers ---
```
**Example 2 - Return headers and first 10 lines of body:**
```
TOP 1 10
+OK Top of message follows
--- all message headers ---
--- first 10 lines of body ---
```
When you receive the same, you can parse the text for the word: "Subject:" which is part of the headers.
Here is a web-page covering some basic [POP3-commands](http://www.electrictoolbox.com/article/networking/pop3-commands/). In any case, by using Google you can find a lot of useful information about POP3.
Good luck | You can intercept e-mails with IMapiAdviseSink
<http://blogs.msdn.com/hegenderfer/archive/2009/04/28/intercepting-mail-using-imapiadvisesink.aspx> | How to detect the title of Email on Windows Mobile? | [
"",
"c#",
"email",
"windows-mobile",
""
] |
I'm adding functionality to one of our existing (but broken) systems. It grabs an XML file from a web service, parses it and then does some stuff before packing it back into our database.
the previous developer (who has now left) left me this little gem:
<http://dl.getdropbox.com/u/109069/wut.GIF>
and I wonder if there's a way round this?
Can I loop through each node and assign to the wo object by its name?
something like this (pseudo code):
```
foreach XmlNode xn in WorkorderNodeTree
{
//find out the property name of the current node
//match to the property in the workorder class
//set the value equal
wo.<xn.name> = xn.innertext
}
```
Now the only thing I found which gets close is this (from the interweb):
```
foreach (XmlNode xl in myXML)
{
object o = Assembly.GetExecutingAssembly().CreateInstance("Workorder", true);
Type t = xl.Name.GetType();
PropertyInfo pi = t.GetProperty(xl.Name);
pi.SetValue(o, xl.InnerText, null);
}
```
but it returns a null reference exception on o. I am a little confused, any tips?
I presume to do this, I need to use reflection or generics, but I've never hit upon these things before - can anyone advise anything which might point me in the right direction or at least try to explain reflection?
Many thanks all, apologies for the hideously long post!
EDIT:
Thanks, Very deep and sincere thanks go to Fredrik and Rytmis - both of you are white knights in my drab office environment. Rytmis' code edits have solved the issue but I have learned much in this hour or so - Thanks guys, really appreciate it. | I think your code may need a bit of adjustment.
```
foreach (XmlNode xl in myXML)
{
object o = Assembly.GetExecutingAssembly().CreateInstance("Workorder", true);
Type t = xl.Name.GetType();
PropertyInfo pi = t.GetProperty(xl.Name);
pi.SetValue(o, xl.InnerText, null);
}
```
This creates a new instance of WorkOrder for every property you're setting, and also tries to reflect the PropertyInfo from Name.GetType() which is actually typeof(String), and not typeof(WorkOrder) like you'd want it to be. Instead:
```
WorkOrder w = new WorkOrder();
Type t = typeof(WorkOrder);
foreach (XmlNode xl in myXML)
{
PropertyInfo pi = t.GetProperty(xl.Name);
pi.SetValue(w, xl.InnerText, null);
}
```
[edit] You may also want to specify some binding flags:
```
PropertyInfo pi = t.GetProperty(xl.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
```
That may or may not be required. I can never remember what the defaults are. :) | Try [AutoMapper](http://www.codeplex.com/AutoMapper) or Custom Mapping in [BLToolkit](http://bltoolkit.com/Doc/Mapping/MapToJson.htm). | c# choosing class properties with a variable? | [
"",
"c#",
".net",
"reflection",
""
] |
I can't for the life of me find the proper syntax using the Fluent/AAA syntax in Rhino for validating order of operations.
I know how to do this with the old school record/playback syntax:
```
MockRepository repository = new MockRepository();
using (repository.Ordered())
{
// set some ordered expectations
}
using (repository.Playback())
{
// test
}
```
Can anyone tell me what the equivalent to this in AAA syntax for Rhino Mocks would be. Even better if you can point me to some documentation for this. | Try this:
```
//
// Arrange
//
var mockFoo = MockRepository.GenerateMock<Foo>();
mockFoo.GetRepository().Ordered();
// or mockFoo.GetMockRepository().Ordered() in later versions
var expected = ...;
var classToTest = new ClassToTest( mockFoo );
//
// Act
//
var actual = classToTest.BarMethod();
//
// Assert
//
Assert.AreEqual( expected, actual );
mockFoo.VerifyAllExpectations();
``` | Here's an example with interaction testing which is what you usually want to use ordered expectations for:
```
// Arrange
var mockFoo = MockRepository.GenerateMock< Foo >();
using( mockFoo.GetRepository().Ordered() )
{
mockFoo.Expect( x => x.SomeMethod() );
mockFoo.Expect( x => x.SomeOtherMethod() );
}
mockFoo.Replay(); //this is a necessary leftover from the old days...
// Act
classToTest.BarMethod
//Assert
mockFoo.VerifyAllExpectations();
```
This syntax is very much Expect/Verify but as far as I know it's the only way to do it right now, and it does take advantage of some of the nice features introduced with 3.5. | What is the AAA syntax equivalent to using Ordered() in Rhino Mocks | [
"",
"c#",
"unit-testing",
"rhino-mocks",
""
] |
I need to sort a list of UK postcodes in to order.
Is there a simple way to do it?
UK postcodes are made up of letters and numbers:
see for full info of the format:
<http://en.wikipedia.org/wiki/UK_postcodes>
But my problem is this a simple alpha sort doesn't work because each code starts with 1 or two letters letters and then is immediately followed by a number , up to two digits, then a space another number then a letter. e.g. LS1 1AA or ls28 1AA, there is also another case where once the numbers in the first section exceed 99 then it continues 9A etc.
Alpha sort cause the 10s to immediately follow the 1:
```
...
LS1 9ZZ
LS10 1AA
...
LS2
```
I'm looking at creating a SQL function to convert the printable Postcode into a sortable postcode e.g. 'LS1 9ZZ' would become 'LS01 9ZZ', then use this function in the order by clause.
Has anybody done this or anything similar already? | You need to think of this as a tokenization issue so SW1A 1AA should tokenize to:
* SW
* 1
* A
* 1AA
(although you could break the inward part down into 1 and AA if you wanted to)
and G12 8QT should tokenize to:
* G
* 12
* (empty string)
* 8QT
Once you have broken the postcode down into those component parts then sorting should be easy enough. There is an exception with the GIR 0AA postcode but you can just hardcode a test for that one
*edit: some more thoughts on tokenization*
For the sample postcode SW1A 1AA, SW is the postcode area, 1A is the postcode district (which we'll break into two parts for sorting purposes), 1 is the postcode sector and AA is the unit postcode.
These are the valid postcode formats (source: Royal Mail PAF user guide page 8 - link at bottom of [this page](http://www.royalmail.com/portal/rm/content3?mediaId=56000705&catId=400085)):
AN NAA
AAN NAA
ANN NAA
ANA NAA
AAA NAA (only for GIR 0AA code)
AANN NAA
AANA NAA
So a rough algorithm would be (assuming we want to separate the sector and unit postcode):
* code = GIR 0AA? Tokenize to GI/R/ /0/AA (treating R as the district simplifies things)
* code 5 letters long e.g G1 3AF? Tokenize to G/1/ /3/AF
* code 6 letters long with 3rd character being a letter e.g. W1P 1HQ? Tokenize to W/1/P/1/HQ
* code 6 letters long with 2nd character being a letter e.g. CR2 6XH? Tokenize to CR/2/ /6/XH
* code 7 letters long with 4th character being a letter e.g. EC1A 1BB? Tokenize to EC/1/A/1/BB
* otherwise e.g. TW14 2ZZ, tokenize to TW/14/ /2/ZZ
If the purpose is to display a list of postcodes for the user to choose from then I would adopt Neil Butterworth's suggestion of storing a 'sortable' version of the postcode in the database. The easiest way to create a sortable version is to pad all entries to nine characters:
* two characters for the area (right-pad if shorter)
* two for the district number (left-pad if shorter)
* one for the district letter (pad if missing)
* space
* one for the sector
* two for the unit
and GIR 0AA is a slight exception again. If you pad with spaces then the sort order should be correct. Examples using # to represent a space:
* W1#1AA => W##1##1AA
* WC1#1AA => WC#1##1AA
* W10#1AA => W#10##1AA
* W1W#1AA => W##1W#1AA
* GIR#0AA => GI#R##0AA
* WC10#1AA => WC10##1AA
* WC1W#1AA => WC#1W#1AA
You need to right-pad the area if it's too short: left-padding produces the wrong sort order. All of the single letter areas - B, E, G, L, M, N, S, W - would sort before all of the two-letter areas - AB, AL, ..., ZE - if you left-padded
The district number needs to be left padded to ensure that the natural W1, W2, ..., W9, W10 order remains intact | I know this is a couple of years late but i too have just experienced this problem.
I have managed to over come it with the following code, so thought i would share as i searched the internet and could not find anything!
```
mysql_query("SELECT SUBSTRING_INDEX(postcode,' ',1) as p1, SUBSTRING_INDEX(postcode,' ',-1) as p2 from `table` ORDER BY LENGTH(p1), p1, p2 ASC");
```
This code will take a Full UK postcode and split it into 2.
It will then order by the first part of the postcode followed by the second. | Sort Postcode for menu/list | [
"",
"sql",
"sorting",
"postal-code",
""
] |
I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc...
So what I've got is something like:
```
double? amount = Convert.ToDouble(strAmount);
```
The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this:
```
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
```
Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert.
I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this:
```
public static class GenericExtension
{
public static Nullable<T> ConvertToNullable<T>(this string s, T type) where T: struct
{
if (s.Trim().Length > 0)
{
return (Nullable<T>)s;
}
return null;
}
}
```
But I get the error: Cannot convert type 'string' to 'T?'
Is there a way around this? I am not very familiar with creating methods using generics. | Another thing to keep in mind is that the string itself might be null.
```
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
``` | You could try using the below extension method:
```
public static T? GetValueOrNull<T>(this string valueAsString)
where T : struct
{
if (string.IsNullOrEmpty(valueAsString))
return null;
return (T) Convert.ChangeType(valueAsString, typeof(T));
}
```
This way you can do this:
```
double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();
``` | Convert string to nullable type (int, double, etc...) | [
"",
"c#",
".net",
"generics",
"extension-methods",
"type-conversion",
""
] |
The javascript jQuery code below works, except I would like to add 2 features to the button's state.
1. When a user clicks one of the buttons, the other button that was not clicked gets a new class (look).
2. Both button's state should change to unclickable.
```
[div id="1" class="__button_image"] [/div]
[div id="2" class="__button_image"] [/div]
```
```
$("div.__button_image").mouseover(function () {
$(this).addClass("__button_image_hover");
});
$("div.__button_image").mouseout(function () {
jq(this).removeClass("__button_image_hover");
});
$("div.__button_image").click(function () {
$(this).removeClass("__button_image_hover");
$(this).addClass("__button_image_clicked");
jQuery.get('/do/request');
});
``` | Here is final code I went with:
```
$("div.__button_image").mouseover(function () {
$(this).addClass("__button_image_hover");
});
$("div.__button_image").mouseout(function () {
$(this).removeClass("__button_image_hover");
});
$("div.__button_image").click(function () {
/** change button look to 'clicked' */
$(this).addClass("__button_image_clicked");
/** get the id of the current button */
b_id = $(this).attr('id');
/** unbind both vote buttons for *no* interaction */
$("div.__button_image").unbind('click');
$("div.__button_image").unbind('mouseover');
$("div.__button_image").unbind('mouseout');
/**
* wire the .each function to iterate the classes
* so we can change the look of the one that was
* not clicked.
*/
$('div.__button_image').each(function() {
button_id = $(this).attr('id');
if(button_id!=b_id) {
$('#'+button_id).removeClass("__button_image");
$('#'+button_id).addClass("__button_image_gray");
}
});
jQuery.get('/do/request?id='+b_id);
$(this).parent().css('cursor', 'default');
``` | What's the problem? The only thing I can see that you're missing is
```
$("div.__button_image").unbind('click');
```
This will remove the 'click' handler (setting it back to the default). | jQuery Change Div Button States & Click Disable | [
"",
"javascript",
"jquery",
"css",
"user-interface",
"frontend",
""
] |
Is there a short way of converting a strongly typed `List<T>` to an Array of the same type, e.g.: `List<MyClass>` to `MyClass[]`?
By short i mean one method call, or at least shorter than:
```
MyClass[] myArray = new MyClass[list.Count];
int i = 0;
foreach (MyClass myClass in list)
{
myArray[i++] = myClass;
}
``` | Try using
```
MyClass[] myArray = list.ToArray();
``` | ```
List<int> list = new List<int>();
int[] intList = list.ToArray();
```
is it your solution? | Conversion from List<T> to array T[] | [
"",
"c#",
".net",
"arrays",
"linq",
"list",
""
] |
I have two tables:
**Patient**
* pkPatientId
* FirstName
* Surname
**PatientStatus**
* pkPatientStatusId
* fkPatientId
* StatusCode
* StartDate
* EndDate
**Patient** -> **PatientStatus** is a one to many relationship.
I am wondering if its possible in SQL to do a join which returns only the first two PatientStatus records for each Patient. If only one PatientStatus record exists then this should not be returned in the results.
The normal join of my query is:
```
SELECT FROM Patient p INNER JOIN PatientStatus ps ON p.pkPatientId = ps.fkPatientId
ORDER BY ps.fkPatientId, ps.StartDate
``` | A CTE is probably your best bet if you're in SQL Server 2005 or greater, but if you want something a little more compatible with other platforms, this should work:
```
SELECT
P.pkPatientID,
P.FirstName,
P.LastName,
PS1.StatusCode AS FirstStatusCode,
PS1.StartDate AS FirstStatusStartDate,
PS1.EndDate AS FirstStatusEndDate,
PS2.StatusCode AS SecondStatusCode,
PS2.StartDate AS SecondStatusStartDate,
PS2.EndDate AS SecondStatusEndDate
FROM
Patient P
INNER JOIN PatientStatus PS1 ON
PS1.fkPatientID = P.pkPatientID
INNER JOIN PatientStatus PS2 ON
PS2.fkPatientID = P.pkPatientID AND
PS2.StartDate > PS1.StartDate
LEFT OUTER JOIN PatientStatus PS3 ON
PS3.fkPatientID = P.pkPatientID AND
PS3.StartDate < PS1.StartDate
LEFT OUTER JOIN PatientStatus PS4 ON
PS4.fkPatientID = P.pkPatientID AND
PS4.StartDate > PS1.StartDate AND
PS4.StartDate < PS2.StartDate
WHERE
PS3.pkPatientStatusID IS NULL AND
PS4.pkPatientStatusID IS NULL
```
It does seem a little odd to me that you would want the first two statuses instead of the last two, but I'll assume that you know what you want.
You can also use WHERE NOT EXISTS instead of the PS3 and PS4 joins if you get better performance with that. | Here is my attempt - It should work on SQL Server 2005 and SQL Server 2008 (Tested on SQL Server 2008) owing to the use of a common table expression:
```
WITH CTE AS
(
SELECT fkPatientId
, StatusCode
-- add more columns here
, ROW_NUMBER() OVER
(
PARTITION BY fkPatientId ORDER BY fkPatientId desc) AS [Row_Number]
from PatientStatus
where fkPatientId in
(
select fkPatientId
from PatientStatus
group by fkPatientId
having COUNT(*) >= 2
)
)
SELECT p.pkPatientId,
p.FirstName,
CTE.StatusCode
FROM [Patient] as p
INNER JOIN CTE
ON p.[pkPatientId] = CTE.fkPatientId
WHERE CTE.[Row_Number] = 1
or CTE.[Row_Number] = 2
``` | SQL query - Join that returns the first two records of joining table | [
"",
"sql",
"sql-server",
"join",
""
] |
Are there any jQuery plugins or templates that people use to get poeple to stop using IE6 on their websites?
I recently saw a plugin that was very obtrusive and offensive that "warned" users of evil of IE6. I am looking for something one can show their customers. | Just add a div that only IE6 users see.
```
<!--[if IE 6]>
<div>
Using IE 6 will curve your spine, please upgrade your version
of Internet Explorer or download Firefox, Opera, Safari or Chrome.
</div>
<![endif]-->
``` | Keep in mind that many web users are 'held up' using IE6 because of their big corporation's IT department.
They already know about the need to upgrade and your message aggravates them further. Why make them more miserable? At least give a gentle message explaining why you can't support IE6. | notify users that they need to stop using IE6 | [
"",
"javascript",
"jquery",
"internet-explorer-6",
""
] |
I'm looking for C# code to convert an HTML document to plain text.
I'm not looking for simple tag stripping , but something that will output plain text with a *reasonable* preservation of the original layout.
The output should look like this:
[Html2Txt at W3C](http://www.w3.org/services/html2txt)
I've looked at the HTML Agility Pack, but I don't think that's what I need. Does anyone have any other suggestions?
**EDIT:** I just download the HTML Agility Pack from [CodePlex](http://html-agility-pack.net/?z=codeplex), and ran the Html2Txt project. What a disappointment (at least the module that does html to text conversion)! All it did was strip the tags, flatten the tables, etc. The output didn't look anything like the Html2Txt @ W3C produced. Too bad that source doesn't seem to be available.
I was looking to see if there is a more "canned" solution available.
**EDIT 2:** Thank you everybody for your suggestions. **FlySwat** tipped me in the direction i wanted to go. I can use the `System.Diagnostics.Process` class to run lynx.exe with the "-dump" switch to send the text to standard output, and capture the stdout with `ProcessStartInfo.UseShellExecute = false` and `ProcessStartInfo.RedirectStandardOutput = true`. I'll wrap all this in a C# class. This code will be called only occassionly, so i'm not too concerned about spawning a new process vs. doing it in code. Plus, Lynx is FAST!! | What you are looking for is a text-mode DOM renderer that outputs text, much like Lynx or other Text browsers...This is much harder to do than you would expect. | Just a note about the HtmlAgilityPack for posterity. The project contains an [example of parsing text to html](https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs), which, as noted by the OP, does not handle whitespace at all like anyone writing HTML would envisage. There are full-text rendering solutions out there, noted by others to this question, which this is not (it cannot even handle tables in its current form), but it is lightweight and fast, which is all I wanted for creating a simple text version of HTML emails.
```
using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
//small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs
public static class HtmlToText
{
public static string Convert(string path)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(path);
return ConvertDoc(doc);
}
public static string ConvertHtml(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
return ConvertDoc(doc);
}
public static string ConvertDoc (HtmlDocument doc)
{
using (StringWriter sw = new StringWriter())
{
ConvertTo(doc.DocumentNode, sw);
sw.Flush();
return sw.ToString();
}
}
internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
{
foreach (HtmlNode subnode in node.ChildNodes)
{
ConvertTo(subnode, outText, textInfo);
}
}
public static void ConvertTo(HtmlNode node, TextWriter outText)
{
ConvertTo(node, outText, new PreceedingDomTextInfo(false));
}
internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
{
string html;
switch (node.NodeType)
{
case HtmlNodeType.Comment:
// don't output comments
break;
case HtmlNodeType.Document:
ConvertContentTo(node, outText, textInfo);
break;
case HtmlNodeType.Text:
// script and style must not be output
string parentName = node.ParentNode.Name;
if ((parentName == "script") || (parentName == "style"))
{
break;
}
// get text
html = ((HtmlTextNode)node).Text;
// is it in fact a special closing node output as text?
if (HtmlNode.IsOverlappedClosingElement(html))
{
break;
}
// check the text is meaningful and not a bunch of whitespaces
if (html.Length == 0)
{
break;
}
if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace)
{
html= html.TrimStart();
if (html.Length == 0) { break; }
textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;
}
outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @"\s{2,}", " ")));
if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1]))
{
outText.Write(' ');
}
break;
case HtmlNodeType.Element:
string endElementString = null;
bool isInline;
bool skip = false;
int listIndex = 0;
switch (node.Name)
{
case "nav":
skip = true;
isInline = false;
break;
case "body":
case "section":
case "article":
case "aside":
case "h1":
case "h2":
case "header":
case "footer":
case "address":
case "main":
case "div":
case "p": // stylistic - adjust as you tend to use
if (textInfo.IsFirstTextOfDocWritten)
{
outText.Write("\r\n");
}
endElementString = "\r\n";
isInline = false;
break;
case "br":
outText.Write("\r\n");
skip = true;
textInfo.WritePrecedingWhiteSpace = false;
isInline = true;
break;
case "a":
if (node.Attributes.Contains("href"))
{
string href = node.Attributes["href"].Value.Trim();
if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase)==-1)
{
endElementString = "<" + href + ">";
}
}
isInline = true;
break;
case "li":
if(textInfo.ListIndex>0)
{
outText.Write("\r\n{0}.\t", textInfo.ListIndex++);
}
else
{
outText.Write("\r\n*\t"); //using '*' as bullet char, with tab after, but whatever you want eg "\t->", if utf-8 0x2022
}
isInline = false;
break;
case "ol":
listIndex = 1;
goto case "ul";
case "ul": //not handling nested lists any differently at this stage - that is getting close to rendering problems
endElementString = "\r\n";
isInline = false;
break;
case "img": //inline-block in reality
if (node.Attributes.Contains("alt"))
{
outText.Write('[' + node.Attributes["alt"].Value);
endElementString = "]";
}
if (node.Attributes.Contains("src"))
{
outText.Write('<' + node.Attributes["src"].Value + '>');
}
isInline = true;
break;
default:
isInline = true;
break;
}
if (!skip && node.HasChildNodes)
{
ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten){ ListIndex = listIndex });
}
if (endElementString != null)
{
outText.Write(endElementString);
}
break;
}
}
}
internal class PreceedingDomTextInfo
{
public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten)
{
IsFirstTextOfDocWritten = isFirstTextOfDocWritten;
}
public bool WritePrecedingWhiteSpace {get;set;}
public bool LastCharWasSpace { get; set; }
public readonly BoolWrapper IsFirstTextOfDocWritten;
public int ListIndex { get; set; }
}
internal class BoolWrapper
{
public BoolWrapper() { }
public bool Value { get; set; }
public static implicit operator bool(BoolWrapper boolWrapper)
{
return boolWrapper.Value;
}
public static implicit operator BoolWrapper(bool boolWrapper)
{
return new BoolWrapper{ Value = boolWrapper };
}
}
```
As an example, the following HTML code...
```
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<header>
Whatever Inc.
</header>
<main>
<p>
Thanks for your enquiry. As this is the 1<sup>st</sup> time you have contacted us, we would like to clarify a few things:
</p>
<ol>
<li>
Please confirm this is your email by replying.
</li>
<li>
Then perform this step.
</li>
</ol>
<p>
Please solve this <img alt="complex equation" src="http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png"/>. Then, in any order, could you please:
</p>
<ul>
<li>
a point.
</li>
<li>
another point, with a <a href="http://en.wikipedia.org/wiki/Hyperlink">hyperlink</a>.
</li>
</ul>
<p>
Sincerely,
</p>
<p>
The whatever.com team
</p>
</main>
<footer>
Ph: 000 000 000<br/>
mail: whatever st
</footer>
</body>
</html>
```
...will be transformed into:
```
Whatever Inc.
Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:
1. Please confirm this is your email by replying.
2. Then perform this step.
Please solve this [complex equation<http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png>]. Then, in any order, could you please:
* a point.
* another point, with a hyperlink<http://en.wikipedia.org/wiki/Hyperlink>.
Sincerely,
The whatever.com team
Ph: 000 000 000
mail: whatever st
```
...as opposed to:
```
Whatever Inc.
Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:
Please confirm this is your email by replying.
Then perform this step.
Please solve this . Then, in any order, could you please:
a point.
another point, with a hyperlink.
Sincerely,
The whatever.com team
Ph: 000 000 000
mail: whatever st
``` | How can I Convert HTML to Text in C#? | [
"",
"c#",
"html",
".net",
"parsing",
"text",
""
] |
I'm writing a DSP application in C# (basically a multitrack editor). I've been profiling it for quite some time on different machines and I've noticed some 'curious' things.
On my home machine, the first run of the playback loop takes up about 50%-60% of the available time, (I assume it's due to the JIT doing its job), then for the subsequent loops it goes down to a steady 5% consumption. The problem is, if I run the application on a slower computer, the first run takes up more than the available time, causing the playback to get interrupted and messing the output audio, which is unacceptable. After that, it goes down to a 8%-10% consumption.
Even after the first run, the application keeps calling some time-consuming routines from time to time (every 2 seconds more or less), which causes the steady 5% consumption to experience very short peaks of 20%-25%. I've noticed that if I let the application run for a while these peaks will also go down to a 7%-10%. (I'm not sure if it's due to the JIT recompiling these portions of code).
So, I have a serious problem with the JIT. While the application will behave nicely even in very slow machines, these 'compiling storms' are going to be a big problem. I'm trying to figure out how to resolve this issue and I've come up with an idea, which is to mark all the 'sensible' routines with an attribute that will tell the application to 'squeeze' them beforehand during start-up, so they'll be fully optimized when they're really needed. But this is only an idea (and I don't like it too much either) and I wonder if there's a better solution to the whole problem.
I'd like to hear what you guys think.
(NGEN the application is not an option, I like and want all the JIT optimizations I can get.)
EDIT:
Memory consumption and garbage collection kicks are not an issue, I'm using object pools and the maximum peak of memory during playback is 304 Kb. | You can trigger the JIT compiler to compile your entire set of assemblies during your application's initialization routine using the `PrepareMethod` ... method (without having to use `NGen`).
This solution is described in more detail here: [Forcing JIT Compilation During Runtime](http://www.liranchen.com/2010/08/forcing-jit-compilation-during-runtime.html). | The initial speed indeed sounds like Fusion+JIT, which would be helped by ILMerge (for Fusion) and NGEN (for JIT); you could always play a silent track through the system at startup so that this does all the hard work without the user noticing any distortion?
NGEN is a good option; is there a *reason* you can't use it?
The issues you mention *after* the initial load do **not** sound like they are related to JIT. Perhaps garbage collection.
Have you tried profiling? Both CPU and memory (collections)? | Forcing the .NET JIT compiler to generate the most optimized code during application start-up | [
"",
"c#",
".net",
"optimization",
"compiler-construction",
"jit",
""
] |
I'm new to COM programming. I've got a COM object (and associated IClassFactory) all ready to go, but I can't quite figure out how to go about registering the resulting DLL for use by other programs. The number of GUIDs I need to sling around is also unclear to me.
The COM object I'm trying to register implements the IAudioSessionEvents interface.
I have come across the DllRegisterServer and DllUnregisterServer functions, but I haven't found any clear demonstrations of their usage. What keys do they deal with, how are they invoked, by what and when, etc.?
Thanks,
-Kevin Montrose | I'm not sure from this post whether you are implementing or consuming the DLL that supports IAudioSessionEvents. If you're consuming this DLL, then you can register the component using the comment line utility regsvr32. To register use:
regsvr32
To unregister:
regsvr32 /u
regsvr32 should be on your path, so this command will work from any directory.
If you are implementing the DLL in question, then you must provide an implementaion of the DllRegisterServer and DllUnRegisterServer functions. These functions must set up and clean up registry entries for your component. The purpose of the registry entries is to provide a ProgID, map it to a CLSID, and provid interface ID for the interfaces that the component supports. For example, the interface ID for IAudioSessionEvent. If you're implementing the DLL, you'll have to provide code to perform all of these tasks.
Note: these functions are called by regsvr32 in order to register the component.
If very unusual to actually write this code, generally you'll want to use a framework like ATL, which takes care of the busywork for you. It is a good exercise to write this code at least once if you really want to know COM from the ground up. | You need one GUID for every class you expose to COM and one GUID for every new interface you introduce and want to make available through COM.
DllRegisterServer/DllUnregister server are called when you use regsvr32 utility (ships with Windows) to register your COM-exposed classes. It adds/removes keys to HKCR/CLSID branch for every class you expose to COM. These keys are used by CoCreateInstance() to find out which DLL to load for creating an instance of a class with a given GUID.
If you use ATL or something similar usually don't need to completely implement DllRegisterServer/DllUnRegisterServer but use the implementation provided with the library. | Registering implementation of a COM interface | [
"",
"c++",
"windows",
"com",
""
] |
If I have a variable in PHP containing `0001` and I add 1 to it, the result is 2 instead of `0002`.
How do I solve this problem? | ```
$foo = sprintf('%04d', $foo + 1);
``` | It would probably help you to understand the PHP data types and how they're affected when you do operations to variables of various types. You say you have "a variable in PHP say 0001", but what type is that variable? Probably a string, "0001", since an integer can't have that value (it's just 1). So when you do this:
```
echo ("0001" + 1);
```
...the `+` operator says, "Hm, that's a string and an integer. I don't know how to add a string and an int. But I DO know how to convert a string INTO an int, and then add two ints together, so let me do that," and then it converts "0001" to 1. Why? Because the PHP rules for converting a string to an integer say that any number of leading zeroes in the string are discarded. Which means that the string "0001" becomes 1.
Then the `+` says, "Hey, I know how to add 1 and 1. It's 2!" and the output of that statement is 2. | In PHP, how do I add to a zero-padded numeric string and preserve the zero padding? | [
"",
"php",
"variables",
"string-formatting",
"zero-pad",
""
] |
I want to create my own function `loop()`:
```
loop($x,$y){
//do something
}
```
it should work like for, foreach operators:
```
$y=count($array);
for($x=0; $x<$y; $x++){
//do something
}
```
How to create functions like this with `{ }` in PHP? (NOT a regular function) | Another thing which you can if you are really serious about your function/s you can write it a php extension which will you some flexibility...<http://devzone.zend.com/node/view/id/1021> I must warn you though..it's not as easy.... | You can't.
Constructs like for or foreach are part of php syntax.
If you want to create regular function just use function keyword:
```
function some_func($x, $y)
{
....
}
``` | How to create my own function with { } in PHP | [
"",
"php",
"function",
""
] |
While studying C++ (and C) I had some particular doubts regarding the working of stack allocation, that I can't find a solution to:
1. Does stack allocation call malloc/free functions implicitly? If not; how does it assure there is no conflict between stack allocation and heap allocation?
2. If yes; does stack allocation in C++ implicitly call new/delete too? If yes; does overloading the new operator for a class affect its stack allocation?
It yielded confusing results in VC++; but as VC++ isn't entirely standard-compliant (or so I heard) I decided I better ask here... | Stack allocation doesn't use anything like malloc/free. It uses a piece of memory called program stack which is just a contiguous segment of memory.
There's a special register that stores the top of the stack. When a new object is created on stack the top is raised thus increasing the stack, when an object is deallocated (goes out of scope) the top is lowered thus decreasing the stack.
If you try to allocate a too large object on stack or go too deep into recursion the top will outgrow the maximum allowed size of the stack and this is called stack overflow.
Note: actual direction of stack growth (increasing or decreasing addresses) [will vary by system](https://stackoverflow.com/questions/664744/what-is-the-direction-of-stack-growth-in-most-modern-systems), but general idea is the same regardless of actual direction. | The answer to your first question is No. Stack is not allocated from the heap at all.
You should read [What and where are the stack and heap](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) first to understand the basic concepts. | About C/C++ stack allocation | [
"",
"c++",
"c",
"memory-management",
"stack",
"heap-memory",
""
] |
Let's say I have a data object, but this object can hold one of several types of data.
```
class Foo
{
int intFoo;
double doubleFoo;
string stringFoo;
}
```
Now, I want to create an accessor. Some way to get at this data. Obviously, I could create multiple accessors:
```
public int GetIntFoo();
public double GetDoubleFoo();
public string GetStringFoo();
```
Or I could create multiple properties
```
public int IntFoo { get; set; }
public double DoubleFoo { get; set; }
public string StringFoo { get; set; }
```
I don't that this is a very good design. It requires the client code to be more concerned about type than it should have to be. What's more, I really need only a single value for this class and the above would allow one of each type to be assigned at the same time. Not good.
One option is to use Generics.
```
class Foo<T>
{
public T TheFoo { get; set; }
}
```
However, this doesn't create a Foo, it creates a Foo<T>. A different type for each, so I can't really use them as the same type.
I could derive Foo<T> from FooBase, then treat all of them as FooBase's, but then i'm back in the problem of accessing the data.
A different Generics option is to use something like this:
```
class Foo
{
string stringRepresentationOfFoo;
public T GetFoo<T>() { return /* code to convert string to type */ }
}
```
OF course the problem is that any kind of T could be passed, and frankly, it's a bit busy.
I could also just box the values and return an object, but then there is no type safety.
Ideally, I want to treat all Foo's the same, but I want type safety so that if there isn't a StringFoo, I can't even compile a reference to a StringFoo.
```
Foo foo = new Foo("Foo");
string sFoo = foo.Value; // succeeds.
Foo foo = new Foo(0);
int iFoo = foo.Value; // succeeds
string sFoo = foo.Value; // compile error
```
Perhaps this isn't even possible.. and I'll have to make some compromises, but maybe i'm missing something.
Any ideas?
EDIT:
Ok, so as daniel points out, the compile time checking of a runtime type is not practical.
What is my best option for doing what I want to do here? Namely, Treat all Foo's the same, but still have a relatively sane access mechanism?
EDIT2:
I don't want to convert the value to different types. I want to return the correct type for the value. That is, if it's a double, I don't want to return an int. | How about passing in the variable as a parameter to the get? Like this:
```
int i = foo.get(i);
```
Then in your class, you'd have something like:
```
public int get(int p) {
if(this.type != INTEGER) throw new RuntimeException("Data type mismatch");
return this.intVal;
}
public float get(float p) {
if(this.type != FLOAT) throw new RuntimeException("Data type mismatch");
return this.floatVal;
}
```
This sort of turns the type checking inside-out: instead of checking what type foo holds, you have foo check what type you want. If it can give you that type, it does, or else it throws a runtime exception. | I don't think this could work (giving you the compiler error you want)
What would you want this to do:
```
Foo bar = (new Random()).Next(2) == 0 ? new Foo("bar") : new Foo(1);
int baz = bar.Value;
```
Is that a compiler error?
I think "treat them all the same" (at least the way you've described it) and "compile time error" are going to be mutually exclusive.
In any case, I think the "best way" is going to be a compromise between generics and inheritance. You can define a `Foo<T>` that is a subclass of Foo; then you can still have collections of `Foo`.
```
abstract public class Foo
{
// Common implementation
abstract public object ObjectValue { get; }
}
public class Foo<T> : Foo
{
public Foo(T initialValue)
{
Value = initialValue;
}
public T Value { get; set; }
public object ObjectValue
{
get { return Value; }
}
}
``` | Best way to design a multi-type object | [
"",
"c#",
"generics",
"type-safety",
""
] |
We have a product built on the Client-Server architecture. Some details about the technology stack used.
* Client - Java Swing
* Server - RMI
* Java Database - Oracle
The clients are located at different parts of the world but the java server & the oracle database are located on the same machine in Sweden. Because of this there is a lot of network latency. The clients located at distant locations have terrible performance. The application is used for processing files with the size over 50MB. Each operation in general requires about over 1000 Network calls.
Based on your experience, how do you tackle this problem and improve the performance?
EDIT: To answer a few questions
1. Files contains the actual business data which needs to be processed and updated to the database cannot be sent in part.
2. Some of the network calls could be batched but it would require major refactoring of the code. This is a very old application written way back in 2001. And the design of the application is such that, the server holds all the services and they are made reusable across the code and the business logic is written on the client side. So, this business logic calls server numerous times and hence the astronomical figure.
-Snehal | **Decrease your number of round trips**
1000 round trips for a single operation is an astronomic figure. No way you should be seeing those numbers.
You still have a problem though with the 50MB files. In which case, you will either need to find a way to make the transfer more efficient (transfer only deltas between two similar files?), or employ caching of some sort.
The WAN traffic is killing your app, and it sounds like you have major refactoring to do. | Sending big files and lot of requests over the net costs a lot of time. Period. Even if you could upgrade to gigabit Ethernet, the protocol still demands that your client idles a few milliseconds between two consecutive network packets (so other hosts get a chance to talk, too).
But gigabit Ethernet is not feasible since the clients are far away (probably connected via the Internet).
So the only path which will work is to move the business code closer to the server. The most simple solution will be to install the clients on little boxes in the same LAN as the server and use VNC or a similar protocol to access them remotely.
The next level would be to cut the clients into a business layer and a display layer. Turn the business layer into a service and install the display layer on the clients. This way, data is only pushed around on the (fast) intranet. When the results are ready for display, the clients get only the results (little data). | How to improve the performance of Client-Server Architecture Application? | [
"",
"java",
"performance",
"client-server",
"rmi",
""
] |
Let's say I've got an HTML / CSS page with some images in it, and I wanted to generate a PDF from that source in Python - possible? | <http://www.xhtml2pdf.com/>
install was a little quirky for me, but otherwise it worked fine. | You can do something like this using [`Pisa`](http://www.xhtml2pdf.com/):
```
def receipt(request, id):
import ho.pisa as pisa
from django.template.loader import render_to_string
from datetime import datetime
r = get_or_404(id, request.affiliate)
now = datetime.now()
contents = render_to_string('home/reservations/receipt.html', {
'reservation': r,
'today': now
})
filename = now.strftime('%Y-%m-%d') + '.pdf'
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + filename
pdf = pisa.CreatePDF(contents, response)
if pdf.err:
message(request, 'Unable to generate the receipt.')
return HttpResponseRedirect(reverse('view_reservation', args=[r.id]))
else:
return response
```
(This is a Django view that generates a receipt but obviously you can use Pisa in whatever setting)
You're going to have to tweak the HTML to make it play as nice as possible with Pisa, though. | How to generate a PDF from an HTML / CSS (including images) source in Python? | [
"",
"python",
"html",
"css",
"pdf",
"pdf-generation",
""
] |
I want to know how to work out the new co-ordinates for a point when rotated by an angle relative to another point.
I have a block arrow and want to rotate it by an angle theta relative to a point in the middle of the base of the arrow.
This is required to allow me to draw a polygon between 2 onscreen controls. I can't use and rotate an image.
From what I have considered so far what complicates the matter further is that the origin of a screen is in the top left hand corner. | If you rotate point `(px, py)` around point `(ox, oy)` by angle `theta` you'll get:
```
p'x = cos(theta) * (px-ox) - sin(theta) * (py-oy) + ox
p'y = sin(theta) * (px-ox) + cos(theta) * (py-oy) + oy
``` | If you are using GDI+ to do that, you can use `Transform` methods of the `Graphics` object:
```
graphics.TranslateTransform(point of origin);
graphics.RotateTransform(rotation angle);
```
Then draw the actual stuff. | Rotate a point by another point in 2D | [
"",
"c#",
"math",
"rotation",
"angle",
""
] |
Could anyone please explain the concept of **Island of isolation** of Garbage Collection? | Object A references object B. Object B references object A. Neither object A nor object B is referenced by any other object. That's an island of isolation.
Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island of isolation too.
**Edit from Comment:**
```
class A {
B myB;
}
class B {
A myA;
}
/* later */
A a = new A();
B b = new B();
a.b = b;
b.a = a;
``` | Here is a [good explanation](http://www.xyzws.com/Javafaq/what-is-islands-of-isolation-in-garbage-collection/42) of this term. Excerpt:
> * "If an object obj1 is garbage collected, but another object obj2
> contains a reference to it, then obj2
> is also eligible for garbage
> collection"
> * "If object obj2 can access object obj1 that is eligible for garbage
> collection, then obj2 is also eligible
> for garbage collection"
>
> This is called "Island of Isolation".
> An "island of isolation" describes one
> or more objects have NO references to
> them from active parts of an
> application. | "Island of isolation" of Garbage Collection | [
"",
"java",
"garbage-collection",
""
] |
Under what circumstances should each of the following synchronization objects be used?
1. ReaderWriter lock
2. Semaphore
3. Mutex | * Since wait() will return once for each time post() is called, semaphores are a basic producer-consumer model - the simplest form of inter-thread message except maybe signals. They are used so one thread can tell another thread that something has happened that it's interested in (and how many times), and for managing access to resources which can have at most a fixed finite number of users. They offer ordering guarantees needed for multi-threaded code.
* Mutexes do what they say on the tin - "mutual exclusion". They ensure that the right to access some resource is "held" by only on thread at a time. This gives guarantees of atomicity and ordering needed for multi-threaded code. On most OSes, they also offer reasonably sophisticated waiter behaviour, in particular to avoid priority inversion.
Note that a semaphore can easily be used to implement mutual exclusion, but that because a semaphore does not have an "owner thread", you don't get priority inversion avoidance with semaphores. So they are not suitable for all uses which require a "lock".
* ReaderWriter locks are an optimisation over mutexes, in cases where you will have a lot of contention, most accesses are read-only, and simultaneous reads are permissible for the data structure being protected. In such cases, exclusion is required only when a writer is involved - readers don't need to be excluded from each other. To promote a reader to writer all other readers must finish (or abort and start waiting to retry if they also wish to become writers) before the writer lock is acquired. ReaderWriter locks are likely to be slower in cases where they aren't faster, due to the additional book-keeping they do over mutexes.
* Condition variables are for allowing threads to wait on certain facts or combinations of facts being true, where the condition in question is more complex than just "it has been poked" as for semaphores, or "nobody else is using it" for mutexes and the writer part of reader-writer locks, or "no writers are using it" for the reader part of reader-writer locks. They are also used where the triggering condition is different for different waiting threads, but depends on some or all of the same state (memory locations or whatever).
* Spin locks are for when you will be waiting a very short period of time (like a few cycles) on one processor or core, while another core (or piece of hardware such as an I/O bus) simultaneously does some work that you care about. In some cases they give a performance enhancement over other primitives such as semaphores or interrupts, but must be used with extreme care (since lock-free algorithms are difficult in modern memory models) and only when proven necessary (since bright ideas to avoid system primitives are often premature optimisation).
Btw, these answers aren't C# specific (hence for example the comment about "most OSes"). Richard makes the excellent point that in C# you should be using plain old locks where appropriate. I believe Monitors are a mutex/condition variable pair rolled into one object. | I would say each of them can be "the best" - depends on the use case ;-) | When should each thread synchronization objects be used? | [
"",
"c#",
"multithreading",
"synchronization",
""
] |
I’m trying to use the MVP pattern and I’m running into a design problem. I’m developing an application that will have several UserControls. The UserControls themselves have nothing to do with one another and only represent a subset of the actual model. From what I’ve read, people tend to say you should use one Presenter per View. This seems to make sense, but if I have 30 UserControls, do I really want 30 Presenters? On the flip side, if I have 1 Presenter and 1 View that represent the entire “application” view, then I’ll have bloated View and Presenter interfaces. Then each View would have to implement methods that have nothing to do with it. My question is, is there a better way to handle multiple UserControls, or should I just create 1 Presenter for each View? | It would make more sense to group the code that is related in one object. So, in this case, if the views are specific groupings of related code, then the presenter would also mimic these groupings. To have a "global" presenter for different views would group unrelated code in one object. It would definitely bloat the interface for the presenter as well. Check out the [single responsibility principle](http://www.objectmentor.com/resources/articles/srp.pdf).
Now, you could have one Presenter Manager class perhaps that could give you access to each presenter interface, [like the Interface Segregation Principle](http://www.objectmentor.com/resources/articles/isp.pdf) states, by either inheritance (have a global concrete presenter that implements many presenter interfaces..which kind of violates the single responsibilty) or aggregation (having individual presenters for each interface and get functions...thus the global interface would the the get functions) or a combination of both (global presenter being somewhat of an adapter).
I think the best solution though would just to have 30 different presenters. | You should be doing one presenter per one control because of:
* that would allow you to have **focused unit tests** tackling only that control
* **increased maintainability** due to the fact you won’t need to support gigantic presenter containing union of presentation logic of all controls
* that would **prevent redundancy** in cases of having same control on multiple pages
* **Increases SRP** by having controls focusing on their specific logic while the page performs container specific roles:
There are two problems usually mentioned related to the decision “presenter per control”:
* **Shared context** is problem where due to the fact that all of the controls are just showing different pieces of the same page data context, that situation may look like a problematic use case leading to a lot of data retrieval redundant code in every of the controls.
That is easily solvable through dependency injection where page (or controller) performs single data retrieval and then inject the data context object into every of the presenters\views (usually implementing some interface enabling that).
In case of MV-VM pattern (Silverlight, WPF) same effect can be achieved through data bounding where the page would set its DataContext which would then be used from views itself
* **Communication between views** on the same page is second problem which is easily solvable using couple of approaches:
* Controls are publishing **events** to which page subscribes and then makes direct calls to appropriate methods in other controls (page is container to all controls meaning it is aware of all of their members)
* **Observer** design pattern
* **Event aggregator** pattern
In each one of this approaches controls are communicating with each other without being aware of each other | MVP and multiple User Controls | [
"",
"c#",
"design-patterns",
"oop",
"user-controls",
"mvp",
""
] |
I came across 2 different modules for porting Django to App Engine:
<http://code.google.com/p/app-engine-patch/>
<http://code.google.com/p/google-app-engine-django/>
Both seem to be compatible with Django 1.0,
The featured download of the latter is in Aug 08, whereas the former is Feb 09.
What are the relative merits?
What if I don't use the database at all, would it matter? | It's a bit late to answer, but the problem I've had so far with app-engine-patch is that, while it's a generally feature-complete port of Django 1.0, it discards Django models in favor of AppEngine's db.Model.
It's understandable, given the differences between the two, but it can require quite a bit of effort to port, depending on how involved your models (and usage of those models; this means you lose the Django query syntax as well). | At the moment, the App Engine Patch is outdated.
Djangoappengine and Django-Nonrel provide "Native Django on App Engine":
<http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine> | 2 different Django modules on Google App Engine | [
"",
"python",
"django",
"google-app-engine",
""
] |
How do I get the OpenGL color matrix transforms working?
I've modified a sample program that just draws a triangle, and added some color matrix code to see if I can change the colors of the triangle but it doesn't seem to work.
```
static float theta = 0.0f;
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );
glClearDepth(1.0);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef( theta, 0.0f, 0.0f, 1.0f );
glMatrixMode(GL_COLOR);
GLfloat rgbconversion[16] =
{
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f
};
glLoadMatrixf(rgbconversion);
glMatrixMode(GL_MODELVIEW);
glBegin( GL_TRIANGLES );
glColor3f( 1.0f, 0.0f, 0.0f ); glVertex3f( 0.0f, 1.0f , 0.5f);
glColor3f( 0.0f, 1.0f, 0.0f ); glVertex3f( 0.87f, -0.5f, 0.5f );
glColor3f( 0.0f, 0.0f, 1.0f ); glVertex3f( -0.87f, -0.5f, 0.5f );
glEnd();
glPopMatrix();
```
As far as I can tell, the color matrix I'm loading should change the triangle to black, but it doesn't seem to work. Is there something I'm missing? | The color matrix only applies to pixel transfer operations such as glDrawPixels which aren't hardware accelerated on current hardware. However, implementing a color matrix using a fragment shader is really easy. You can just pass your matrix as a uniform mat4 then mulitply it with `gl_FragColor` | It looks like you're doing it correctly, but your current color matrix sets the triangle's alpha value to 0 as well, so while it is being drawn, it does not appear on the screen. | OpenGL Color Matrix | [
"",
"c++",
"opengl",
"colors",
""
] |
I am trying to make a few php scripts that will run among other things system calls commands like top and other custom scripts. You can see the code below is super simple. The problem that we are having with the php below is that when I call the php from the linux prompt like:
```
#php checkTOP.php
```
it will return the top -n 1 output in the screen no problem there.
When I run the script from the webserver using the <http://url.com/checkTOP.php> it only returns the following:
> program:/usr/bin/top -n 1 ver1 =
> retval = 1 Returned not zero
Which is my debugging statements.
```
<?php
$program="/usr/bin/top -n 1";
echo "program:{$program}<br /> \n";
$ver1=system($program,$retval);
echo "ver1 = {$ver1}<br />\n";
echo "retval = {$retval}<br /> \n";
if($retval==0)
{
echo "Returned 0<br />\n";
}
else
{
echo "Returned not zero <br />\n";
}
die;
?>
```
Change 1: One more thing. All permissions are set correctly /usr/bin/top is set root:apache with rxrxrx and also all the directories /usr/bin. | Ole beat me; I used output buffering so I'll post it:
`<?PHP
ob_start();
$program="/usr/bin/top -n 1 -b";
passthru($program);
$t=ob_get_contents();
ob_end_clean();
echo "<PRE>$t</PRE>";
?>` | Sounds like it's a problem related to user accounts. When you run it from the command-line manually, you're probably running under a different user than the webserver tries to run as.
Some things to check:
* is [Safe Mode](http://php.net/manual/en/features.safe-mode.php) enabled for PHP?
* does the user the webserver runs under (often "www-data") have permission to execute `top`?
* can you turn on a higher [error reporting level](http://php.net/manual/en/function.error-reporting.php) to see if you can get more information? | Why the php code below is not returning the expected values? | [
"",
"php",
"linux",
"bash",
"scripting",
""
] |
How do I create a datetime in Python from milliseconds? I can create a similar `Date` object in Java by [`java.util.Date(milliseconds)`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html).
> Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. | Just convert it to timestamp
```
datetime.datetime.fromtimestamp(ms/1000.0)
``` | What about this? I presume it can be counted on to handle dates before 1970 and after 2038.
```
target_datetime_ms = 200000 # or whatever
base_datetime = datetime.datetime(1970, 1, 1)
delta = datetime.timedelta(0, 0, 0, target_datetime_ms)
target_datetime = base_datetime + delta
```
as mentioned in the Python standard lib:
> fromtimestamp() may raise ValueError, if the timestamp is out of the
> range of values supported by the platform C localtime() or gmtime()
> functions. It’s common for this to be restricted to years in 1970
> through 2038.
Very obviously, this can be done in one line:
```
target_dt = datetime(1970, 1, 1) + timedelta(milliseconds=target_dt_ms)
```
... not only was this obvious from my answer, but the 2015 comment by jfs is also highly misleading, because it calls the variable `utc_time`.
Er no: it's not "time", it's `datetime`, and it's most definitely NOT *UTC*. The `datetime` with which we're concerned here is a "timezone-naive" `datetime`, as opposed to a **timezone-aware** `datetime`. Therefore definitely NOT UTC.
Search on this if you're not familiar with the issue. | How do I create a datetime in Python from milliseconds? | [
"",
"python",
"datetime",
""
] |
I have created a CustomValidator control
```
public class MyValidator :CustomValidator, IScriptControl {}
```
and also created the equivalent client script. The server validation works fine, however how do I hook up my client script?
The rendered javascript looks like
```
var MyValidator1 = document.all ? document.all["MyValidator1"] : document.getElementById("MyValidator1");
MyValidator1.controltovalidate = "MyField";
MyValidator1.errormessage = "error";
MyValidator1.evaluationfunction = "MyValidatorEvaluateIsValid";
```
How do I override the generated javascript to set the value of evaluationfunction? E.g.
```
MyValidator1.evaluationfunction = "MyCustomJavascriptFunction";
``` | I've answered this myself as the other answer didn't quite achieve exactly what I wanted. I ended up using.
```
public class MyValidator : BaseValidator, IScriptControl {
protected override void AddAttributesToRender(HtmlTextWriter writer) {
base.AddAttributesToRender(writer);
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "MyJavascriptFunction");
}
}
```
Which will cause the control to generate:
```
MyValidator1.evaluationfunction = "MyJavascriptFunction";
``` | You can set the ClientValidationFunction property of the base class like this -
```
base.ClientValidationFunction = "MyCustomJavascriptFunction";
```
So, it will render it like this -
```
MyValidator1.evaluationfunction = "MyCustomJavascriptFunction";
```
You can do it from the control also by setting the same property.
EDIT: You can do
```
document.getElementById("<%= ValidatorId %>").evaluationfunction = "MyCustomJavascriptFunction";
``` | How do I hook up javascript to my CustomValidator control in .Net | [
"",
"asp.net",
"javascript",
"custom-validators",
""
] |
I'm trying to consume a .NET 2.0 web service using Axis.
I generated the web services client using Eclipse WST Plugin and it seems ok so far.
Here the expected SOAP header:
```
<soap:Header>
<Authentication xmlns="http://mc1.com.br/">
<User>string</User>
<Password>string</Password>
</Authentication>
</soap:Header>
```
I didn't find any documentation on how to configure this header from an Axis client.
When I generated the client using Visual Studio C# Express 2008, it generates a class named `Authentication` with two String attributes (`User` and `Password`) and all the client methods receive an object of this class as first parameter, but it did not happen with Axis WS client.
How can I set this header in my client calls? | Maybe you can use `org.apache.axis.client.Stub.setHeader` method? Something like this:
```
MyServiceLocator wsLocator = new MyServiceLocator();
MyServiceSoap ws = wsLocator.getMyServiceSoap(new URL("http://localhost/MyService.asmx"));
//add SOAP header for authentication
SOAPHeaderElement authentication = new SOAPHeaderElement("http://mc1.com.br/","Authentication");
SOAPHeaderElement user = new SOAPHeaderElement("http://mc1.com.br/","User", "string");
SOAPHeaderElement password = new SOAPHeaderElement("http://mc1.com.br/","Password", "string");
authentication.addChild(user);
authentication.addChild(password);
((Stub)ws).setHeader(authentication);
//now you can use ws to invoke web services...
``` | If you have an object representing the `Authentication` container with userid and password, you can do it like so:
```
import org.apache.axis.client.Stub;
//...
MyAuthObj authObj = new MyAuthObj("userid","password");
((Stub) yourServiceObject).setHeader("urn://your/name/space/here", "partName", authObj);
``` | Set custom SOAP header using Axis 1.4 | [
"",
"java",
".net",
"web-services",
"soap",
"axis",
""
] |
I'm trying to map network drive from windows service, I use batch file for executing the following command
```
NET USE U: \\192.168.55.6\folder password
```
While executing batch file either in service constructor or in onstart event, drive is not mapped?
```
Process process = new Process();
process.StartInfo.FileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\MAP.BAT";
process.StartInfo.CreateNoWindow = false;
process.Start();
```
How does one map network drive from windows service? | All issues solved by using [Map Network Drive (API)](http://www.codeproject.com/KB/system/mapnetdrive.aspx) to map network drive. I map required drives while OnStart event of service. | This can be achieved using a reference to Windows Script Host Object Model.
Add a COM reference to **Windows Script Host Object Model** which adds an entry IWshRuntimeLibrary to the references section. Now you can use the following code to map a drive.
```
using IWshRuntimeLibrary;
IWshNetwork_Class network = new IWshNetwork_Class();
network.MapNetworkDrive("k:",@"\\192.168.20.35\MyShare", Type.Missing, "user1", "password1");
```
you can use the following code to UnMap or remove the mapping.
```
network.RemoveNetworkDrive("k:");
```
I have documented the detailed steps [here](http://techisolutions.blogspot.com/2011/12/map-network-drive-using-c-vbnet-code.html "here") | How does one map network drive from windows service? | [
"",
"c#",
"windows-services",
"network-drive",
""
] |
I have downloaded php.vim file, which contains PHP-based syntax information. It should be able to provide syntax based folding, but I can't make it work for some reason.
I have set `:let g:php_folding 2` and `:set foldmethod=syntax` but for no avail. I'm pretty sure the file is in right place and is read by vim, since I can do `:let g:php_sql_query=1` which works.
The `php.vim` file is located in `~/.vim/syntax/php.vim` | Apparently my VIM didn't run :syntax enable.
Doing :syntax enable fixed the problem, but I also added :syntax on to .vimrc | :syntax enable (or :syntax on) work because both those options also turn on filetype detection. The filetype has to be detected before folding or highlighting work.
If you're developing in PHP you probably want to add these three lines to your .vimrc
```
set nocompatible " Because filetype detection doesn't work well in compatible mode
filetype plugin indent on " Turns on filetype detection, filetype plugins, and filetype indenting all of which add nice extra features to whatever language you're using
syntax enable " Turns on filetype detection if not already on, and then applies filetype-specific highlighting.
```
Then you can put your `let g:php_folding=2` and `set foldmethod=syntax` in your `~/.vim/after/ftplugin/php.vim` file.
This will keep your .vimrc file clean, help organize all your settings, and the foldmethod=syntax will only affect php files (If you want to set syntax as your default fold method for all filestypes, leave that line in your .vimrc file)
For more detailed information read these help files:
> :help filetype
> :help usr\_05.txt
> :help usr\_43.txt | Vim syntax based folding with php | [
"",
"php",
"vim",
"syntax",
"folding",
""
] |
I'd like an iterator in C++ that can only iterate over elements of a specific type. In the following example, I want to iterate only on elements that are SubType instances.
```
vector<Type*> the_vector;
the_vector.push_back(new Type(1));
the_vector.push_back(new SubType(2)); //SubType derives from Type
the_vector.push_back(new Type(3));
the_vector.push_back(new SubType(4));
vector<Type*>::iterator the_iterator; //***This line needs to change***
the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
SubType* item = (SubType*)*the_iterator;
//only SubType(2) and SubType(4) should be in this loop.
++the_iterator;
}
```
How would I create this iterator in C++? | You must use a dynamic cast.
```
the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
SubType* item = dynamic_cast<SubType*>(*the_iterator);
if( item != 0 )
...
//only SubType(2) and SubType(4) should be in this loop.
++the_iterator;
}
``` | [boost filter iterator?](http://www.boost.org/doc/libs/1_38_0/libs/iterator/doc/filter_iterator.html) | How to create an iterator over elements that match a derived type in C++? | [
"",
"c++",
"stl",
"iterator",
""
] |
I've been reading a bit about what metaclasses are, but I would like to know if they can be achieved in C++.
I know that Qt library is using MetaObjects, but it uses an extension of C++ to achieve it. I want to know if it is possible directly in C++.
Thanks. | It's possible to create meta-classes, however C++ is not about that, it's about statically compile-time based implementations, not runtime flexibility.
Anyways it depends if you want Meta-Classes with methods or just Meta-Classes with data, the Data classes can be implemented with Boost constructs like boost::any, and if you want Classes with methods, you can use boost::bind to bind methods to the object, or you can implement them on your own with a single-entry point interface like COM-objects.
However the "real" C++ way is to use generics so it can all be determined at compile-time, for best performance.
To be honest, I've seen very few systems, although I have seen some, that truly need runtime flexibility, in most cases objects are born and die the same class, or at least enough to spend 95% of their lifetime as a single class once they come out of their factory.
So in many situations one finds themselves paying too much for runtime meta-classes. Of course there is the school of thought that this provides better developer performance, but in many situations, each line of code will be run on hardware a few hundred million times more than the time it took to write it. So you can think about compile-time and runtime classes as paying up front or leasing for-ever. Personally I like to pay up front. | If the working definition of metaclass is "a language entity whose instantiations are themselves classes," then *generics* are metaclasses in C++:
```
#include <iostream>
using namespace std;
template <typename T>
class Meta {
public:
Meta(const T&init) : mData(init) {}
// ...
private:
T mData;
};
int main(int, char **) {
cout << "The size of Meta<double> is " << sizeof(Meta<double>) << endl ;
return 0;
}
```
The use of Meta<double> in the antepenultimate line compels the compiler to instantiate the Meta<double> class; the sizeof operator operates upon Meta, thus demonstrating that this is not simply semantic sugar and that the class has been instantiated. The program is complete even though no objects of type Meta are instantiated. | How can I implement metaclasses in C++? | [
"",
"c++",
"metaclass",
""
] |
I need to check if a file is on HDD at a specified location ($path.$file\_name).
Which is the difference between [`is_file()`](http://www.php.net/manual/en/function.is-file.php) and [`file_exists()`](http://www.php.net/manual/en/function.file-exists.php) functions and which is better/faster to use in PHP? | `is_file()` will return `false` if the given path points to a directory. `file_exists()` will return `true` if the given path points to a valid file *or* directory. So it would depend entirely on your needs. If you want to know *specifically* if it's a file or not, use `is_file()`. Otherwise, use `file_exists()`. | `is_file()` is the fastest, but recent benchmark shows that `file_exists()` is slightly faster for me. So I guess it depends on the server.
My test benchmark:
```
benchmark('is_file');
benchmark('file_exists');
benchmark('is_readable');
function benchmark($funcName) {
$numCycles = 10000;
$time_start = microtime(true);
for ($i = 0; $i < $numCycles; $i++) {
clearstatcache();
$funcName('path/to/file.php'); // or 'path/to/file.php' instead of __FILE__
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "$funcName x $numCycles $time seconds <br>\n";
}
```
Edit: @Tivie thanks for the comment. Changed number of cycles from 1000 to 10k. The result is:
1. when the file *exists*:
is\_file x 10000 1.5651218891144 seconds
file\_exists x 10000 1.5016479492188 seconds
is\_readable x 10000 3.7882499694824 seconds
2. when the file *does not exist*:
is\_file x 10000 0.23920488357544 seconds
file\_exists x 10000 0.22103786468506 seconds
is\_readable x 10000 0.21929788589478 seconds
Edit: moved clearstatcache(); inside the loop. Thanks CJ Dennis. | is_file or file_exists in PHP | [
"",
"php",
"file",
"exists",
""
] |
I'm writing a script to tidy up a bunch of media spread across my hard drives, and it works pretty well so far at home (on my Mac) as I use symlinks in a directory to give the impression that everything is organised in one location, whilst the actual data is spread across the 4 drives.
Unfortunately, I have to use Windows at work, and of course there's no symlink support there until PHP 5.3 (and I assume that requires Vista as that's when the command-line tool "mklink" first appeared).
As a workaround, I considered creating a shortcut, but I can't find a way of doing it. Is it possible, or is there a better solution I've not considered? | Thanks to the above answer, I found that you can indeed call COM from php, here's my first draft of a symlink() replacement:
```
if (! function_exists('symlink')) {
function symlink($target, $link) {
if (! substr($link, -4, '.lnk'))
$link .= '.lnk';
$shell = new COM('WScript.Shell');
$shortcut = $shell->createshortcut($link);
$shortcut->targetpath = $target;
$shortcut->save();
}
}
``` | There is support for junction points (similar to UNIX symlinks) before Vista.
You need the `linkd` tool from the windows resource kit (free download).
Shortcuts are just files. You can create shortcut files using the COM WScript API. The sample code does this using Python. If there exists a library for PHP that lets you do COM interop, you should be able to do something similar.
```
import win32com.client
import winshell
userDesktop = winshell.desktop()
shell = win32com.client.Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(userDesktop + '\\Zimbra Webmail.lnk')
shortcut.Targetpath = r'C:\Program Files\Mozilla Firefox\firefox.exe'
shortcut.Arguments = 'http://mysite.com/auth/preauth.php'
shortcut.WorkingDirectory = r'C:\Program Files\Mozilla Firefox'
shortcut.save()
``` | Is it possible to create a Windows shortcut using PHP? | [
"",
"php",
"windows",
""
] |
In an interview a while ago for a .NET position the interviewer asked me "what would you use a private interface for?".
I asked him did he mean the difference between implicit vs explicit interface implementation to which he answered no.
So I'm wondering:
1. What he meant?
2. What you would use a private interface for? | An interface could be private within another class
```
public class MyClass
{
private interface IFoo
{
int MyProp { get; }
}
private class Foo : IFoo
{
public int MyProp { get; set; }
}
public static void Main(string[] args)
{
IFoo foo = new Foo();
return foo.MyProp;
}
}
```
in terms of utility it simply hides from other code, even within the same assembly, that said interface exists. The utility of this is not terribly high in my opinion.
[Explicit interface implementation](http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx) is a different matter, has some very useful cases (especially when working with generics and older non generic interfaces) but I would not term it 'private interfaces' and would not say that the term is commonly used in that manner.
Using the two techniques together you can do:
```
public class MyClass
{
private interface IFoo
{
int MyProp { get; }
}
public class Foo : IFoo
{
int IFoo.MyProp { get; set; }
}
public static void Main(string[] args)
{
IFoo foo = new Foo();
return foo.MyProp;
}
}
public class HiddenFromMe
{
public static void Main(string[] args)
{
MyClass.Foo foo = new MyClass.Foo();
return foo.MyProp; // fails to compile
}
}
```
This allows you to expose the nested classes in some fashion while allowing the parent class to invoke methods on them that the outside world cannot. This is a potentially useful case but is not something I would wish to use very often. Certainly it's use in an interview smacks of being a boundary case the interviewer is using because they've seen it and though it was 'interesting' | From [this link](https://web.archive.org/web/20111016070748/http://en.csharp-online.net/Common_Type_System%E2%80%94Private_Interface_Inheritance).
> **Private Interface Inheritance**
>
> Historically, languages have permitted private inheritance. In C++, you can inherit from a type without being polymorphically compatible with that type. It’s just a convenient way to reuse an implementation. In the CTS, you cannot do private implementation inheritance. But you can use private interface inheritance.
>
> Private interface inheritance is really just a way to hide methods from a type’s public API. They are compiled into private methods but are actually accessible through a type’s interface map. In other words, they can only be called through a reference typed as the interface on which the method is defined. An example will make this easier to understand:
>
> ```
> class PrivateImplementer : IFoo
> {
> void IFoo.Foo()
> {
> Console.WriteLine("PrivateImplementer::IFoo.Foo");
> }
> }
> ```
>
> In this case, `PrivateImplementer` is publicly known to implement `IFoo`. Thus, an instance can be treated polymorphically as an instance of `IFoo`. But you cannot actually call Foo on it unless you do treat it as an `IFoo`. This code demonstrates this:
>
> ```
> PrivateImplementer p = new PrivateImplementer();
> p.Foo(); // This line will fail to compile
> IFoo f = p;
> f.Foo();
> ```
>
> You can select individual methods of an interface to implement privately. For instance, if `PrivateImplementer` implemented `IFooBar`, it might choose to implement Foo privately, but Bar publicly using the ordinary syntax.
>
> In practice, there aren’t many common cases where you would use private implementation. The `System.Collections.Generic` library uses this approach to secretly implement all of the legacy System.Collections weakly typed interfaces. This makes backwards compatibility "just work," for example passing an instance of `List<T>` to a method that expects an `IList` will work just fine. In this specific example, cluttering the new type APIs would have been a pity (there are quite a few methods necessary for the weakly typed interoperability).
"No," is a pretty poor answer if he was looking to find out what you knew. Sounds like someone who just wants to show how much they know. | What is a private interface? | [
"",
"c#",
""
] |
I have a linux box. When I had a Windows box, I was able to download the free non-commericial use MS SQL Server.
How can I run free personal copies of SQL Server, Sybase, or Oracle on my linux box?
I don't need to to have any permanent databases or any great amount of storage. I just want to (re-)familiarize myself with these different SQL dialects, and compare techniques and timing to the MySQL and postgresql I do have installed.
Thanks. | SQL Server does not run on Linux. [MySQL](http://www.mysql.com/), however, would and likely came with your Linux distribution.
The Oracle download is [here](http://www.oracle.com/technology/software/products/database/oracle11g/111060_linuxsoft.html).
Sybase is [here](http://www.sybase.com/linuxpromo). | At least for Oracle, they have their [Express Edition](http://www.oracle.com/technology/products/database/xe/index.html), which is free download and available for Linux.
For SQL Server, you will have to get Windows, either as a separate OS, or in a virtual machine (like Virtual Box or VMWare). | How can I practice my SQL Server, Sybase, and Oracle skills on a linux box? | [
"",
"sql",
"sql-server",
"oracle",
"sybase",
""
] |
Does anyone know of a good tutorial/e-book that goes in depth on the System.Runtime.InteropServices namespace? I just got through reading [this](http://www.blackwasp.co.uk/ElevatedButton.aspx) tutorial on how to make the UAC shield show up in a button and now I really want to learn this.
P.S. How do look in the windows system files to know that a method exist to show a UAC shield in a button? | As for your p.s., the code you need is in the information you provided. You use the SendMessage method to send the BCM\_SETSHIELD message to a handle (in this case, the handle of your button) that should show it.
## EDIT
pinvoke.net is a good place to get the prototypes of native functions, but if you don't know what you are looking for, it's not the best. I would suggest the [Windows API reference section of MSDN](http://msdn.microsoft.com/en-us/library/aa383749(VS.85).aspx). You can browse functions in alphabetical order, by category, and by Windows Release, all with descriptions of what they do, what they return and the flag options that control their actions. | There are lots of practical examples at <http://pinvoke.net>. | P/Invoke tutorials? | [
"",
"c#",
"interop",
"pinvoke",
"uac",
""
] |
I'm looking for a simple-to-learn php framework for an application that is being migrated from Access to PHP. The application has lots of forms (sometimes 50+ fields per page), and lots of the fields are inter-dependent (ie, you change one field, it updates some other fields or options).
Is there any good php framework for this? I would prefer it really simple since:
* The devs are not so experienced
* The DB is being migrated from Access and was not designed with OOP in mind, it's basically a collection of tables divided by functionality, so I probably don't need any ORM (at least for now).
The most important thing is really the ease of form design and fields correlation (ex: two list boxes where the values of the second depends of the selected value of the first) - I know most ajax libs have some support for this but I would like it out of the box.
---
edit: As a clarification, the most important is not the ajax nifty stuff, although it is important. The important is a **straightforward** way to create db-based forms. The db is not designed with an ORM in mind, so I don't need fancy table associations on the ORM layer whith cascade deletes etc. If an ORM layer doesn't get in the way and simplifies the implementation so that's ok but i doubt this will ever be true. | While I'll certainly add my support behind the excellent and simple to learn [CodeIgniter](http://codeigniter.com/) I fear everyone so far is missing the elephant in the room regarding this question.
To be perfectly honest I don't think *any* framework is going to make assembling an application with 50+ forms per page simpler or easy for Developers without much experience. Especially with the added requirement of ajax ready support for dropdown dependencies.
Having said that, if you're looking for power and flexibilty I'd select Zend. If you're looking for straight simplicity I'd choose CodeIgniter. | I've just done a similar but much more simple application using codeIgniter, which has a pretty nice [form helper](http://codeigniter.com/user_guide/helpers/form_helper.html)
Examples of code:
```
form_hidden('userName', 'johndoe');
// Would produce: <input type="hidden" name="username" value="johndoe" />
form_input('username', @$_POST['userName'])
// Would produce an input populated with a variable from the post array
```
And you can do allsorts using arrays etc:
```
$js = 'id="shirts" onChange="some_function();"';
echo form_dropdown('shirts', $options, 'large', $js);
``` | PHP Framework for form-intensive application | [
"",
"php",
"forms",
"frameworks",
""
] |
I see a lot of c++ code that looks like this:
```
for( const_iterator it = list.begin(),
const_iterator ite = list.end();
it != ite; ++it)
```
As opposed to the more concise version:
```
for( const_iterator it = list.begin();
it != list.end(); ++it)
```
Will there be any difference in speed between these two conventions? Naively the first will be slightly faster since list.end() is only called once. But since the iterator is const, it seems like the compiler will pull this test out of the loop, generating equivalent assembly for both. | I'll just mention for the record that the C++ standard mandates that calling `begin()` and `end()` on *any* container type (be it `vector`, `list`, `map` etc.) **must take only constant time**. In practice, these calls will almost certainly be inlined to a single pointer comparison if you compile with optimisations turned on.
Note that this guarantee does not necessarily hold for additional vendor-supplied "containers" that do not actually obey the formal requirements of being a container laid out in the chapter 23 of the standard (e.g. the singly-linked list `slist`). | The two versions are not the same though. In the second version it compares the iterator against `list.end()` every time, and what `list.end()` evaluates to might change over the course of the loop. Now of course, you cannot modify `list` through the const\_iterator `it`; but nothing prevents code inside the loop from just calling methods on `list` directly and mutating it, which could (depending on what kind of data structure `list` is) change the end iterator. It might therefore be incorrect in some circumstances to store the end iterator beforehand, because that may no longer be the correct end iterator by the time you get to it. | C++ iterators & loop optimization | [
"",
"c++",
"optimization",
"compiler-construction",
"coding-style",
"iterator",
""
] |
I want to develop an Java application that can detect the user logged on a Window Domain. These credentials are going to be used to logging on the Java application.
How can I do this?
Thanks! | ```
System.getProperty("user.name")
``` | If you need to domain name, you can use this :
```
com.sun.security.auth.module.NTSystem NTSystem = new
com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());
System.out.println(NTSystem.getDomain());
```
Bye. | Detect user logged on a computer using Java | [
"",
"java",
"active-directory",
""
] |
What is the best database schema to represent an NCAA mens basketball bracket? Here is a link if you aren't familiar: <http://www.cbssports.com/collegebasketball/mayhem/brackets/viewable_men>
I can see several different ways you could model this data, with a single table, many tables, hard-coded columns, somewhat dynamic ways, etc. You need a way to model both what seed and place each team is in, along with each game and the outcome (and possibly score) of each. You also need a way to represent who plays who at what stage in the tournament.
In the spirit of March Madness, I thought this would be a good question. There are some obvious answers here, and the main goal of this question is to see all of the different ways you could answer it. Which way is best could be subjective to the language you are using or how exactly you are working with it, but try to keep the answers db agnostic, language agnostic and fairly high level. If anyone has any suggestions on a better way to word this question or a better way to define it let me know in the comments. | For a RDBMS, I think the simplest approach that's still flexible enough to accommodate the majority of situations is to do the following:
* **Teams** has *[team-id (PK)]*, *[name]*, *[region-id (FK to **Regions**)]*, *[initial-seed]*. You will have one entry for each team. (The regions table is a trivial code table with only four entries, one for each NCAA region, and is not listed here.)
* **Participants** has *[game-id (FK to **Games**)]*, *[team-id (FK to **Teams**)]*, *[score (nullable)]*, *[outcome]*. *[score]* is nullable to reflect that a team might forfeit. You will have typically have two Participants per Game.
* **Games** has *[game-id (PK)]*, *[date]*, *[location]*. To find out which teams played in a game, look up the appropriate game-id in the Participants table. (Remember, there might be more than two teams if someone dropped out or was disqualified.)
To set up the initial bracket, match the appropriate seeds to each other. As games are played, note which team has *outcome = Winner* for a particular game; this team is matched up against the winner of another game. Fill in the bracket until there are no more winning teams left. | The natural inclination is to look at a bracket in the order the games are played. You read the traditional diagram from the outside in. But let's think of it the other way around. Each game is played between two teams. One wins, the other loses.
Now, there's a bit more to it than just this. The winners of a particular pair of games face off against each other in another game. So there's also a relationship between the games themselves, irrespective of who's playing in those games. That is, the teams that face off in each game (except in the first round) are the winners of two earlier games.
So you might notice that each game has two "child games" that precede it and determine who faces off in that game. This sounds exactly like a binary tree: each root node has at most two child nodes. If you know who wins each game, you can easily determine the teams in the "parent" games.
So, to design a database to model this, you really only need two entities: `Team` and `Game`. Each `Game` has two foreign keys that relate to other `Game`s. The names don't matter, but we would model them as separate keys to enforce the requirement that each game have no more than two preceding games. Let's call them `leftGame` and `rightGame`, to keep with the binary tree nomenclature. Similarly, we should have a key called `parentGame` that tracks the reverse relationship.
Also, as I noted earlier, you can easily determine the teams that face off in each game by looking at who won the two preceding games. So you really only need to track the winner of each game. So, give the `Game` entity a `winner` foreign key to the `Team` table.
Now, there's the small matter of seeding the bracket. That is, modeling the match-ups for the first round games. You could model this by having a `Game` for each team in the overall competition where that team is the `winner` and has no preceding games.
So, the overall schema would be:
```
Game:
winner: Team
leftGame: Game
rightGame: Game
parentGame: Game
other attributes as you see fit
Team:
name
other attributes as you see fit
```
Of course, you would add all the other information you'd want to the entities: location, scores, outcome (in case the game was won by forfeit or some other out of the ordinary condition). | Best Schema to represent NCAA Basketball Bracket | [
"",
"sql",
"database-design",
"language-agnostic",
"database-agnostic",
""
] |
I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code.
Is it possible to eval the python code and run it ? Is there another way of doing this?
The bottom line is that the python code must run from C, and it must behave exactly as if ran under the python interpreter. I'm asking this now, because I don't want to waste time writing the python code just to find out later that I can't achieve this . As a sidenote, I only plan on using basic python modules ( socket,select, etc. ).
EDIT: maybe this edit is in order. I haven't embedded python in C before, and I don't know what the behaviour will be. The thing is, the server will have a select loop, and will therefore run "forever". Will C let me do that ?
EDIT2: here is why I need to do this. At school, a teacher asked us to do a pretty complex client-server app in C. I'm going to cheat, write the code in python and embed it in C. | here's a nice tutorial for doing exactly that <http://www.linuxjournal.com/article/8497> | It's called embedding Python -- it's well covered in the Python docs. See <https://docs.python.org/extending/embedding.html>
See [how do i use python libraries in C++?](https://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c) | Can I write my apps in python and then run them from C? | [
"",
"python",
"c",
"interop",
""
] |
I read several threads on here about structs (one about mutable structs) and I keep reading about how a struct should have no identity.
What exactly is a lack of identity in a struct? I am guessing it would be like a number, e.g. 5, not having a context (5 what?). Whereas client would be someone expecting a service, and thus there is an identity. Am I thinking correctly?
I know the technical differences and how structs are thread safe (as long as they can't be mutated, but I can still write methods to mutate state), they have new copies everytime they are passed into a method, etc... | It means that the only data you have about a struct is the values is stores - there's no difference between one "5" and another "5". Compare this with a class:
```
Person person1 = new Person("Jon");
Person person2 = new Person("Jon");
Person person3 = person2;
```
Now `person1` and `person2` have references to distinct objects, although they both contain the same data. `person2` and `person3` both refer to the *same* objects. With structs this distinction doesn't exist. | Struct is a value type, so it just represents a value. An Id would only be useful to create a reference to it, in which case it is better off being a class. | What does it mean when a struct has no identity? | [
"",
"c#",
""
] |
Certainly there is some type of context switching, marshaling, serializing, etc that takes place when you choose to write a stored procedure in NET vs T/SQL.
Are there any hard facts about this overhead as it relates to making a decision about using .NET vs T/SQL for stored procedures?
What factors do you use in order to make the decision?
For me, developing in C# is 1000% faster than developing in T/SQL due to my learning curve, but when does this gain not offset the performance hit (if there even is one)? | I'd say it depends.
Some things you will find using CLR procedres are better
1. Using native .NET objects -- file system, network, etc
2. Using features not offered by TQL or not as good as .NET e.g regular expressions
For yet others you will find TSQL procedures are better, either in terms of ease of use or raw execution speed
1. Using set based logic (where abc in def or abc not in ghi)
2. CRUD operations | The overhead is irrelevant in relation to switching, marshaling, etc, unless...your data is not already in the database.
That said, I tend to do almost no stored procedures do as much as possible with T-SQL -- wrapped in an ORM.
Really, that is the answer for there. Look into Entity Framework, NHibernate, Linq To SQL, etc. Get out of writing stored procs (I can hear the down votes now), and do it with C#.
EDIT: Added more info
Stored procs are hard to test (inherently data bound), they offer not speed benefits over dynamic sql, and really are not any more secure. That said, for things like sorting and filtering, a relational database is more efficient than C# will be.
But, if you have to use stored procs (and there are times), use TSQL as much as possible. If you have a substancial amount of logic that needs to be performed, that is not set based, then break out C#.
The one time I did this was to add some extra date processing to my database. The company I was at used a 5-4-4 week-to-month fiscal calendar. That was almost impossible to do in SQL. So I used C# for that one. | What is the overhead associated with .NET stored procedures executing on Sql Server? | [
"",
"c#",
".net",
"sql-server",
"performance",
"stored-procedures",
""
] |
I have a system which I've been wrestling with for a while. Essentially, it uses a lot of abstraction to deal with the fact that later extension is not just expected, but necessary. One place this is required is data access. The system generally deals with managing objects encapsulating some observation (in the sense of an observed value or set of values) and using them. To this end, I have something to the effect of:
```
public interface Observation
{
/** UniqueKey is used to access/identify an observation */
UniqueKey Key
{
get;
}
}
public interface ObservationDataSource
{
/**
* Retrieves an Observation from the actual data source.
* performs any necessary operations to encapsulate values in object
*/
Observation GetObservationByUniqueKey(UniqueKey key);
}
```
The problem arises for specific implementations of these interfaces. Eventually, the `Observation` and `ObservationDataSource` class are implemented with specific runtime classes. However, `UniqueKey` may also be extended to deal with whatever the uniquely identifying set of values are for an observation in the data source (maybe an id, maybe a time, etc). So any implementation of `GetObservationByUniqueKey` will expose a `UniqueKey` argument, but expect a specific subclass. I expect the `UniqueKey` to be casted to a specific type once passed in.
This seems like a poor design choice, since the implementation is lying about the argument requirements -- but I can't see another way of doing this. I expect other people to be using these interfaces, so I can't just say that I'll remember this convention.
Any ideas to fix it or handle it more elegantly? | I do not see this as a problem, simply by amending this one statement of yours:
> So any implementation of
> GetObservationByUniqueKey will expose
> a UniqueKey argument, but expect a
> specific subclass **if and only if
> that UniqueKey was generated by this
> ObservationDataSource**.
If the UniqueKey is not of the expected type, that's just a trivial rejection case that can be handled one of two ways:
(1) By exposing a UniqueKeyType property in your ObservationDataSource interface, the caller of GetObservationByUniqueKey can check the UniqueKey's instance type a priori.
(2) It becomes the contractual responsibility of each GetObservationByUniqueKey implementor to handle the case where the UniqueKey was not generated by it. (This seems perfectly reasonable to me)
However, your entire issue begs the question - why are you allowing UniqueKey to be polymorphic in the first place, when you already have a defined lookup function to get at your data objects? | You say
> So any implementation of GetObservationByUniqueKey will expose a UniqueKey argument,
Howerver, this is incorrect. It will not expose the argument - it will receive one. As you say, the caller might pass arbitrary unique keys, and there is nothing wrong with that.
For a specific data source, only specific unique keys will have associated observation - not just specific wrt. type, but also specific wrt. to actual value. If the value has no observation associated, you return null (I suppose). Do the same if the type of the uniqueid is incorrect - if somebody passes a time when an ID is expect, no observation is associated with that key, in that data source.
OTOH, if the caller is free to pick unique ids, and the data source is supposed to return an empty observation to be filled by the caller, then you have two choices:
1. Don't use interfaces in the first place. Apparently, you cannot substitute one implementation for the other, and the caller must be aware what implementation they use.
2. Alternatively, make sure that all implementations support all kinds of unique keys. | Interface exposes type A, but implementation requires type B (subclass of A) | [
"",
"c#",
"generics",
"arguments",
""
] |
I'm working through [Josh Smith's CommandSink Example](http://www.codeproject.com/KB/WPF/VMCommanding.aspx) and the `base.Executed += (s, e) =>...` structures are throwing me, can someone help make this crystal clear?
**what I understand:**
* base.CanExecute is the event on the inherited class CommandBinding
* the += is adding a delegate to that event
* the delegate is the anonymous function which follows that line
**what I don't understand:**
* is (s,e) is the signature of that function?
* where is the variable s used?
**Here is the code in context:**
```
public class CommandSinkBinding : CommandBinding
{
#region CommandSink [instance property]
ICommandSink _commandSink;
public ICommandSink CommandSink
{
get { return _commandSink; }
set
{
if (value == null)
throw new ArgumentNullException("Cannot set CommandSink to null.");
if (_commandSink != null)
throw new InvalidOperationException("Cannot set CommandSink more than once.");
_commandSink = value;
base.CanExecute += (s, e) =>
{
bool handled;
e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
e.Handled = handled;
};
base.Executed += (s, e) =>
{
bool handled;
_commandSink.ExecuteCommand(e.Command, e.Parameter, out handled);
e.Handled = handled;
};
}
}
...
``` | `(s, e)` is the Method Parameter Signature for the event handler (in this case the anoymous method that's defined)
think `(object Sender, EventArgs e)`
The `s` parameter just isn't being used in the rest of the method which is fine. It has to be there to match the expected signature
```
base.CanExecute += (s, e) =>
{
bool handled;
e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
e.Handled = handled;
};
```
is the equivalent of doing
```
base.CanExecute += new EventHandler(myMethod_CanExecute);
///....
protected void myMethod_CanExecute(object sender, EventArgs e)
{
bool handled;
e.CanExecute = _commandSink.CanExecuteCommand(e.Command, e.Parameter, out handled);
e.Handled = handled;
};
``` | Yes, (s, e) is the signature. The function must have the signature defined by the event (CommandBinding.CanExecute: <http://msdn.microsoft.com/en-us/library/system.windows.input.commandbinding.canexecute.aspx>).
The variable s is not used, in this particular example. The event follows the same design pattern as most other events in .NET. The first parameter will usually contain a reference to the instance that raised the event, the second parameter contains an EventArgs class (or a more specialized class that inherits EventArgs). In this case, the second parameter would be a instance of the type CanExecuteRoutedEventArgs (unless I misinterpreted any information). | can someone explain this C# structure: base.Executed += (s, e) => | [
"",
"c#",
"mvvm",
""
] |
I was writing an algorithm this morning and I ran into a curious situation. I have two `std::map`s. I want to perform a set intersection on the sets of the keys of each (to find which keys are common to both maps). At some point in the future, I think it's likely I'll also want to perform set subtraction here as well. Luckily, the STL includes functions for both of those operations. The problem is, I can't seem to get a `std::set` of the keys out of a `std::map`. Is there any way to do this? I'm looking for something that would be this simple, like it is in Java:
```
std::set<Foo> keys = myMap.getKeySet();
```
My understanding is that I can't use the `std::set_intersection()` function directly on iterators into the maps because the maps expose `std::pair` objects instead of just keys. Also, I don't think the map guarantees order. I'm also interested in performing this same operation on a pair of `std::multimap`s, if that makes any difference.
**EDIT**: I forgot to mention initially that due to the age of the compiler I'm forced to use (MSVC++ 6), most of the nifty template tricks that are available in boost can not be used. | You can use the versatile boost::transform\_iterator to return an iterator that returns only the keys (and not the values). See [How to retrieve all keys (or values) from a std::map and put them into a vector?](https://stackoverflow.com/questions/110157/how-to-retrieve-all-keys-or-values-from-a-stdmap/110228#110228) | What you basically want is a copy, as std::map doesn't keep the keys in a std::set. std::copy assumes that the value types are compatible, which isn't the case here. The std::map::value\_type is a std::pair. You want to copy only the first part of the pair, which means you need a std::transform. Now, since you will be using an insert\_iterator on the set, order doesn't matter. The std::set will sort on insertion, even though the map was already sorted.
[edit] Code might be easier. Top of my head, not compiled.
```
std::transform(MyMap.begin(), MyMap.end(),
std::inserter(MySet, MySet.end()),
boost::bind(&std::pair<Key,Value>::first, _1));
```
If you've got SGI's select1st, you don't need the boost::bind.
[edit]
Updated for C++14
```
std::transform(MyMap.begin(), MyMap.end(),
std::inserter(MySet, MySet.end()),
[](auto pair){ return pair.first; });
``` | how can I get a std::set of keys to a std::map | [
"",
"c++",
"stl",
"dictionary",
"set",
""
] |
I am trying to have a single text link on which the user clicks and it asks the user which file he/she wants to upload then, auto matically POSTs it to the form. How can I achieve the same? I know I have to style my file input but how to get it to post automatically on file selection?
Thank you very much | You can call the submit method of your form. It will submit your page to the server and you can get the file in the Files collection of the request.
You'll have to call the submit() method of the form on the "onchange" event of the "file" element.
```
<input type="file" onchange="formname.submit();" id="f" />
```
EDIT: [Try this.](http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom) | Embedding javascript in the page is [bad practice](http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/).
Add the submit to the item using a selector. This also enables you to add the functionality to a basic link, as you have requested.
**HTML**
```
<form id="myForm">
<a id="uploadLink" href="#">Upload file</a>
</form>
```
**jQuery**
```
$(document).ready(function() {
$("#uploadLink").click(function() {
$("#myForm").submit();
}
});
```
## Additonal resources
Here is a link to the [jQuery Form plugin](http://malsup.com/jquery/form/).
There is also a [multi-file upload plugin for jQuery](http://jquery-multifile-plugin.googlecode.com/svn/trunk/index.html). | Style input file and auto submit | [
"",
"javascript",
"jquery",
"css",
""
] |
I am learning JSP and Java at the moment and wrote a (very) simple guestbook to get started with JSP. But i want to ensure that noone can use CSS, so i need to strip the HTML code before saving it to my mySQL database. I already searched here and found the "
```
PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (ID, ?, ?)");
pStmt.setString(1, request.getParameter("sender"));
pStmt.setString(2, request.getParameter("text"));
pStmt.executeUpdate();
```
So what would be the proper way to do this ? | Short answer: have a look at [org.apache.commons.lang.StringEscapeUtils.escapeHtml()](http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeHtml(java.lang.String)).
More detailed answer: Escaping HTML is the job of the presentation code, not the database code. What if for some reason, you want to display you data at some point in a non-web environment, such as a classic GUI? You will have to unescape the whole thing, otherwise it will display total garbage.
Just save the data as it is and make sure you escape *everything* you get from the user *right before* you display it (ok, maybe not numbers stored as numbers, but you get the idea).
If you're using AJAX, you can take this even further and only escape your strings in JavaScript (or use innerText). | The usual practice is the other way around. We save whatever is in the `textarea`, and use `escapeXML` attribute of a `<c:out>` tag when showing it. This way everything CSS, HTML tags all will be treated as simple text. | How to escape-html in JSP before saving to database? | [
"",
"java",
"database",
"jsp",
"escaping",
""
] |
So I have an XSD and a webservice that delivers in that same format.
Now I could go ahead and read the xml into a document, create my objects from the class etc... But I am thinking, there must be some easier way to do that.
Am I right? ;)
* [Yahoo Maps GeocodeResponse XSD](http://api.local.yahoo.com/MapsService/V1/GeocodeResponse.xsd)
* [Yahoo Maps GeocodeResponse sample](http://local.yahooapis.com/MapsService/V1/geocode?appid=YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--&street=One%20Microsoft%20way1&city=redmond&state=washington "Yahoo GeocodeResponse")
```
<ResultSet xsi:schemaLocation="urn:yahoo:maps http://api.local.yahoo.com/MapsService/V1/GeocodeResponse.xsd">
<Result precision="address">
<Latitude>47.643727</Latitude>
<Longitude>-122.130474</Longitude>
<Address>1 Microsoft Way, #Way1</Address>
<City>Redmond</City>
<State>WA</State>
<Zip>98052-6399</Zip>
<Country>US</Country>
</Result>
</ResultSet>
```
Below are auto-generated classes (two actually), using [xsd.exe](https://stackoverflow.com/questions/87621/how-do-i-map-xml-to-c-objects)
[](https://i.stack.imgur.com/KeUAz.png) | You could use the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer_methods.aspx) to deserialize the XML text into instances of the classes generated by **xsd.exe**.
The XmlSerializer will use the **metadata attributes** placed on the generated classes to map back and forth between XML elements and objects.
```
string xmlSource = "<ResultSet><Result precision=\"address\"><Latitude>47.643727</Latitude></Result></ResultSet>";
XmlSerializer serializer = new XmlSerializer(typeof(ResultSet));
ResultSet output;
using (StringReader reader = new StringReader(xmlSource))
{
output = (ResultSet)serializer.Deserialize(reader);
}
``` | You could just create a Typed DataSet from the XSD and then fill one of those objects with the XML. That's the pretty common method. | How to read XML into a class/classes that matches its xsd | [
"",
"c#",
".net",
"xml",
"xsd",
"xsd.exe",
""
] |
Before the PHP Version update I used to be able to include files as following without specifying the document root:
```
<?php include '/absolute/path/to/files/file1.php'; ?>
```
However I now have to include the same file as following:
```
<?php include $_SERVER['DOCUMENT_ROOT'].'/absolute/path/to/files/file1.php'; ?>
```
What php.ini setting could have overridden the former behaviour? | Including an absolute path should be working the same way straight through PHP 5.2.9 (haven't tried 5.3, but this shouldn't change). Since you're specifying an absolute path, the include\_path directive has no bearing.
Can you provide some more information? What PHP version, platform, and the error you get back from include would be a great start.
> Linux: RHEL 5 PHP: Version PHP 5.2.9 Error Messages I get are: PHP Warning: require(/conf/common.php): failed to open stream: No such file or directory in /var/www/vhosts/DOMAIN/httpdocs/tell-a-friend-fns.php on line 63 PHP Fatal error: require(): Failed opening required '/conf/common.php' (include\_path='.:/usr/share/pear:/usr/lib/php:/tmp') in /var/www/vhosts/DOMAIN/httpdocs/tell-a-friend-fns.php on line 63
Okay, it looks like your application is living in /var/www/vhosts/DOMAIN, and you're looking for /conf/common.php, right? I don't know if your file is actually in /conf/ or if it's in /var/www/vhosts/DOMAIN/conf/ (I assume the latter, with the information given). If it's in /conf/, then make sure that your Web server user can read that directory. If not, change your include to /var/www/vhosts/DOMAIN/httpdocs/conf/common.php.
Better yet, you might be able to do `include '../conf/common.php`, depending on where common.php lives in relation to your main script for the requested page.
Remember that any path given with a leading "/" is absolute in relation to the file system, not the Web server document root. Any path given without a "/" is assumed to be a relative path, relative to your executing script (not the current file). My guess is that prepending $\_SERVER['DOCUMENT\_ROOT'] to your path is changing the absolute path to a relative path. I have no idea why an absolute path would act as a relative path pre-upgrade, unless you were operating in a jailed environment (common with virtual hosts) which got removed during the upgrade. | You need the php.ini directive `include_path`
See: <http://us.php.net/manual/en/ini.core.php#ini.include-path> | including files without having to specify $_SERVER['DOCUMENT_ROOT'] | [
"",
"settings",
"php",
""
] |
If a call to fread() returns 0 and ferror() indicates an error (vs. EOF), is it OK to retry the read or is it better to close and reopen the file?
I can't start over entirely -- the input file has been partially processed in a way that can't be undone (say I'm writing out a chunk at a time to a socket and, due to existing protocol, have no way of telling the remote end, "never mind, I need to start over").
I could fclose() and fopen() the file, fseek() past the data already processed, and continue the fread()-ing from there, but is all that necessary? | There's no "one size fits all" solution, since different errors can require different handling. Errors from `fread()` are unusual; if you're calling it correctly, an error may indicate a situation that has left the `FILE*` in a weird error state. In that case you're best off calling `fclose()`, `fopen()`, `fseek()` to get things back in a good state.
If you're coding for something that's happening, please mention the actual errors you're getting from `ferror()`... | You can give the [`clearerr`](http://www.cplusplus.com/reference/clibrary/cstdio/clearerr/) function a look. | What is a good way to recover from a fread() failure? | [
"",
"c++",
"c",
"error-handling",
"recovery",
"fread",
""
] |
I am using the maven-ear-plugin version 2.3.1 - I know there is a new version available: <http://maven.apache.org/plugins/maven-ear-plugin/>
I can't work out how to upgrade to the latest version? | The default plugin versions are inherited from the Super POM, and you can check them with `mvn help:effective-pom`.
If you want to override the version provided there, add this to your POM:
```
<project>
<build>
<plugins>
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<version>2.3.1</version>
</plugin>
</plugins>
</build>
</project>
```
Replace the version with what you need. | Even though this has already gotten the "approved answer", it turns out that there is this [AWESOME versions plugin](http://www.mojohaus.org/versions-maven-plugin/) that handles the neverending version maintenance problem.
For those lazy people here are some of its goals:
* **versions:display-dependency-updates** scans a project's dependencies and produces a report of those dependencies which have newer versions available.
* **versions:display-plugin-updates** scans a project's plugins and produces a report of those plugins which have newer versions available.
* **versions:display-property-updates** scans a projectand produces a report of those properties which are used to control artifact versions and which properies have newer versions available.
* **versions:update-parent** updates the parent section of a project so that it references the newest available version. For example, if you use a corporate root POM, this goal can be helpful if you need to ensure you are using the latest version of the corporate root POM.
* **versions:update-properties** updates properties defined in a project so that they correspond to the latest available version of specific dependencies. This can be useful if a suite of dependencies must all be locked to one version.
* **versions:update-child-modules** updates the parent section of the child modules of a project so the version matches the version of the current project. For example, if you have an aggregator pom that is also the parent for the projects that it aggregates and the children and parent versions get out of sync, this mojo can help fix the versions of the child modules. (Note you may need to invoke Maven with the -N option in order to run this goal if your project is broken so badly that it cannot build because of the version mis-match).
* **versions:lock-snapshots** searches the pom for all -SNAPSHOT versions and replaces them with the current timestamp version of that -SNAPSHOT, e.g. -20090327.172306-4
* **versions:unlock-snapshots** searches the pom for all timestamp locked snapshot versions and replaces them with -SNAPSHOT.
* **versions:set** can be used to set the project version from the command line.
* **versions:use-releases** searches the pom for all -SNAPSHOT versions which have been released and replaces them with the corresponding release version.
* **versions:use-next-releases** searches the pom for all non-SNAPSHOT versions which have been a newer release and replaces them with the next release version.
* **versions:use-latest-releases** searches the pom for all non-SNAPSHOT versions which have been a newer release and replaces them with the latest release version.
* **versions:use-next-snapshots** searches the pom for all non-SNAPSHOT versions which have been a newer -SNAPSHOT version and replaces them with the next -SNAPSHOT version.
* **versions:use-latest-snapshots** searches the pom for all non-SNAPSHOT versions which have been a newer -SNAPSHOT version and replaces them with the latest -SNAPSHOT version.
* **versions:use-next-versions** searches the pom for all versions which have been a newer version and replaces them with the next version.
* **versions:use-latest-versions** searches the pom for all versions which have been a newer version and replaces them with the latest version. | How do I upgrade the version of a maven plugin? | [
"",
"java",
"maven-2",
"build-process",
"maven-ear-plugin",
""
] |
how can I create `std::ostream` and `std::istream` objects to point to a piece of memory I allocated and manage (I don't want the stream to free my memory).
I was looking at using `rdbuf()->pubsetbuf()` to modify one of the other streams - say `sstringstream`. However I think streambuf used by `stringstream` will free the buffer afterwards?
Basically I'm trying to serialize some things to shared memory.
Thanks. | Take a look at the [bufferstream](http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess/streams.html#interprocess.streams.bufferstream) class in the [Boost.Interprocess](http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess.html) library:
> The bufferstream classes offer
> iostream interface with direct
> formatting in a fixed size memory
> buffer with protection against buffer
> overflows. | ```
#include <iostream>
#include <streambuf>
//...
size_t length = 100;
auto pBuf = new char[length]; // allocate memory
struct membuf: std::streambuf // derive because std::streambuf constructor is protected
{
membuf(char* p, size_t size)
{
setp( p, p + size); // set start end end pointers
}
size_t written() {return pptr()-pbase();} // how many bytes were really written?
};
membuf sbuf( pBuf, length ); // our buffer object
std::ostream out( &sbuf ); // stream using our buffer
out << 12345.654e10 << std::endl;
out.flush();
std::cout << "Nr of written bytes: " << sbuf.written() << std::endl;
std::cout << "Content: " << (char*)pBuf << std::endl;
//...
delete [] pBuf; // free memory
``` | C++ stream to memory | [
"",
"c++",
"stream",
""
] |
The last release was in 2008-03-06. What happened to it? Is it still under active development? Are there any replacements? | Slightly modified version of Rhino (1.6r2) is [part of Java 6](http://www.onjava.com/pub/a/onjava/2006/04/26/mustang-meets-rhino-java-se-6-scripting.html) and on top of that from what I've tested Rhino is very much feature complete so there really isn't anything left to develop onwards, apparently it's also quite bug-free also.
I'd say Rhino is one of those rare libraries which are actually done. | According to a post last week at <http://groups.google.com/group/mozilla.dev.tech.js-engine.rhino/topics>
```
On Mar 9, 11:45 am, Rhino user <anupama.jo...@gmail.com> wrote:
> Does anybody has any tentative dates for 1.7R2 release?
I need to look at https://bugzilla.mozilla.org/show_bug.cgi?id=482203
but other than that it is ready to go.
``` | What happened to Rhino? Is it still under active development? | [
"",
"java",
"rhino",
"scripting-language",
""
] |
Here is what I want to do and I am wondering if there is any Spring classes that will help with implementing. I don't have to use spring for this particular problem, I'm just implementing it with everything else.
In my DAO layer I want to externalize my sql files aka 1 sql per file. I want to read and cache the sql statement even maybe as a spring bean singleton. But in my initial struggles, I am having a problem just loading a sql file in the classpath...
Is there anything in spring to help with that? I've been through the documentation but nothing is jumping out at me.
Here is kind of what I'm after.. but I can't get it to recognize the file or maybe the classpath... not real sure does something need to be defined in applicationContext?
Here are a couple of attempts that do not seem to work... both spring'ish and just java'ish.
```
reader = new BufferedReader(new InputStreamReader(new ClassPathResource("com.company.app.dao.sql.SqlQueryFile.sql").getInputStream())
reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("com.company.app.dao.sql.SqlQueryFile.sql")));
```
Any thoughts? | Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
```
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
```
And then in your application context file, in the bean definition, just set a property:
```
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
```
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into [PropertyPlaceholderConfigurer](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html), and store all your SQL in property files and just inject each one separately where needed. There are lots of options. | Change . to / as the path separator and use `getResourceAsStream`:
```
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
```
or
```
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
```
Note the leading slash when using `Class.getResourceAsStream()` vs `ClassLoader.getResourceAsStream`.
`getSystemResourceAsStream` uses the *system* classloader which isn't what you want.
I suspect that using slashes instead of dots would work for `ClassPathResource` too. | read file in classpath | [
"",
"java",
"spring",
"file-io",
"classpath",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.