Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am looking for a way to set the width on the returned column result from a SQL query.
I run a query like Select Product from ConfigScheduling where Product is an Nvarchar(Max) column.
The result in SQL Server Management Studio with Results to Grid is a 90 char wide visible column, with the full result present, but not visible.
Thank you | If I remember correctly, SQL Server Management Studio cannot pull the whole nvarchar(max) field into display and won't attempt to either. The only way to fully access the resultset is to use a third party tool or display it in a gridview or something in a webapp. | Couldn't find it by default, but if you double-click on the right part of the Column Header it will stretch like in Excel. | Format SQL query results | [
"",
"sql",
"sql-server",
""
] |
C++ has so much stuff that I don't know.
Is there any way to create a function within a class, that will always be called whenever any other function of that class is called? (like making the function attach itself to the first execution path of a function)
I know this is tricky but I'm curious. | Yes-ish, with a bit of extra code, some indirection and another class and using the -> instead of the . operator.
```
// The class for which calling any method should call PreMethod first.
class DogImplementation
{
public:
void PreMethod();
void Bark();
private:
DogImplementation(); // constructor private so can only be created via smart-pointer.
friend class Dog; // can access constructor.
};
// A 'smart-pointer' that wraps a DogImplementation to give you
// more control.
class Dog
{
public:
DogImplementation* operator -> ()
{
_impl.PreMethod();
return &_impl;
}
private:
DogImplementation _impl;
};
// Example usage of the smart pointer. Use -> instead of .
void UseDog()
{
Dog dog;
dog->Bark(); // will call DogImplementation::PreMethod, then DogImplementation::Bark
}
```
Well.. something roughly along those lines could be developed into a solution that I think would allow you to do what you want. What I've sketched out there probably won't compile, but is just to give you a starting point. | Yes. :-)
* Wrap the object in a smart pointer
* Invoke the object's special function automatically from the smart pointer's dereferencing operators (so that the special function is invoked whenever a client dereferences the smart pointer). | In c++ making a function that always runs when any other function of a class is called | [
"",
"c++",
"syntax",
""
] |
I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found [MSNP](http://msnp.sourceforge.net/). I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probably changed one or two small little things over the years.
Does anybody know of something equivalent to that? | I don't know of anything equivalent, but you can look at the source to [libpurple](http://developer.pidgin.im/wiki/WhatIsLibpurple) and roll your own without a terrible amount of difficulty. | If you're prepared to do some hard work with the original source code, you could update it to support the current version of the MSN protocol:
<http://msnpiki.msnfanatic.com/index.php/Main_Page> | MSN with Python | [
"",
"python",
"msn",
""
] |
this is a rather basic java question
I have an array containing String that i want to sort using java.util.Arrays.sort
when i write
```
String[] myArray = {"A","B","C"};
java.util.Arrays.sort(myArray);
```
it gets sorted correctly
however when i have
```
String[] myArray = new String[10];
myArray[0] = "A";
myArray[1] = "B";
myArray[2] = "C";
java.util.Arrays.sort(myArray);
```
sort throws a nullreferenceexception
i'm pretty sure its something really dumb i just dont get right now. I have to new the String, because hardcoding default values doesnt get anyone, anywhere. | When you initialize the second array, you only initialize the first three elements. The other elements are initialized to null and thus can't be sorted. | In the source, the method uses compareTo() as a sort condition. Obviously, invoking compareTo() on *null*, will raise a NullPointerException. As its mentioned in Java Docs that,
> All elements in the array must be
> mutually comparable (that is,
> e1.compareTo(e2) must not throw a
> ClassCastException for any elements
> e1 and e2 in the array)
Of course here its not about ClassCastException, but invocation of comapreTo() is obvious.
**[Edited]**
P.S. Figuring this out from Exception Stack Trace is your best bet. | Basic array initialization and sorting question | [
"",
"java",
"arrays",
"new-operator",
""
] |
I am working on a lab for school that runs 10 trails of 10000 5 card hands. I have to find flushes and pairs in each hands. I have to find the percentage of pairs and flushs per trail.
My problem is when I try to get the percentage of a pair of one trail for example
```
double percent = total_pairs/10000;
```
or
```
double percent = 5600/10000;
```
my output becomes 0 when I want to print out 2 decimal places I get the following
```
0.00
```
using this code
```
cout<<setiosflags(ios::fixed | ios::showpoint);
cout<<setprecision(2)<<percent<<endl;
```
but I still get zero I get actual numbers when I cast it like so
```
double percent = (double) 5600/10000;
```
is this correct because I don't want it to truncate my outputs or am I missing something
Hope you can understand me. | Is "total\_pairs" an int? If so, the divide is done as integer division. You need to explicitly cast one of the numbers to a double (and the other will be automatically promoted to double):
```
double percent = ((double)total_pairs)/10000; // or just simply 10000.0
``` | Yes, this is the case, the following performs integer division. The result (0) is then converted to a double.
```
double percent = 5600/10000
```
The line below forces 5600 to be a double so now you have actual division of doubles
```
double percent = (double) 5600/10000
```
If one of your numbers is a constant you can just make sure you use decimal format for it to force floating point division:
```
double percent = 5600.0/10000
```
Another trick I sometimes use is to multiply by a 1.0 which converts what follows to a double:
```
double percent = 1.0 * inta / intb
``` | How do I divide two integers inside a double variable? | [
"",
"c++",
""
] |
My Java RCP application prompts the user for username and password upon start-up. How could I use these credentials to do authentication against the native OS without using JNI to port some C libraries? Thanks!
PS. If possible, pure Java implementation without using third-party libraries will be very much preferable. | AFAIK, this just isn't possible without involving native extensions to Java in some manner - there is no Java API for this.
You could take a look at the [JNA project](https://github.com/twall/jna/). It uses native code, but you don't have to write any - it's done for you.
---
EDIT: If all you want to do is *validate* the username/password, then I believe that the JNDI/LDAP direction may work for you - I've done this before on the AS/400 from Java, though I was not totally happy with the end result.
If you want to cause the O/S to recognize your JVM process as being credentialed as a particular user, you are going to need some form of access to non-portable native API's.
BTW, what O/S(s) are we talking about.
---
EDIT2: I am going to post fragments from how I used LDAP to verify a username/password, on the off chance that that is what you are after; these are lifted straight from my code, not intended to be directly compilable.
This is some of the first Java code I ever wrote, please be merciful:
```
import java.security.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
...
private Hashtable masterEnv; // master environment settings
private String authMethod; // default authentication method
...
public void init() {
// NOTE: Important to use a non-pooled context and a clone of the environment so that this authenticated
// connection is not returned to the pool and used for other operations
masterEnv=new Hashtable();
masterEnv.put(Context.INITIAL_CONTEXT_FACTORY,ldapFactory);
masterEnv.put(Context.PROVIDER_URL,providerUrl);
masterEnv.put(Context.SECURITY_PROTOCOL,secProtocol);
masterEnv.put(Context.REFERRAL,"follow");
masterEnv.put("com.sun.jndi.ldap.connect.pool","false");
authMethod=System.getProperty("authenticationMethod","simple");
}
...
private void verifyUserPassword(String ui, String pw, String am) throws NameNotFoundException, AuthenticationException, AuthenticationNotSupportedException, NamingException, NamingException {
// ui=user ID
// pw=password
// am=authentication method
DirContext lc=null; // ldap context object
Hashtable le; // ldap environment object
if(am.length()==0) { am=authMethod; }
le=(Hashtable)masterEnv.clone();
le.put(Context.SECURITY_AUTHENTICATION,am);
le.put(Context.SECURITY_PRINCIPAL ,ui);
le.put(Context.SECURITY_CREDENTIALS ,pw);
lc=new InitialDirContext(le);
lc.close();
}
``` | You could validate using JNDI and LDAP (assuming you are using LDAP/Active Directory for verification). Check out [this thread](http://forums.sun.com/thread.jspa?threadID=581444) for more details on how to do this. | How to authenticate against native OS in Java and without using JNI? | [
"",
"java",
"authentication",
""
] |
Out of interest when working with SQL statements should I always use the fully qualifed column name (tablename.columnname) even if only working with one table e.g.
```
SELECT table.column1, table.column2 FROM table
``` | It's better if you do - it doesn't add any complexity, and it can prevent errors in the future.
But in a well-defined system, you shouldn't *have* to - it's like namespaces in programming languages. The ideal is not to have conflicts, but it can clutter the code with the superfluous use of explicit names.
-Adam | I generally follow these rules:
When using a single table, it is not necessary to use the table name prefix:
```
SELECT col1, col2 FROM table1
```
For multiple tables, use the full table name. Aliases can be confusing, especially when doing multiple joins:
```
SELECT table1.col1, table2.col2 FROM table1 INNER JOIN table2 on
table1.id = table2.id
```
I see many developers using table aliases, but particularly in large projects with multiple developers, these can become cryptic. A few extra keystrokes can provide a lot more clarity in the code.
If may, however, become necessary to use a column alias when columns have the same name. In that case:
```
SELECT table1.col1, table2.col1 as table2_col1 FROM table1
INNER JOIN table2 on
table1.id = table2.id
``` | Should I Always Fully Qualify Column Names In SQL? | [
"",
"sql",
"coding-style",
""
] |
```
for (i=0 ; i<=10; i++)
{
..
..
}
i=0;
while(i<=10)
{
..
..
i++;
}
```
In for and while loop, which one is better, performance wise? | (update)
Actually - there is one scenario where the `for` construct is more efficient; looping on an array. The compiler/JIT has optimisations for this scenario *as long as you use* `arr.Length` *in the condition*:
```
for(int i = 0 ; i < arr.Length ; i++) {
Console.WriteLine(arr[i]); // skips bounds check
}
```
In this very specific case, it skips the bounds checking, as it already knows that it will never be out of bounds. Interestingly, if you "hoist" `arr.Length` to try to optimize it manually, you prevent this from happening:
```
int len = arr.Length;
for(int i = 0 ; i < len ; i++) {
Console.WriteLine(arr[i]); // performs bounds check
}
```
However, with other containers (`List<T>` etc), hoisting is fairly reasonable as a manual micro-optimisation.
(end update)
---
Neither; a for loop is evaluated as a while loop under the hood anyway.
For example 12.3.3.9 of ECMA 334 (definite assignment) dictates that a for loop:
```
for ( for-initializer ; for-condition ; for-iterator ) embedded-statement
```
is essentially equivalent (from a **Definite assignment** perspective (not quite the same as saying "the compiler must generate this IL")) as:
```
{
for-initializer ;
while ( for-condition ) {
embedded-statement ;
LLoop:
for-iterator ;
}
}
```
> with continue statements that target
> the for statement being translated to
> goto statements targeting the label
> LLoop. If the for-condition is omitted
> from the for statement, then
> evaluation of definite assignment
> proceeds as if for-condition were
> replaced with true in the above
> expansion.
Now, this doesn't mean that the compiler has to do exactly the same thing, but in reality it pretty much does... | I would say they are the same and you should never do such micro-optimizations anyway. | for and while loop in c# | [
"",
"c#",
"for-loop",
"while-loop",
""
] |
Should I load child forms in the Constructor or the FormLoad()?
I have some code that is calling a custom class that embeds a form in a control. I had originally been declaring my child forms outside the Constructor and then calling a FormPaint() routine in the FormLoad() to then load the forms like so:
```
internal frmWWCMCPHost frmWWCMCPHost = new frmWWCMCPHost();
internal frmWWCEnrollmentHost frmWWCEnrollmentHost = new frmWWCEnrollmentHost();
internal frmWWCMemberHost frmWWCMemberHost = new frmWWCMemberHost();
public frmWWCModuleHost()
{
InitializeComponent();
}
private void frmWWCModuleHost_Load(object sender, EventArgs e)
{
FormPaint();
}
public void FormPaint()
{
WinFormCustomHandling.ShowFormInControl(frmWWCMCPHost, ref tpgMCP, FormBorderStyle.FixedToolWindow,-4,-2);
WinFormCustomHandling.ShowFormInControl(frmWWCMemberHost, ref tpgMember, FormBorderStyle.FixedToolWindow, -4, -2);
WinFormCustomHandling.ShowFormInControl(frmWWCEnrollmentHost, ref tpgEnrollment, FormBorderStyle.FixedToolWindow, -4, -2);
// Call each top-Level (visible) tabpage's form FormPaint()
frmWWCMCPHost.FormPaint();
}
```
Now I have been shown a much better way of embedding forms in container controls, as it relates to my custom class, [here](https://stackoverflow.com/questions/543087/custom-class-for-dealing-with-embedding-in-forms/545864#545864).
My question is where should I be loading these as the example has them being loaded in the Constructor declaring them at the same time, like so:
```
public frmWWCModuleHost()
{
InitializeComponent();
WinFormCustomHandling.ShowFormInContainerControl(tpgCaseNotes, new XfrmTest());
}
```
Which is, obviously, much less code. By loading in the constructor will I be using far more unnecessary resources? Will I be gaining anything? How do I decide? | Interesting question Mr\_Mom. My recommendation would be to use your constructors to do only the setup needed for the sub forms and put off loading the sub forms until the parent formLoad().
As for resources, gains, and losts... I do not know. | I prefer to use form's constructor. I mean setup everything **before** a form would be shown, not after. | To Form Load() or Not to Form Load() | [
"",
"c#",
".net",
"winforms",
"constructor",
"form-load",
""
] |
Quick question, wondering if anyone knew what the limit is for SO\_RCVBUF under Windows. | SO\_RCVBUF in winsock is not limited by the TCP window size. At least for pre-Vista stacks. It would be limited by non-paged pool availability, which is a whole different topic.
So you can make it quite big, if you want to.
Obligatory unsolicited advice: If you are using a large buffer because you are receiving infrequently, I would look into asynchronous I/O with events/select/completion ports. | I can't recall for sure, but I believe Windows supports the POSIX function `fpathconf()` with the `_PC_SOCK_MAXBUF` option. If so, this is exactly what you're looking for. | max value for SO_RCVBUF in Windows? | [
"",
"c++",
"c",
"windows",
"networking",
"sockets",
""
] |
When writing a C# application whose #1 priority is to **never crash**, how often should I used a try-catch block?
Can I encapsulate all the statements in a method in try-catch blocks?
```
public void SomeMethod()
{
try
{
// entire contents of the function
// library calls
// function calls
// variable initialization .. etc
}
catch (Exception e)
{
// recover
}
}
```
What are the downsides to wrapping everything in try-catch blocks? | The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.
Also, you don't want to use try/catch for control flow. Consider this (bad code):
```
try {
FileStream fs = File.Open("somefile.txt", FileMode.Open);
} catch (Exception ex) {
MessageBox.Show("The file does not exist. Please select another file");
}
```
You'll get more performance from some thing like File.Exists. such as:
```
if(!File.Exists("somefile.txt"))
MessageBox.Show("The file does not exist.")
```
EDIT:
found the [MSDN direct quote](http://msdn.microsoft.com/en-us/library/ms973839.aspx):
> Finding and designing away
> exception-heavy code can result in a
> decent perf win. Bear in mind that
> this has nothing to do with try/catch
> blocks: you only incur the cost when
> the actual exception is thrown. You
> can use as many try/catch blocks as
> you want. Using exceptions
> gratuitously is where you lose
> performance. For example, you should
> stay away from things like using
> exceptions for control flow. | This is a big topic. Start [here](http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx) for some excellent discussion of Exception handling best practices and be prepared for a religious war...
[Code Analysis Team Blog](http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx)
[Martin Fowler - Fail Fast](http://www.martinfowler.com/ieeeSoftware/failFast.pdf)
[MSDN on Exception Handling](http://msdn.microsoft.com/en-us/library/ms229005.aspx)
[Checked vs Unchecked Exceptions](http://www.javapractices.com/topic/TopicAction.do?Id=129)
My own opinion is that for the most part you use "try/finally" a lot, but "catch" very little. The problem is that if you attempt to catch and handle Exceptions in the wrong instances, you may inadvertently put your application in a bad state. As a rule, use dev and test to learn where you actually need to handle an exception. Those will be places that you can't check. i.e. you shouldn't really need to handle nullreference or filenotfound because you can proactively check for those. Only exceptions you know may happen, but you can't do anything about. Beyond that, for the sake of your data's state, let it crash.
If you are swallowing exceptions, it generally means you don't understand your program or why you are getting an exception. Catching System.Exception is the poster child of code smells... | How often should I use try and catch in C#? | [
"",
"c#",
""
] |
I'm trying to customise a log4net file path to use a property I have set in the `log4net.GlobalContext.Properties` dictionary.
```
log4net.GlobalContext.Properties["LogPathModifier"] = "SomeValue";
```
I can see that this value is set correctly when debugging through it. and then in my configuration
```
<file type="log4net.Util.PatternString"
value="Logs\%appdomain_%property{LogPathModifier}.log" />
```
However, the output of this gives me "\_(null).log" at the end of the path. What gives? | I ran into the same behavior and solved it by setting the global variable before calling the XmlConfigurator... Here is what I am successfully using:
log4net.config details:
```
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<File type="log4net.Util.PatternString" value="App_Data/%property{LogName}" />
...
</appender>
```
Global.asax details:
```
private static readonly log4net.ILog log = log4net.LogManager.GetLogger("Global.asax");
void Application_Start(object sender, EventArgs e)
{
// Set logfile name and application name variables
log4net.GlobalContext.Properties["LogName"] = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["ApplicationName"] = GetType().Assembly.GetName().Name;
// Load log4net configuration
System.IO.FileInfo logfile = new System.IO.FileInfo(Server.MapPath("log4net.config"));
log4net.Config.XmlConfigurator.ConfigureAndWatch(logfile);
// Record application startup
log.Debug("Application startup");
}
```
Hope this helps... | Add type=`log4net.Util.PatternString` into File element | How do I use a GlobalContext property in a log4net appender name? | [
"",
"c#",
"log4net",
""
] |
We are currently implementing a portal to our web based services. The portal and services are written with Seam and we are using OpenLDAP to store the security data such as users, groups and permissions. So far we have looked at writing our own code to access LDAP but are there any existing APIs that we could use? | If you're a Spring user, I'd look into the [Spring LDAP modules](http://www.springsource.org/ldap). They're beautifully done; they follow the idiom laid down by their JDBC implementation. Very clean, very nice. | We did this for our web application a while ago and investigated the following:
<http://developers.sun.com/sw/docs/examples/appserver/ldap.html>
However, we ended up just using the LDAP support built in to Tomcat, since basic authentication was enough for us.
Here is an example on how we set up out authentication in tomcat:
<http://blog.mc-thias.org/?c=1&more=1&pb=1&tb=1&title=tomcat_ldap_authentication> | Best Framework For Accessing OpenLDAP With Seam & JBoss AS? | [
"",
"java",
"seam",
"openldap",
""
] |
This is a detail question for C#.
Suppose I've got a class with an object, and that object is protected by a lock:
```
Object mLock = new Object();
MyObject property;
public MyObject MyProperty {
get {
return property;
}
set {
property = value;
}
}
```
I want a polling thread to be able to query that property. I also want the thread to update properties of that object occasionally, and sometimes the user can update that property, and the user wants to be able to see that property.
Will the following code properly lock the data?
```
Object mLock = new Object();
MyObject property;
public MyObject MyProperty {
get {
lock (mLock){
return property;
}
}
set {
lock (mLock){
property = value;
}
}
}
```
By 'properly', what I mean is, if I want to call
```
MyProperty.Field1 = 2;
```
or whatever, will the field be locked while I do the update? Is the setting that's done by the equals operator inside the scope of the 'get' function, or will the 'get' function (and hence the lock) finish first, and then the setting, and then 'set' gets called, thus bypassing the lock?
Edit: Since this apparently won't do the trick, what will? Do I need to do something like:
```
Object mLock = new Object();
MyObject property;
public MyObject MyProperty {
get {
MyObject tmp = null;
lock (mLock){
tmp = property.Clone();
}
return tmp;
}
set {
lock (mLock){
property = value;
}
}
}
```
which more or less just makes sure that I only have access to a copy, meaning that if I were to have two threads call a 'get' at the same time, they would each start with the same value of Field1 (right?). Is there a way to do read and write locking on a property that makes sense? Or should I just constrain myself to locking on sections of functions rather than the data itself?
Just so that this example makes sense: MyObject is a device driver that returns status asynchronously. I send it commands via a serial port, and then the device responds to those commands in its own sweet time. Right now, I have a thread that polls it for its status ("Are you still there? Can you accept commands?"), a thread that waits for responses on the serial port ("Just got status string 2, everything's all good"), and then the UI thread which takes in other commands ("User wants you to do this thing.") and posts the responses from the driver ("I've just done the thing, now update the UI with that"). That's why I want to lock on the object itself, rather than the fields of the object; that would be a huge number of locks, a, and b, not every device of this class has the same behavior, just general behavior, so I'd have to code lots of individual dialogs if I individualized the locks. | No, your code won't lock access to the members of the object returned from `MyProperty`. It only locks `MyProperty` itself.
Your example usage is really two operations rolled into one, roughly equivalent to this:
```
// object is locked and then immediately released in the MyProperty getter
MyObject o = MyProperty;
// this assignment isn't covered by a lock
o.Field1 = 2;
// the MyProperty setter is never even called in this example
```
In a nutshell - if two threads access `MyProperty` simultaneously, the getter will briefly block the second thread until it returns the object to the first thread, *but* it'll then return the object to the second thread as well. Both threads will then have full, unlocked access to the object.
**EDIT in response to further details in the question**
I'm still not 100% certain what you're trying to achieve, but if you just want atomic access to the object then couldn't you have the calling code lock against the object itself?
```
// quick and dirty example
// there's almost certainly a better/cleaner way to do this
lock (MyProperty)
{
// other threads can't lock the object while you're in here
MyProperty.Field1 = 2;
// do more stuff if you like, the object is all yours
}
// now the object is up-for-grabs again
```
Not ideal, but so long as all access to the object is contained in `lock (MyProperty)` sections then this approach will be thread-safe. | Concurrent programming would be pretty easy if your approach could work. But it doesn't, the iceberg that sinks that Titanic is, for example, the client of your class doing this:
```
objectRef.MyProperty += 1;
```
The read-modify-write race is pretty obvious, there are worse ones. There is absolutely nothing you can do to make your property thread-safe, other than making it immutable. It is your client that needs to deal with the headache. Being forced to delegate that kind of responsibility to a programmer that is least likely to get it right is the Achilles-heel of concurrent programming. | C# thread safety with get/set | [
"",
"c#",
"locking",
"properties",
"thread-safety",
""
] |
My question is as follows:
I have to read a big XML file, 50 MB; and anonymise some tags/fields that relate to private issues, like name surname address, email, phone number, etc...
I know exactly which tags in XML are to be anonymised.
```
s|<a>alpha</a>|MD5ed(alpha)|e;
s|<h>beta</h>|MD5ed(beta)|e;
```
where `alpha` and `beta` refer to any characters within, which will also be hashed, using probably an algorithm like [MD5](http://en.wikipedia.org/wiki/MD5).
I will only convert the tag value, not the tags themselves.
I hope, I am clear enough about my problem. How do I achieve this? | Using regexps is indeed dangerous, unless you know exactly the format of the file, it's easy to parse with regexps, and you are sure that it will not change in the future.
Otherwise you could indeed use XML::Twig,as below. An alternative would be to use XML::LibXML, although the file might be a bit big to load it entirely in memory (then again, maybe not, memory is cheap these days) so you might have to use the pull mode, which I don't know much about.
Compact XML::Twig code:
```
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
use Digest::MD5 'md5_base64';
my @tags_to_anonymize= qw( name surname address email phone);
# the handler for each element ($_) sets its content with the md5 and then flushes
my %handlers= map { $_ => sub { $_->set_text( md5_base64( $_->text))->flush } } @tags_to_anonymize;
XML::Twig->new( twig_roots => \%handlers, twig_print_outside_roots => 1)
->parsefile( "my_big_file.xml")
->flush;
``` | You have to do something like the following in Python.
```
import xml.etree.ElementTree as xml # or lxml or whatever
import hashlib
theDoc= xml.parse( "sample.xml" )
for alphaTag in theDoc.findall( "xpath/to/tag" ):
print alphaTag, alphaTag.text
alphaTag.text = hashlib.md5(alphaTag.text).hexdigest()
xml.dump(theDoc)
``` | How can I anonymise XML data for selected tags? | [
"",
"python",
"xml",
"perl",
"anonymize",
""
] |
I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but **Moq doesn't seem to offer a way to override a static method** (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?
Here is a trivial example that fails with the usual ***"Invalid expectation on a non-overridable member"***. This is a bad example of needing to mock an extension method, but it should do.
```
public class SomeType {
int Id { get; set; }
}
var ListMock = new Mock<List<SomeType>>();
ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))
.Returns(new SomeType { Id = 5 });
```
As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon. | Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible. | If you can change the extension methods code then you can code it like this to be able to test:
```
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
public static class MyExtensions
{
public static IMyImplementation Implementation = new MyImplementation();
public static string MyMethod(this object obj)
{
return Implementation.MyMethod(obj);
}
}
public interface IMyImplementation
{
string MyMethod(object obj);
}
public class MyImplementation : IMyImplementation
{
public string MyMethod(object obj)
{
return "Hello World!";
}
}
```
So the extention methods are only a wrapper around the implementation interface.
(You could use just the implementation class without extension methods which are sort of syntactic sugar.)
And you can mock the implementation interface and set it as implementation for the extensions class.
```
public class MyClassUsingExtensions
{
public string ReturnStringForObject(object obj)
{
return obj.MyMethod();
}
}
[TestClass]
public class MyTests
{
[TestMethod]
public void MyTest()
{
// Given:
//-------
var mockMyImplementation = new Mock<IMyImplementation>();
MyExtensions.Implementation = mockMyImplementation.Object;
var myClassUsingExtensions = new MyClassUsingExtensions();
// When:
//-------
var myObject = new Object();
myClassUsingExtensions.ReturnStringForObject(myObject);
//Then:
//-------
// This would fail because you cannot test for the extension method
//mockMyImplementation.Verify(m => m.MyMethod());
// This is success because you test for the mocked implementation interface
mockMyImplementation.Verify(m => m.MyMethod(myObject));
}
}
``` | How do I use Moq to mock an extension method? | [
"",
"c#",
"mocking",
"moq",
"extension-methods",
""
] |
Can someone give me an example of a Unmanaged C++ HTML Client with proxy support?
I want to do some get and posts inside my unmanaged c++ programs, ideally I would like to allow for proxy server configuration, or just use the IE defaults.
I am not looking for hand outs, just something to go by, as I can't seem to find too much on this. | Call [WinHttpGetIEProxyConfigForCurrentUser](http://msdn.microsoft.com/en-us/library/aa384096.aspx) to get the proxy configuration and then use the HTTP stack of your choice. I would avoid implementing your own psuedo HTTP stack, getting it right is more work then you probably think. | What, [seriously?](http://www.mozilla.com/) | Can someone give me an example of a Unmanaged C++ HTML Client with proxy support? | [
"",
"c++",
"html",
"http",
""
] |
I'm trying to write what I hope is a simple application tracker. That is, whenever a new application starts, or a running application becomes current, I want to note the event and start timing it's time "on top".
I have code that lists all the current applications that are running, and some code that tells me the top window (always my test console app, naturally).
What I think I'm missing is the Windows event stream to monitor or something.
I'm using .NET (C# preferred).
Any hints, tips or cheats available?
Thanks - Jonathan | I think the best way to do this would be using windows "hooks" (i.e. [SetWindowsHookEx](http://msdn.microsoft.com/en-us/library/ms644990.aspx)). These allow you to hook in to windows core functionality, specifically there is one called `WH_CALLWNDPROC` which calls a user function any time any window in the system receives a message.
You could use this to globally listen for messages that bring a window to the foreground, and/or messages for user interaction (mouse, keyboard).
However, this is a raw Windows API function primarily meant for use in a C/C++ windows DLL. You can implement it in C#, but that is a can of worms you may not want to open. But opening it would probably be the best way of doing what you're asking. | I'm not sure if there's a way to hook a Windows event, but simply polling System.Diagnostics.Process.GetProcesses() at regular intervals (say, 100ms) and looking for new/removed processes (comparing by process ID) should do the job. Also, Process.StartTime will give you the time at which the process began.
Caveat: This method may be require a higher amount of processing compare an event-based method (none of which I am aware). Processes that start and end between each poll will not be observed, but this ought to be quite rare indeed for a reasonably high polling frequency (and perhaps you do not even care about these processes anyway). Saying this, these are minor detractions, and I would recommend you at least test this solution as it is fairly simple. | Find the Current Windows Application | [
"",
"c#",
"windows",
""
] |
I've been trying to learn Python, and while I'm enthusiastic about using closures in Python, I've been having trouble getting some code to work properly:
```
def memoize(fn):
def get(key):
return (False,)
def vset(key, value):
global get
oldget = get
def newget(ky):
if key==ky: return (True, value)
return oldget(ky)
get = newget
def mfun(*args):
cache = get(args)
if (cache[0]): return cache[1]
val = apply(fn, args)
vset(args, val)
return val
return mfun
def fib(x):
if x<2: return x
return fib(x-1)+fib(x-2)
def fibm(x):
if x<2: return x
return fibm(x-1)+fibm(x-2)
fibm = memoize(fibm)
```
Basically, what this is supposed to do is use closures to maintain the memoized state of the function. I realize there are probably many faster, easier to read, and in general more 'Pythonic' ways to implement this; however, my goal is to understand exactly how closures work in Python, and how they differ from Lisp, so I'm not interested in alternative solutions, just why my code doesn't work and what I can do (if anything) to fix it.
The problem I'm running into is when I try to use `fibm` - Python insists that `get` isn't defined:
```
Python 2.6.1 (r261:67515, Feb 1 2009, 11:39:55)
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import memoize
>>> memoize.fibm(35)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "memoize.py", line 14, in mfun
cache = get(args)
NameError: global name 'get' is not defined
>>>
```
Seeing as I'm new to Python, I don't know if I've done something wrong, or if this is just a limitation of the language. I'm hoping it's the former. :-) | The problem is in your scoping, not in your closures. If you're up for some heavy reading, then you can try <http://www.python.org/dev/peps/pep-3104/>.
If that's not the case, here's the simple explanation:
The problem is in the statement `global get` . `global` refers to the outermost scope, and since there isn't any global function `get`, it throws.
What you need, is an access specifier for variables in the enclosing scope, and not the global scope.
In python 3.0, as I've tested, the `nonlocal` keyword is exactly what you need, in the place of `global`.
```
nonlocal get
...
```
In python 2.x, I just removed the `global get` and the `oldget` references and it works properly. | ```
def memoize(fn):
get = [lambda key: (False, None)]
def vset(args):
value = fn(*args)
oldget = get[0]
def newget(key):
if args == key:
return (True, value)
return oldget(key)
get[0] = newget
return value
def mfun(*args):
found, value = get[0](args)
if found:
return value
return vset(args)
return mfun
CALLS = 0
def fib(x):
global CALLS
CALLS += 1
if x<2: return x
return fib(x-1)+fib(x-2)
@memoize
def fibm(x):
global CALLS
CALLS += 1
if x<2: return x
return fibm(x-1)+fibm(x-2)
CALLS = 0
print "fib(35) is", fib(35), "and took", CALLS, "calls"
CALLS = 0
print "fibm(35) is", fibm(35), "and took", CALLS, "calls"
```
Output is:
```
fib(35) is 9227465 and took 29860703 calls
fibm(35) is 9227465 and took 36 calls
```
Similar to other answers, however this one works. :)
The important change from the code in the question is assigning to a non-global non-local (get); however, I also made some improvements while trying to maintain your `*`cough`*`*broken*`*`cough`*` closure use. Usually the cache is a dict instead of a linked list of closures. | Closures in Python | [
"",
"python",
"closures",
"lexical-scope",
""
] |
Suppose you have these tables: `RestaurantChains`, `Restaurants`, `MenuItems` - with the obvious relations between them. Now, you have tables `Comments` and `Ratings`, which store the customer comments/ratings about chains, restaurants and menu items. What would be the best way to link these tables? The obvious solutions could be:
* Use columns `OwnerType` and `OwnerID` in the tables `Comments` and `Ratings`, but now I can't add foreign keys to link comments/ratings with the objects they are ment for
* Create separate tables of `Comments` and `Ratings` for each table, e.g. `MenuItemRatings`, `MenuItemComments` etc. This solution has the advantage that all the correct foreign keys are present and has the obvious disadavantage of having lots and lots of tables with basically the same structure.
So, which solution works better? Or is there even a better solution that I don't know about? | Since comments about a menu item are different from comments about a restaurant (even if they happen to share the same structure) I would put them in separate tables and have the appropriate FKs to enforce some data integrity in your database.
I don't know why there is an aversion to having more tables in your database. Unless you're going from 50 tables to 50,000 tables you're not going to see a performance problem due to large catalog tables (and having more, smaller tables in this case should actually give you better performance). I would also tend to think that it would be a lot clearer to understand when dealing with tables called "Menu\_Item\_Comments" and "Restaurant\_Comments" than it would to deal with a table called "Comments" and not knowing what exactly is really in it just by the name of it. | How about this [alt text http://www.freeimagehosting.net/uploads/8241ff5c76.png](http://www.freeimagehosting.net/uploads/8241ff5c76.png) | Owner ID type database fields | [
"",
"sql",
"database",
"database-design",
""
] |
I have a script which combines a number of files into one, and it breaks when one of the files has UTF8 encoding. I figure that I should be using the `utf8_decode()` function when reading the files, but I don't know how to tell which need decoding.
My code is basically:
```
$output = '';
foreach ($files as $filename) {
$output .= file_get_contents($filename) . "\n";
}
file_put_contents('combined.txt', $output);
```
Currently, at the start of a UTF8 file, it adds these characters in the output: `` | Try using the [`mb_detect_encoding` function](http://www.php.net/manual/en/function.mb-detect-encoding.php). This function will examine your string and attempt to "guess" what its encoding is. You can then convert it as desired. As [brulak suggested](https://stackoverflow.com/questions/505562/detect-file-encoding-in-php#answer-505582), however, you're probably better off converting *to* UTF-8 rather than *from*, to preserve the data you're transmitting. | `mb_detect_encoding` function should be your last choice. That could return the *wrong* encoding. Linux command `file -i /path/myfile.txt` is working great. In PHP you could use:
```
function _detectFileEncoding($filepath) {
// VALIDATE $filepath !!!
$output = array();
exec('file -i ' . $filepath, $output);
if (isset($output[0])){
$ex = explode('charset=', $output[0]);
return isset($ex[1]) ? $ex[1] : null;
}
return null;
}
``` | Detect file encoding in PHP | [
"",
"php",
"utf-8",
"character-encoding",
""
] |
I include a JS file in a user control. The host page has multiple instances of the user control.
The JS file has a global variable that is used as a flag for a JS function. I need the scope of this variable be restricted to the user control. Unfortunately, when I have multiple instances of the control, the variable value is overwritten.
What's the recommended approach in a situation like this? | I would recommend refactoring your code such that all the common JS logic is stored in one place, not in every UserControl. This will reduce the size of your page by a good margin.
You can pass in the id of the UserControl to the common JS method(s) to differentiate between the UserControls.
For the issue of limiting the scope of your 'UserControl' variable, you could store some sort of a Key/Value structure to keep your UserControl-specific value - the Key would be the UserControl clientID, and the value would be the variable that you're interested in.
For example:
```
var UCFlags = new Object();
//set the flag for UserControl1:
UCFlags["UC1"] = true;
//set the flag for UserControl2:
UCFlags["UC2"] = false;
```
To access them, you simply pass the ClientID of the UserControl in to the UCFlags array:
```
myFlag = UCFlags["UC1"];
```
On the server-side, you can replace the constant strings "UC1" or "UC2" with
```
<%= this.ClientID %>
```
like this:
```
myFlag = UCFlags["<%= this.ClientID %>"];
```
You can still use the <%= this.ClientID %> syntax here even though the bulk of the JS is in a separate file; simply set
```
UCFlags["<%= this.ClientID %>"] = value;
```
before the call to embed the JS file. | Some options are to dynamically generate the javascript based on the ClientId of the User Control. You could dynamically generate the global variable for example.
Another option and one I would recommend is to encapsulate the global variable and function within an object, then your user control can emit the JS to create an instance of that object (Which can be dynamically named thus letting you scope the object as you see fit).
# Edit
I don't have a working code sample that I can share but, I have done this in a couple different ways. the easiest method is to do this in the markup of your user control.
```
<script language='javascript'>
var <%=this.ClientID%>myObject=new myObject();
</script>
```
Assuming your control has a clientId of myControl this will create a variable myControlmyObject.
Another way to do this would be to generate the script in the code behind you could register it using: `Page.ClientScript.RegisterStartupScript()`. | Multiple user controls and javascript | [
"",
"asp.net",
"javascript",
""
] |
I have the following code:
```
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
```
How can I get it to parse XML contained within a String instead of a file? | I have this function in my code base, this should work for you.
```
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
```
also see [this similar question](https://stackoverflow.com/questions/33262) | One way is to use the version of parse that takes an InputSource rather than a file
A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader
So something like
```
parse(new InputSource(new StringReader(myString))) may work.
``` | In Java, how do I parse XML as a String instead of a file? | [
"",
"java",
"xml",
"string",
"file",
"parsing",
""
] |
I'm using Mockito to write a unit test in Java, and I'd like to verify that a certain method is the *last one* called on an object.
I'm doing something like this in the code under test:
```
row.setSomething(value);
row.setSomethingElse(anotherValue);
row.editABunchMoreStuff();
row.saveToDatabase();
```
In my mock, I don't care about the order in which I edit everything on the row, but it's very important that I *not* try to do anything more to it after I've saved it. Is there a good way to do this?
Note that I'm not looking for verifyNoMoreInteractions: it doesn't confirm that saveToDatabase is the last thing called, and it also fails if I call anything on the row that I don't explicitly verify. I'd like to be able to say something like:
```
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verifyTheLastThingCalledOn(row).saveToDatabase();
```
If it helps, I'm switching to Mockito from a JMock test that did this:
```
row.expects(once()).method("saveToDatabase").id("save");
row.expects(never()).method(ANYTHING).after("save");
``` | I think it requires more custom work.
```
verify(row, new LastCall()).saveToDatabase();
```
and then
```
public class LastCall implements VerificationMode {
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
InvocationMatcher matcher = data.getWanted();
Invocation invocation = invocations.get(invocations.size() - 1);
if (!matcher.matches(invocation)) throw new MockitoException("...");
}
}
```
Previous Answer:
You are right. verifyNoMoreInteractions is what you need.
```
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verify(row).editABunchMoreStuff();
verify(row).saveToDatabase();
verifyNoMoreInteractions(row);
``` | Not 100% on topic but I was just looking to find the opposite of verify, and this was the only relevant result, it ends up I was after Mockito.verifyZeroInteractions(mock);
Just incase anyone else ends up here looking for this... | Use Mockito to verify that nothing is called after a method | [
"",
"java",
"unit-testing",
"mocking",
"mockito",
""
] |
select u.user, g.group, u2g.something
from users, groups, u2g
where users.u = u2g.u and groups.g = u2g.g
that returns data like this:
```
user, group, something
----------------------
1 , 3, a
1 , 5, b
2 , 3, c
3 , 3, d
4 , 5, e
```
now I would like to limit this query in such a way that it only shows users which are **both** in groups 3 and 5 - so it would only return {1,3, a} , {1,5, b} for my example data.
edit: I added another column to the data because there may be an incorrect solution using a group by.
edit2: sorry, I was misled by documentation. MySQL 4.0 does not support subqueries :(
edit3: This SQL will be generated programatically for any number of groups (well, up to 20 in current specification) so I would like to avoid solutions that give me too much additional coding to do. If a solution will not be found, I will just modify the resulting .Net 1.1 DataTable, but I would like to avoid that if possible.
edit4: any new idea? Perhaps one without subqueries that includes IN (3,5)? | Using double join with groups-table will give you the correct result:
```
select u.user, u2g.something
from users
INNER JOIN u2g ON users.u = u2g.u
INNER JOIN groups g1 ON u2g.g = g1.g AND g1.group = 3
INNER JOIN groups g2 ON u2g.g = g2.g AND g2.group = 5
/* try this for two rows, one for each group */
INNER JOIN groups ON u2g.g = groups.g
```
However, this doesn't exactly match your request, that you want two rows, one for each group. This will only give you one row, you might be able to join it once more with groups therefor rendering two rows.
Another example (if you're selecting using the same groupID that you map against ):
```
SELECT u.uID, gm.something
FROM cdcms_users u
inner join cdcms_group_memberships gm1 on gm1.uID = u.uID AND gm1.gID = 32
inner join cdcms_group_memberships gm2 on gm2.uID = u.uID AND gm2.gID = 33
``` | Why is `groups` used in the query? Its only accessed field (`g`) exists in `u2g`. I imagine you probably want to bring back a boatload of stuff from there as well.
In order to get the sort of resultset you describe without the use of subqueries you end up with a real mess: a quadratic explosion of query text!
You'll need something of the following form:
```
select users.u, groups.g, u2g0.something
from users u, groups g, u2g u2g0, u2g u2g1
where groups.g = 3
and users.u = u2g0.u
and u2g0.g = 3
and users.u = u2g1.u
and u2g1.g = 5
union all
select users.u, groups.g, u2g1.something
from users u, groups g, u2g u2g0, u2g u2g1
where groups.g = 5
and users.u = u2g0.u
and u2g0.g = 3
and users.u = u2g1.u
and u2g1.g = 5
```
Since this is a programmatically generated query, I'll use a web-page-scripting-like notation here to describe the query construction. I will also make the rash and unwarranted simplifying assumption that the group identifiers are not a potential SQL-injection attack vector. :-)
```
<% for(int i = 0; i < requiredGroups.Length; i++) { %>
<% if(i > 0) { %>
union all
<% } %>
select users.u, groups.g, u2g<%=i%>.something
from users u, groups g
<% for(int j = 0; j < requiredGroups.Length; j++) { %>
, u2g u2g<%=j%>
<% } %>
where groups.g = <%=requiredGroups[i]%>
<% for(int j = 0; j < requiredGroups.Length; j++) { %>
and users.u = u2g<%=j%>.u
and u2g<%=j>.g = <%=requiredGroups[j]%>
<% } %>
<% } %>
``` | MySQL 4.0 query help double join in lieu of subqueries | [
"",
"sql",
"select",
"join",
"limit",
""
] |
I asked this question previously ([any-good-tutorial-for-moving-from-eclipse-to-vim](https://stackoverflow.com/questions/495268/any-good-tutorial-for-moving-from-eclipse-to-vim))
From the inputs, I started using GVIM instead of Eclipse. I added `ctags` to it and I am able to navigate now comfortably.
The only problem left for me is "Debugging"? I tried searching for some links, and couldn't find a useful one?
If anyone using or familiar with Java Debugging using vim/Gvim, can provide their inputs/ links/tutorials, it would be very helpful. | Your best bet seems to be integration of the command line debugger `jdb`, one such solution is [yavdb](http://www.vim.org/scripts/script.php?script_id=1954), another is [JavaKit](http://www.vim.org/scripts/script.php?script_id=1154). | Eclim now supports a Java debugger. See <http://eclim.org/vim/java/debug.html> | How to Debug Java Application using VIM/GVIM? | [
"",
"java",
"debugging",
"vim",
"editor",
""
] |
I was reading another answer. And it made me wonder, when do does one need to explicitly call Dispose if I am using `using` statements?
EDIT:
Just to vindicate myself from being a total know-nothing, the reason I asked was because someone on another thread said something implying there was a good reason to have to call Dispose manually... So I figured, why not ask about it? | You don't. The `using` statement does it for you.
---
According to [MSDN](http://msdn.microsoft.com/en-us/library/yh598w02.aspx), this code example:
```
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
```
is expanded, when compiled, to the following code (note the extra curly braces to create the limited scope for the object):
```
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
```
---
**Note:** As [@timvw mentioned](https://stackoverflow.com/questions/545062/when-do-you-need-to-call-idisposable-if-you-are-using-using-statments/545139#545139), if you chain methods or use object initializers in the using statement itself and an exception is thrown, the object won't be disposed. Which makes sense if you look at what it will be expanded to. For example:
```
using(var cat = new Cat().AsDog())
{
// Pretend a cat is a dog
}
```
expands to
```
{
var cat = new Cat().AsDog(); // Throws
try
{
// Never reached
}
finally
{
if (cat != null)
((IDisposable)cat).Dispose();
}
}
```
`AsDog` will obviously throw an exception, since a cat can never be as awesome as a dog. The cat will then never be disposed of. Of course, some people may argue that cats should never be disposed of, but that's another discussion...
Anyways, just make sure that what you do `using( here )` is safe and you are good to go. (Obviously, if the constructor fails, the object won't be created to begin with, so no need to dispose). | Normally you don't. This is the point of the using statement. There is however a situation where you have to be careful:
If you reassign the variable to another value the using statement will only call the Dispose method on the original value.
```
using (someValue = new DisposableObject())
{
someValue = someOtherValue;
}
```
The compiler will even give you a **Warning** about this:
> Possibly incorrect assignment to local 'someValue' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. | When do you need to call IDisposable, if you are using `using` statements? | [
"",
"c#",
".net",
""
] |
I am trying to run a simple SQL statement with DB2 and am having a few problems.
I would like to have a single script in a txt/db2 file and have the engine process all of the commands
Here is the script:
```
CONNECT TO MYDB
CREATE TABLE PERSONS(
PID SMALLINT NOT NULL,
NAME VARCHAR(20) NOT NULL
)
TERMINATE
```
When I run a db2 -f /pathtofile I get:
```
SQL0104N An unexpected token "(" was found following "CREATE TABLE PERSONS".
Expected tokens may include: "END-OF-STATEMENT". SQLSTATE=42601
```
What am I doing wrong? Is there something wrong with my script?
Also, why is it working without ";" terminators at the end of my statements?
Thank you, | May be this will be of help,
<http://www.uc.edu/R/r25/documentation/Version3.2/install_instructions.pdf>:
> The scripts use a semi-colon (;) to terminate each SQL
> command. If you use the DB2 Command Line Processor,
> you should remember to use the “-t” flag.
> ...
> If you do not use the -t flag, you will get errors such as the
> following upon running the db2ct32.sql script:
> create table “ACCOUNTS” (
> DB21034E The command was processed as an SQL statement because it was not a
> valid Command Line Processor command. During SQL processing it returned:
> SQL0104N An unexpected token “(“ was found following “ate table “ACCOUNTS””.
> Expected tokens may include: “END-OF-STATEMENT”. SQLSTATE=42601
So, I would add semicolons and invoke with -t switch whatever nonsense it stands for.
I looked into samples, they use something like
```
db2 -tf "pathtofile"
```
Also with
```
db2 -tvf "pathtofile"
```
you might get more diagnostics.
Don't push proprietary soft to the limits, they are not that wide. | You have a comma after the name line
Change:
```
NAME VARCHAR(20) NOT NULL,
```
to:
```
NAME VARCHAR(20) NOT NULL
``` | Why am I getting this SQL/DB error? | [
"",
"sql",
"db2",
""
] |
I know I can open config files that are related to an assembly with the static `ConfigurationManager.OpenExe(exePath)` method but I just want to open a config that is not related to an assembly. Just a standard .NET config file. | the articles posted by Ricky are very good, but unfortunately they don't answer your question.
To solve your problem you should try this piece of code:
```
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
```
If need to access a value within the config you can use the index operator:
```
config.AppSettings.Settings["test"].Value;
``` | The config file is just an XML file, you can open it by:
```
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
```
and later retrieving values by:
```
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
``` | Loading custom configuration files | [
"",
"c#",
"configuration",
""
] |
Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from `os.getpid()` and I need to check to see if a process with that pid doesn't exist on the machine.
I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use. | Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.
```
import os
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
``` | Have a look at the [`psutil`](https://pypi.python.org/pypi/psutil) module:
> **psutil** (python system and process utilities) is a cross-platform library for retrieving information on **running processes** and **system utilization** (CPU, memory, disks, network) in Python. [...] It currently supports **Linux**, **Windows**, **OSX**, **FreeBSD** and **Sun Solaris**, both **32-bit** and **64-bit** architectures, with Python versions from **2.6 to 3.4** (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.
It has a function called `pid_exists()` that you can use to check whether a process with the given pid exists.
Here's an example:
```
import psutil
pid = 12345
if psutil.pid_exists(pid):
print("a process with pid %d exists" % pid)
else:
print("a process with pid %d does not exist" % pid)
```
For reference:
* <https://pypi.python.org/pypi/psutil>
* <https://github.com/giampaolo/psutil>
* <http://pythonhosted.org/psutil/#psutil.pid_exists> | How to check if there exists a process with a given pid in Python? | [
"",
"python",
"process",
"pid",
""
] |
In python, I can do something like this:
```
List=[3, 4]
def Add(x, y):
return x + y
Add(*List) #7
```
Is there any way to do this or something similar in C#? Basically I want to be able to pass a List of arguments to an arbitrary function, and have them applied as the function's parameters without manually unpacking the List and calling the function explicitly specifying the parameters. | Well, the closest would be reflection, but that is on the slow side... but look at [MethodInfo.Invoke](http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx)... | You can use the params keyword when defining your method and then you can directly put your list (after calling ToArray) in your method call.
```
public static void UseParams(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
```
...which you can later call with the following.
```
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams(myObjArray);
```
For reference: <http://msdn.microsoft.com/en-us/library/w5zay9db.aspx> | Python-like list unpacking in C#? | [
"",
"c#",
"iterable-unpacking",
""
] |
I was wondering if there is an existing control that I could use to achieve what I am trying.
Basically, I have a html table that I display my header information.
It looks something like this:
```
<table class="tableEdit">
<tr>
<th>Job ID</th><td>10</td>
<th>Client</th><td>Tom</td>
</tr>
<tr>
<th>Comments</th><td>Comments are here</td>
</tr>
</table>
```
I am wondering if there is an existing control that I can use as a container. Then I can assign the datasource to that control
and leverage the field values as such.
```
<asp:Somecontrol runat="server" ID="someid">
<table class="tableEdit">
<tr>
<th>Job ID</th><td><%# Eval("Id") %></td>
<th>Client</th><td><%# Eval("Client.Name") %></td>
</tr>
<tr>
<th>Comments</th><td><%# Eval("Comments") %></td>
</tr>
</table>
</asp:Somecontrol>
private void BindHeader()
{
SomeObjectType data = DAL.SomeMethod();
someid.Datasource = data;
someid.DataBind();
}
```
Is there anything out there to do this? I want to be able to control the layout of the fields within the container.
Thanks. | Actually what i was after was the FormView control.
I had never used this control previously, but this is the exact control for what i wanted to do.
It allows to to mark a region, assign a datasource and bind items as desired.
```
<asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource2" Visible="false">
<ItemTemplate>
<table style="border-collapse: collapse;" class="tableEdit">
<tr>
<td>ClientId</td>
<td><asp:Label ID="ClientId" runat="server" Text='<%# Eval("ClientId") %>' /></td>
</tr>
<tr>
<td>ClientCode</td>
<td><asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ClientCode") %>' /></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Name") %>' /></td>
</tr>
<tr>
<td>BillingContactName</td>
<td><asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("BillingContactName") %>' /></td>
</tr>
```
Thanks AI W for your input. Repeater is also suitable but for binding "a" record, FormView is ideal i think. Thanks. | Use the GridView control. You can attach CSS classes to many properties in Design mode for controlling the layout. | Assigning Datasource to a region | [
"",
"c#",
"asp.net",
"forms",
"datagrid",
""
] |
```
Using MailMessage email = new MailMessage();email.IsBodyHtml = true;
```
Is it possible to set the font for the message?
Also, maybe it's a quirk but p and br tags come out the same for me? Is this normal? | You can use CSS:
```
<style>
p {color:#999; font-family:arial;} /*grey*/
</style>
```
You are limited to what fonts are install on the receivers machine. | I would suggest researching using a style sheet attribute to change the font size.
Not sure what you mean by the 'and tags come out the same for me' part... come out the same as what?
...charles beat me to it | Font in Html mail | [
"",
"c#",
".net",
"html",
"email",
""
] |
I have the following code:
```
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
for ($i=0; $i<count($row); $i++)
{
(DO THING HERE)
$row[$i] = str_replace("\n", " ", $row[$i]);
$row[$i] = str_replace("\r", " ", $row[$i]);
}
}
```
I basically want to do, if the associative array key is equal to "email" (so $row['email']) then append "@gmail.com" to it. | See the `MYSQL_NUM` you have there? [That is going to return your data using the column indexes as keys (ie 0, 1, 2, etc)](http://www.php.net/manual/en/function.mysql-fetch-array.php).
You must either
a) find out which column index the `email` field is and do:
```
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
// 'email' is in column number 5
$row[5] .='@gmail.com';
for ($i=0; $i<count($row); $i++)
{
$row[$i] = str_replace("\n", " ", $row[$i]);
$row[$i] = str_replace("\r", " ", $row[$i]);
}
}
```
b) OR you can change `MYSQL_NUM` to `MYSQL_ASSOC`, and do:
```
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$row['email'] .='@gmail.com';
foreach($row as &$value)
{
$value = str_replace("\n", " ", $value);
$value = str_replace("\r", " ", $value);
}
}
```
Note the `"&"` before `$value` to make it a reference.
I would do the latter (I prefer `foreach` to `for` :) | Use a foreach loop and get both the key and the value for the assoc array.
```
foreach($row as $key => &$value)
{
if($key == 'email') $value .= "@gmail.com";
}
```
Also you should be using `mysql_fetch_array($result, MYSQL_ASSOC)` if you want an associative array returned.
A more efficient way to append to the email key would be something like:
```
if(isset($row['email']))
$row['email'] .= '@gmail.com';
```
Instead of looping through all the columns. | Get PHP assoc array key in loop | [
"",
"php",
""
] |
I've been using Simple Modal and i feel it doesn't live up to what i need at the moment.
Is there a Modal Box that supports loading external files and allows those external files to close the modal box and redirect the parent page to some url.
An example of what i want to do. You have a list of users, you could click "Add user" and a Modal Box with the form pops up, you fill that in and submit it. That would close the box and reload the user list page so you would see the user in the list.
Then you could click "Edit user" and a Modal Box with the user info filled in the form fields would pop up and you could edit, submit and it would close and refresh.
I know this can be done if i have the user info form as a hidden div for each user but this will not scale well and it is a lot of overhead data.
I found some [code about this on Google Code](http://code.google.com/p/simplemodal/source/browse/branches/simplemodal-1.2/test/iframe.html?r=159) but just can't get it to work (possibly different simple modal version
I am willing to change to another modal box tool also.
UPDATE:
Do either Thickbox or Fancybox support being closed from a child IFrame element? | [Fancybox](http://fancy.klade.lv/) is also another option. Works similarly to Thickbox
**EDIT:**
It appears after some playing around that the plugin does not natively support closing the Fancybox through an child iframe element. I think that this is certainly achievable with a little effort (I started ***hacking*** together something [here](http://jsbin.com/epabi), although I stress that this was simply a POC and does not work as the button within the iframe removes the fancybox div wrapper from the DOM and therefore does not display when you click the google image again).I am wondering however, if an iframe is the right lines to go down.
For adding a user, my thought would be that you could present the user with a modal form like the one on the [Monster site you get when you click 'Sign In.'](http://jobsearch.monster.co.uk/Browse.aspx) Once you click add user, make an AJAX call to your datasource to insert a new user and then on returning success, you could either initiate a page refresh or use AJAX to update the list.
For editing a user, once a user is selected, you could make an AJAX call with a user id to populate a modal form with the user details retrieved from your data source when the AJAX call returns success. Once you have finished editing the user, make an AJAX call to update your datasource and then again, initiate a page refresh or use AJAX to update the list.
Instead of the page refresh or final AJAX call in each scenario, you could simply use JavaScript/jQuery to update the list/ list details, depending on whether a user has been added or edited, respectively. | Sounds like you already found the answer but for the benefit of others you can close an iFrame implementation of FancyBox by using the following JavaScript in the iFrame:
```
parent.$.fn.fancybox.close();
``` | JQuery Modal Boxes and Iframe | [
"",
"javascript",
"jquery",
"iframe",
"refresh",
"modal-dialog",
""
] |
Probably a simple question but I only have Linux to test this code on where \_\_declspec(dllexport) is not needed. In the current code \_\_declspec(dllexport) is in front of all files in the .h file but just in front of like 50% of the functions in the cpp file so I am wondering if they are really needed in the cpp file at all ? | No, its only needed in the header.
Here's a [link](https://web.archive.org/web/20120628222847/http://msdn.microsoft.com/en-us/library/a90k134d(VS.80).aspx) with more info.
Expanding on what Vinay was saying, I've often seen a macro defined
```
#if defined(MODULENAME_IMPORT)
#define EXPORTED __declspec(dllimport)
#elif defined(MODULENAME_EXPORT)
#define EXPORTED __declspec(dllexport)
#endif
```
Then in your header you do
```
void EXPORTED foo();
```
set the defines accordingly in the project settings for the project doing the import/exporting. | No, it is not required in cpp file. Only in declaration it is required.
For Example if I have a class CMyClass. If I want to export this then .h will have
.h Server code
\_\_declspec(dllexport) CMyClass
{
};
In the client code i.e., which uses this class you have to forward declare the class as
Client code
\_\_declspec(dllimport) CMyClass;
// Code to use the class | Is __declspec(dllexport) needed in cpp files | [
"",
"c++",
"windows",
"dll",
""
] |
> **Possible Duplicate:**
> [How to compare two word documents?](https://stackoverflow.com/questions/90075/how-to-compare-two-word-documents)
How can you get the diff of two word .doc documents programatically?
Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui diff tool)
I imagine if you grabed the docs via COM and converted the output to text you could provide *some* diff funcitonality. Thoughts?
Is there a way to do this without windows and COM?
(Perferably in python, but I'm open to other solutions)
**UPDATE**
Original question asking about msword diff tools was a duplicate of: (Thanks Nathan)
[How to compare two word documents?](https://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/) | Use this option in Word 2003:
> **T**ools | Compare and Merge **D**ocuments
Or this in Word 2007:
> **R**eview | Co**m**pare
It prompts you for a file with which to compare the file you're editing.
---
This question is a duplicate of [How to compare two word documents?](https://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/), and this answer is a duplicate of [my answer there](https://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/90277#90277). | I am not sure whether you are looking for following functionality.
Microsoft itself has the option in office suite,
Please check
<http://support.microsoft.com/kb/306484> | Get the diff of two MSWord doc files and output to html | [
"",
"python",
"ms-word",
"diff",
""
] |
I have a snippet of code that writes the data alphabetically from a database *ACROSS 3 columns* on a web page.
Example:
```
a result b result c result
d result e result f result
g result h result i result
```
I need instead to display it *alphabetically DOWN the columns*, like this:
```
a result d result g result
b result e result h result
c result f result i result
```
Keeping in mind I have about 100 data results, it would display the first 1/3 in column one descending, then start a new column and continue, breaking it into 3 equal parts.
The code I have now that sorts across the rows is:
```
<%
GL="<table width="+Z+"100%"+Z+"border=0 cellpadding=3 celspacing=3>"
sql="select * from guideDef order by guideDesc;"
rs.open sql,adoCon
colCount=0
do while not rs.eof
colCount=(colCount+1) mod 3
if colCount=1 then GL=GL+"<tr>"
GL=GL+"<td valign=middle id=menu1 width="+Z+"33%"+Z+">"+E
GL=GL+"<a href="+Z+"shop.asp?guide="+rs("guide")+"&city=Plantation"+Z+">"+E
GL=GL+rs("guideDesc")+"</a></td>"
if colCount=0 then GL=GL+"</tr>"
GL=GL+E
rs.moveNext
loop
rs.close
if colCount=1 then GL=GL+"<td> </td><td> </td></tr>"+E
if colCount=2 then GL=GL+"<td> </td></tr>"+E
GL=GL+"</table>"
response.write GL
%>
```
Thanks in advance for any help. I don't write code, so I have tried for hours to change this without success. | I believe this code will solve your problem:
```
<%
Set rs = Server.CreateObject("ADODB.RecordSet")
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open "your connection string here"
Const COLUMN_COUNT = 3
Const adOpenStatic = 3
sql = "SELECT guide, guideDesc FROM guideDef ORDER BY guideDesc;"
rs.Open sql, adoCon, adOpenStatic
CellsRemain = rs.RecordCount Mod COLUMN_COUNT
RowCount = (rs.RecordCount - CellsRemain) / COLUMN_COUNT
Response.Write "<div>Rendering " & rs.RecordCount & " records to a " & _
COLUMN_COUNT & " x " & RowCount & " table with " & _
CellsRemain & " stand-alone cells.</div>"
Response.Write "<table width=""100%"" border=""0"" cellpadding=""3"" celspacing=""3"">" & vbCrLf
done = 0
cell = 0
While done < rs.RecordCount
Response.Write "<tr>" & vbCrLf
While cell < COLUMN_COUNT And done < rs.RecordCount
cell = cell + 1
done = done + 1
guide = "" & rs("guide")
guideDesc = "" & rs("guideDesc")
url = "shop.asp?guide=" + Server.UrlEncode(guide) + "&city=Plantation"
Response.Write "<td>"
Response.Write "<a href=""" & Server.HtmlEncode(url) & """>"
Response.Write Server.HtmlEncode(guideDesc)
Response.Write "</td>" & vbCrLf
If cell < COLUMN_COUNT Then rs.Move RowCount
Wend
If done < rs.RecordCount Then
rs.Move -1 * ((COLUMN_COUNT - 1) * RowCount - 1)
cell = 0
Else
While cell < COLUMN_COUNT
Response.Write "<td> </td>" & vbCrLf
cell = cell + 1
Wend
End If
Response.Write "</tr>" & vbCrLf
Wend
Response.Write "</table>" & vbCrLf
%>
```
This renders your table the way you want it:
```
A E H
B F I
C G J
D
```
You can use the `COLUMN_COUNT` constant to control how many columns will be made. The algorithm flexibly adapts to that number.
What the code does is basically this:
1. open a static RecordSet object so we can jump around in it freely
2. calculate how many rows and columns we need to show all records
3. `<tr>`
4. jump down the RecordSet in `RowCount` steps, painting `<td>`s until `<tr>` is full
5. jump back to the record that's after the one we started with in step 4
6. `</tr>`
7. if there are still records left, go to step 3
8. render as many empty cells as we need to make the table well-formed
9. done. | Maybe a better solution is to leave the SQL as is and handle this in the application code rather than as a result of the query. | How can I change SQL data order from rows to columns? | [
"",
"sql",
"asp-classic",
"ado",
""
] |
I'm struggling to define a class method that populates and returns a collection of instances. The issue I don't know how to get around is that I have private attributes to populate.
Let's use the example of a Book class. I don't want the code to directly set (say) the availability of a book. I want the code to have to use a CheckOut method on a Book instance. So we have something like:
```
public class Book
{
private int ID;
private bool pAvailableForCheckout;
public string Title { get; set; }
public bool AvailableForCheckout { get { return pAvailableForCheckout } }
// instance methods
public Book(int BookID)
{
// Load book from DB by ID
}
public CheckOut()
{
// perform everything involved with checking a book out
}
// .. other methods like saving a book, checking out books etc.
// class method
public static List<Book> FindAll()
{
// load Dataset of books
// foreach record in DB, use the Book(int BookID) constructor and add to List
// return list of books
}
}
```
So, I can do use this in my code:
```
foreach(Book curBook in Book.FindAll())
{ /* do something with book */ }
```
The problem with the above implementation is that I have to use N+1 hits to the database to load all the books instead of just 1 query. How do I get around this?
I'm sure this is programming 101, but I needed to ask. | You could create a protected constructor which populates the private properties directly. | The foreach should be iterating over a list of already instantiated objects, they won't need to connect to the DB.
You need to create a constructor that accepts the properties of your book object so that you can instantiate a book from an existing set of data rather than a new hit to the DB.
so:
Constructor:
```
public book (String title, String avail) {Title=title...}
```
And in the method
```
public static void FindAll()
{
List<Books> books = new List<books>();
using (Sqlconnection conn = new sqlconnection(connstring))
using (sqlcommand cmd = new SqlCommand("select title, available from book ", conn)
{
SqlDatareader dr = cmd.executereader()
while (dr.read())
{
books.add(new Book(dr["title"], dr["avail"])
}
}
foreach(Book curBook in Book.FindAll())
{ /* do something with book */ }
}
``` | How to write class methods that return collections of instances | [
"",
"c#",
"class",
"static-methods",
""
] |
I am trying to write a custom code generator that can parse stored procedures. I wrote a few regex, but they don't seem to work all the time. I do have access to the database; does a system query exist that will return the required parameters and possible return values? I have played around with sp\_depends, but it does not seem to include parameters. Are there any other system procs that may be useful for this? ...am I attempting this the wrong way? | The parameters should be available in the metadata tables (I seem to recall they might even be in syscolumns against the object\_id of the proc). Or the [info-schemas](http://msdn.microsoft.com/en-us/library/aa933216(SQL.80).aspx).
However, results are tricker, since SPs don't have very formalilsed output. UDFs have much stronger metadata. The best you can do with an SP (and it is still hit'n'miss) is SET FMT\_ONLY ON, and execute it and hope it doesn't use any extended stored procedures... | You can get the parameters from
```
select c.*
from syscolumns c
inner join sysobjects o on o.id = c.id
where o.type = 'P' and o.name = '<storedProcName>'
```
Return values, as Marc says, is tricky. You could have
```
if (...)
select * from Customers
else
select * from CustomerOrders
```
so, not going to have much success there. Of course I don't know what sort of person would write something like the above, or why, but it's possible, so... | Can I query the parameters and "selected" column names from a stored procedure? | [
"",
"sql",
"code-generation",
""
] |
I am working on a project that is slowly getting larger and larger and the number of active threads used by many different processes is increasing. Lately, I have been taking a closer look at the running threads in the debugger and I have noticed that a lot of my third party libraries have given very poor names to their threads - Timer-0, qtp0, etc. I want other devs unfamiliar with the poorly named threads to know instantly what is running.
Rather than write patches for the libs we are using, does anyone know how to rename the running threads? Or if this is even a good idea? Any suggestions would be appreciated. | If the problem is in open source libraries, then the best solution is to supply patches to those products for better thread naming. Barring a security manager running, you can rename any thread by enumerating threads (as others have mentioned) and applying an arbitrary name to each, but this is a fragile way of naming threads that are not your own. If the 3rd party library changes their naming, you'll have to change your code.
I agree that 3rd party libraries with poorly-named threads make more difficult understanding what is going on in your application. But renaming threads from a 3rd party library is risky. What happens if their next release changes the way they name threads? And how do you handle a 3rd party library that makes no attempt at all to name threads?
EDIT: Add back text that somehow disappeared from the end | Yes, you can change the name of a thread with the [setName()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#setName(java.lang.String)) method.
As for whether it's a good idea, there's no telling for sure, but relying on the thread name for anything other than a human-readable description would be a very poor decision, and most libraries will not do this. Thus, it's unlikely to break anything if you rename them. | Renaming Threads in Java | [
"",
"java",
"multithreading",
"naming",
""
] |
I wanted to do
```
typedef deque type; //error, use of class template requires template argument list
type<int> container_;
```
But that error is preventing me. How do I do this? | You can't (until C++0x). But it could be emulated with:
```
template<typename T>
struct ContainerOf
{
typedef std::deque<T> type;
};
```
used as:
```
ContainerOf<int>::type container_;
``` | deque is not a type. It is a template, used to generate a type when given an argument.
```
deque<int>
```
is a type, so you could do
```
typedef deque<int> container_
``` | typedef std containers? | [
"",
"c++",
"templates",
"typedef",
""
] |
I am working on a name record application and the information is stored in a SQLite database. All columns in the database are TEXT types, except for the date of birth column, which is a DATETIME. The original Access database that I transferred to the SQLite database allowed nulls for the date of birth, so when I copied it over, I set all nulls to DateTime.MinValue.
In my application, the date of birth column is formatted like so:
```
DataGridViewTextBoxColumn dateOfBirth = new DataGridViewTextBoxColumn();
dateOfBirth.HeaderText = "DOB";
dateOfBirth.DataPropertyName = "DateOfBirth";
dateOfBirth.Width = 75;
dateOfBirth.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";
```
My problem is that rows where there is not a date of birth, the database has DateTime.MinValue, which displays in my DataGridView as 01/01/0001.
I am looking for a way to replace the 01/01/0001 with an empty string ("") in my DataGridView.
```
private void resultsGrid_DateFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if(resultsGrid.Columns[e.ColumnIndex].Name.Equals("DateOfBirth"))
{
if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
{
// Set cell value to ""
}
}
}
```
Anyone have an idea how I can replace a DateTime.MinValue in my DataGridView with an empty string? Thanks!
Edit: Casting the cell value with DateTime allows the if statement I have to work, but I am still not able to figure out the coding to replace the MinValues with a blank string. | You just need to cast it to DateTime
```
if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
{
// Set cell value to ""
}
``` | I discovered why the `DateTime.MinValue` was displaying!
This line in the cell formatting section caused the MinValue of "01/01/0001" to display:
```
dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";
```
Without this line, the Date of Birth field in my `datagridview` is left blank.
Barbaros Alp is still correct about what I was trying to do at the time. Thanks everyone! | Replacing a DateTime.MinValue in a DataGridView | [
"",
"c#",
"datetime",
"sqlite",
"datagridview",
""
] |
So I've been trying to figure out the most efficient way to pull off this trick:
I have a two column primary key in the database (an int and a string) and I'm trying to make a cache (I like using dictionaries) and I need to have a way to reference the two values as a key to get the object out.
The key is
```
private struct PageNameOnSite
{
public int siteId;
public string pageName;
}
```
It was suggested to me that I make a class to wrap this instead but that doesn't sound like the best way to use memory once this thing gets 10,000 entries put in it. My understanding that the memory footprint of a struct is smaller than that of a class. | Why not use the PageNameOnSise the key to the Dictionary? You'd need to override a few things but it's not too bad.
```
private struct PageNameOnSite
{
public int siteId;
public string pageName;
public override bool Equals(object obj) {
if ( !obj is PageNameOnSite) { return false; }
var other = (PageNameOnSite)obj;
return sideId == other.siteId && StringComparer.Oridinal.Equals(pageName, other.pageName);
}
public override int GetHashCode() { return sideId + pageName.GetHashCode(); }
}
```
Then you can just use a quick lookup with an id pageName pair
```
public static object Loopup(Dictionary<PageNameOnSite,object> map, int id, string name) {
var key = new PageNameOnSite() { siteId = id, pageName = name};
return map[key];
}
``` | Here's an answer that adheres to KISS:
Why not generate a string as your key, like site|page, i.e., for site = 1 and page=default.aspx, use 1|default.aspx?
I realize it's not the cool OOP way to go, but if your key changes, you'll be changing code anyway. | Multi column primary key mapped to a Dictionary<>... aka Struct vs. Class | [
"",
"c#",
".net",
"data-structures",
""
] |
Thread to wait **infinitely** in a loop until a **flag state** change, then call function.
**pseudo code illustration:**
```
while (true)
{
while (!flag)
{
sleep(1);
}
clean_upfunction();
}
```
**Currently**:
* Using the multithreaded versions of the [**C run-time libraries only**](http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx)
**No:**
* MFC
**Question:**
* Is there a more efficient way of implementing the above
* A waitForStateChange() - similar to above - in the threading library | For Windows (which you have this tagged for), you want to look at [WaitForSingleObject](http://msdn.microsoft.com/en-us/library/ms687032.aspx). Use a Windows Event (with CreateEvent), then wait on it; the other thread should call SetEvent. All native Windows, no MFC or anything else required. | If you're not on Windows, and are instead on a POSIXish box, `pthread_cond_wait` is the best match:
```
/* signaler */
pthread_mutex_lock(mutex);
flag = true;
pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);
/* waiter */
pthread_mutex_lock(mutex);
do {
pthread_cond_wait(cond, mutex);
} while (!flag);
pthread_mutex_unlock(mutex);
```
The classic self-pipe trick is easier and cooler though :) Works on systems without `pthreads` too.
```
/* setup */
int pipefd[2];
if (pipe(pipefd) < 0) {
perror("pipe failed");
exit(-1);
}
/* signaler */
char byte = 0;
write(pipefd[0], &byte, 1); // omitting error handling for brevity
/* waiter */
char byte;
read(pipefd[1], &byte, 1); // omitting error handling for brevity
```
The waiter will block on the `read` (you don't set `O_NONBLOCK`) until interrupted (which is why you should have error handling) or the signaler writes a byte. | Efficiently wait for a flag state change without blocking resources? | [
"",
"c++",
"windows",
"visual-studio-2008",
"performance",
""
] |
I want to write a simple servlet in JBoss which will call a method on a Spring bean. The purpose is to allow a user to kick off an internal job by hitting a URL.
What is the easiest way to get hold of a reference to my Spring bean in the servlet?
JBoss web services allow you to inject a WebServiceContext into your service class using an @Resource annotation. Is there anything comparable that works in plain servlets? A web service to solve this particular problem would be using a sledgehammer to crush a nut. | Your servlet can use WebApplicationContextUtils to get the application context, but then your servlet code will have a direct dependency on the Spring Framework.
Another solution is configure the application context to export the Spring bean to the servlet context as an attribute:
```
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="jobbie" value-ref="springifiedJobbie"/>
</map>
</property>
</bean>
```
Your servlet can retrieve the bean from the servlet context using
```
SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
``` | There is a much more sophisticated way to do that. There is `SpringBeanAutowiringSupport`inside `org.springframework.web.context.support` that allows you building something like this:
```
public class MyServlet extends HttpServlet {
@Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
```
This will cause Spring to lookup the `ApplicationContext` tied to that `ServletContext` (e.g. created via `ContextLoaderListener`) and inject the Spring beans available in that `ApplicationContext`. | Access Spring beans from a servlet in JBoss | [
"",
"java",
"spring",
"jakarta-ee",
"servlets",
"jboss",
""
] |
I have a flag attribute enumeration that is behind a web service as follows:
```
[Serializable,Flags]
public enum AccessLevels
{
None = 0,
Read = 1,
Write = 2,
Full = Read | Write
}
```
My problem is the consumer of my web service does not have the original constant values of the enum. The resulting proxy class client side has something that amounts to this:
```
{
None = 1,
Read = 2,
Write = 4,
Full = 8
}
```
And thus when the consumer is checking for "Read" access this will be false even when "testItem" is "Full"
```
((testItem & Svc.Read) == Svc.Read)
```
How can I properly provide flags over a web service?
EDIT:
According to [this](http://ikriv.com:8765/en/prog/info/dotnet/WebServices_and_Enums.html) article it may not be possible to do what I am looking to do. Ivan Krivyakov states
> Imperfect Transparency of Enums
>
> It turns out that enums are not as
> transparent as we'd like them to be.
> There are three sticky issues:
>
> 1. If server-side code declares an enum and assigns specific numeric
> values to its members, these values
> will not be visible to the client.
> 2. If server-side code declares a [Flags] enum with "compound" mask
> values (as in White = Red|Green|Blue),
> it is not properly reflected on the
> client side.
> 3. If server or client transmits an "illegal" value which is outside of
> the scope of the enum, it causes an
> exception in XML de-serializer on the
> other side.
So I wonder if this is just a limitation and is not possible. | I have done extensive research on this and found that it is not possible to serialize enumeration constants through a web service. Note that to accomplish your goal you don't need the enumerations None or Full. These two enumerations can be implied with read / write combination:
You could assume full access if your AccessLevels = Read | Write
and none if your AccessLevels = 0 [nothing]
Your enumerations would look like this:
```
[Serializable,Flags]
public enum AccessLevels
{
Read = 1,
Write = 2
}
``` | I had a similar problem and got round it by adding another web service to return the currect flag values first.
Those then became the values I used in the compare.
Might not be the cleanest solution but it works.
Edit:
My original answer suggested that the values are passed across as a separate web service rather than within an enum.
However, poking around, it appears that an enumeration of 0,1,2 being mapped to 1,2,4 across a web service (even that the [Flags] attribute is set) is a common problem.
The solution suggested by a number of people is to modify the original enumeration definition and start from 1 rather than 0. | Flags with web services | [
"",
"c#",
".net",
"web-services",
"flags",
""
] |
I'm aware that you can set an `onclick` handler like this:
```
my_a = document.createElement('a');
my_a.onclick = somefunction;
```
... but what if `somefunction` takes a parameter? For the sake of simplicity, let's say I need to pass it the string `"x"`. Is it possible to dynamically set the `onclick` handler to `somefunction('x')`? | Then you would create an anonymous function:
```
my_a = document.createElement('a');
my_a.onclick = function() { somefunction(x); };
```
If you also like to refer to `this` in `somefunction`, you could use a library like [Prototype][1], then you would do something like:
```
my_a = document.createElement('a');
my_a.onclick = somefunction.bind(this, x);
```
[1]: <http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding> Blog article | You want to use what is called an **anonymous function**:
```
my_a.onclick = function() {
somefunction(arguments, here);
};
```
If you want to retain "this" you can [utilize closures](https://stackoverflow.com/questions/325004/call-function-with-this):
```
my_a.onclick = function() {
somefunction.call(my_a, arguments, here);
};
``` | How, using JavaScript, do I change an <a> tag's onclick event handler to a function with parameters? | [
"",
"javascript",
"html",
""
] |
I already make extensive use of prototype and don't want to add an extra framework like YUI.
I need a javascript calendar which enables me to customize rendering of calendar-cells on a cell by cell basis. (For rendering events, prices, etc. on a certain date) .
YUI Calendar makes this possible, but I already make extensive use of prototype and don't want to add an extra framework like YUI.
Does anyone know a good alternative?
Thanks,
Brits | Here's one: [CalendarView](http://calendarview.org/) and another [CalendarDateSelect](http://code.google.com/p/calendardateselect/). | Have you thought of upgrading from *Prototype* to **YUI** or **jQuery**? Both would give you a lot more functionality than prototype and both have excellent calendar options. | prototype javascript calendar with customizable rendering of cells like YUI Calendar | [
"",
"javascript",
"calendar",
"prototypejs",
""
] |
I have searched the web but all the ones readily available are where you specificy a date and it counts down to that date. What I need is something which will simply count down from "27 minutes and 43 seconds" (in that format) all the way down to 0 from whenever they land on the page, anyone got any snippets available? | Something like this should do the trick. I'm bored and decided to do it myself instead of Googling. Just set the minutes and seconds at the top and change the call to countdown inside the onload to the id of the element you want it to update.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
var interval;
var minutes = 1;
var seconds = 5;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "countdown's over!";
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
</head>
<body>
<div id='countdown'></div>
</body>
</html>
``` | I have made a simple countdown you can use.
It is generating the format:
> DAYS X, HOURS X, MINUTES X, SECONDS X
The JS:
```
countIt();
function countIt(){
year = 2013;
month = 05;
day = 28;
hours = 12;
minutes = 00;
seconds = 00;
setTimeout(function(){
endDate = new Date(year, (month - 1), day, hours, minutes, seconds, 00);
thisDate = new Date();
thisDate = new Date(thisDate.getFullYear(), thisDate.getMonth(), thisDate.getDate(), thisDate.getHours(), thisDate.getMinutes(), thisDate.getSeconds(), 00, 00);
var daysLeft = parseInt((endDate-thisDate)/86400000);
var hoursLeft = parseInt((endDate-thisDate)/3600000);
var minutsLeft = parseInt((endDate-thisDate)/60000);
var secondsLeft = parseInt((endDate-thisDate)/1000);
seconds = minutsLeft*60;
seconds = secondsLeft-seconds;
minutes = hoursLeft*60;
minutes = minutsLeft-minutes;
hours = daysLeft*24;
hours = (hoursLeft-hours) < 0 ? 0 : hoursLeft-hours;
days = daysLeft;
startCount(days, hours, minutes,seconds);
}, 1000);
}
function startCount(days, hours, minutes, seconds){
document.getElementById("counter").innerHTML="DAYS "+days+", HOURS "+hours+", MINUTES "+minutes+", SECONDS: "+seconds;
countIt();
}
```
The HTML:
```
<div id="counter"></div>
```
[Click here to see it live](http://jsfiddle.net/RUTVj/2/) | Javascript Countdown | [
"",
"javascript",
""
] |
I am writing a program in c++ which implements a doubly-linked list that holds a single character in each node. I am inserting characters via the append function:
```
doubly_linked_list adam;
adam.append('a');
```
This function is implemented as follows:
```
//Append node
node* append(const item c){
//If the list is not empty...
if(length){
//maintain pointers to end nodes
node* old_last_node = last;
node* new_last_node = new node;
//re-assign the double link and exit link
old_last_node->next = new_last_node;
new_last_node->back = old_last_node;
new_last_node->next = NULL;
//re-assign the last pointer
last = new_last_node;
}
//If this is the first node
else{
//assign first and last to the new node
last = first = new node;
//assign nulls to the pointers on new node
first->next = first->back = NULL;
}
//increase length and exit
++length;
return last;
}
```
However, I think there is an issue, perhaps with the way C++ handles characters. When I go to print my list, somehow I never get the characters to print which I have appended to my list. This is what I'm using to print:
```
//Friendly output function
friend std::ostream& operator << (std::ostream& out_s, const doubly_linked_list& source_list){
//create iteration node pointer
node* traverse_position = source_list.first;
//iterate through, reading from start
for(int i = 1; i <= source_list.length; ++i){
//print the character
out_s << (traverse_position->data);
traverse_position = traverse_position->next;
}
//return the output stream
return out_s;
}
```
I just get crap when I print it. It prints characters that I never appended to my list - you know, just characters just from somewhere in the memory. What could possibly be causing this? | Where are you assigning the value `c` in the `append()` function? I fear you may have concentrated too much on the doubly-linked-list part and not enough on the storing-data part. :) | As others have already mentioned, you forgot to store the characters you were supposedly appending. It's a reasonable mistake to make. To avoid it in the future, you can let the compiler help you.
Most compilers offer *warnings* about things that are technically OK, but probably aren't what you really want to do. In your case, you declared the parameter `c`, but you never used it. With warnings enabled, your compiler could have noticed that and told you that you hadn't used it. That would probably have been enough of a reminder for you that you weren't finished writing that function.
GCC's option to enable common warnings is `-Wall`. (That's "W" for "warning," plus "all"; it has nothing to do with walls. But it's not really *all* warnings, either.) For example:
```
g++ -Wall list-program.cpp
```
Other compilers have similar options. Check your compiler's documentation for details. | c++ outputting and inputting a single character | [
"",
"c++",
"list",
"linked-list",
"char",
"cout",
""
] |
I wrote a method to convert a given number from days to milliseconds:
```
private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
expireTimeInMilliseconds = expireTimeInDays * 24 * 60 * 60 * 1000;
}
```
I had a hard time to figure out what I did wrong. Now my question:
***Is that error so obvious ?***
The corrected method:
```
private long expireTimeInMilliseconds;
...
public void setExpireTimeInDays(int expireTimeInDays)
{
expireTimeInMilliseconds = ((long) expireTimeInDays) * 24 * 60 * 60 * 1000;
}
```
If I don't convert the integer to long before calculating, I get a complete wrong result. | Is it obvious? I guess it depends on how long you've been using Java and how many times you've had to deal with milliseconds. Of course, it should be okay for up to about 24 days...
I think the biggest hint should be that `System.currentTimeMillis()` returns a `long`. That's a good indication that a number of milliseconds can get big. The type of the variable you're setting should be a good hint too.
Of course, you've *also* got to know that if you do arithmetic operations with ints, the result will be `int` with wrap-around on overflow. Whether that's sufficiently obvious or not could be debated, but it would be a pretty pointless discussion. In C# if you turned overflow checking on, you'd have found the bug pretty quickly - but then not many developers do that (indeed, I don't although I probably should). | Yes, it's pretty obvious if you've done it before. Any time you see a string of numbers multiplied out you should automatically start thinking about integer overflow errors. In this case you're set to overflow if `expireTimeInDays` is more than 24. Technically you should be thinking about overflow errors **any time you're working with integers**, but multiplying a group of them like this should be a very big red flag. | Java multiply operation behavior | [
"",
"java",
"overflow",
"integer-overflow",
""
] |
First of all I was wondering if I should use Qt and Windows together. If so should I use VC++ 6.0 IDE or another one? | I'm of the opinion that no one should be using VC++ 6.0 for anything at this point. Your better off just getting the express version of 2008 if your worried about cost. | Check out [QT Creator](http://www.qtsoftware.com/developer/qt-creator)
> Qt® Creator is a new, lightweight,
> cross-platform integrated development
> environment (IDE) designed to make
> development with the Qt application
> framework even faster and easier.
>
> Tailored specifically to the needs of
> Qt developers creating cross-platform
> applications Focuses on features that
> boost developer productivity without
> getting in their way Helps new Qt
> developers get up and running faster
> Open and extendable; integrates
> familiar tools and file formats
>
> The final release of Qt Creator is
> planned for early 2009. | Qt and VC++ 6.0 IDE? | [
"",
"c++",
"windows",
"user-interface",
"qt",
"visual-c++-6",
""
] |
In terms of performance , what would be better. Using PHP to echo all the HTML output so I can pepper it with the various bits of working code and variables or escape HTML to php periodically throughout the documents.
I know there may be some readability issues but I'm not to worried about that.
Thanks all!
Example 1
```
echo '<html>',
'<body>',
'The content of the ',$container,' element is displayed in your ', $other_container,
'</body>',
'</html>';
```
OR
```
<html>
<body>
The content of the <?php echo $container; ?> element is displayed in your <?php echo $other_container; ?>
</body>
</html>
``` | It's all about which you find the most readable. Of course, this will vary with each situation. If you were doing an entire page, and there were large sections which did not have any PHP in it, then I'd break out of PHP and just write the plain HTML, whereas if there was a section which had a lot of PHP variables, I'd do it all in PHP.
For example:
```
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
```
versus:
```
<?php
echo "<table>"
. "<tr>"
. "<td colspan=\"" . $numCols . "\">"
. $a . ", " . $b . " and " . $c
. "</td>"
. "</tr>"
. "</table>"
; ?>
```
Or
```
<?php
echo "<table>
<tr>
<td colspan='{$numCols}'>
{$a}, {$b}, and {$c}
</td>
</tr>
</table>";
?>
```
Also don't forget about `printf`
```
<?php
printf("<table>"
. "<tr>"
. "<td colspan=\"%d\">%s, %s and %s</td>"
. "</tr>"
. "</table>"
, $numCols
, $a
, $b
, $c
);
?>
``` | **Whichever is easiest to read.**
The performance difference is pretty negligible compared to almost any other issue you'll encounter. Definitely readability is hands down the first issue here. | Escape HTML to PHP or Use Echo? Which is better? | [
"",
"php",
"html",
"performance",
""
] |
We'd like to support some hardware that has recently been discontinued. The driver for the hardware is a plain 32-bit C DLL. We don't have the source code, and (for legal reasons) are not interested in decompiling or reverse engineering the driver.
The hardware sends tons of data quickly, so the communication protocol needs to be pretty efficient.
Our software is a native 64-bit C++ app, but we'd like to access the hardware via a 32-bit process. What is an efficient, elegant way for 32-bit and 64-bit applications to communicate with each other (that, ideally, doesn't involve inventing a new protocol)?
The solution should be in C/C++.
Update: several respondents asked for clarification whether this was a user-mode or kernel-mode driver. Fortunately, it's a user-mode driver. | If this is a real driver (kernel mode), you're SOL. Vista x64 doesn't allow installing unsigned drivers. It this is just a user-mode DLL, you can get a fix by using any of the standard IPC mechanisms. Pipes, sockets, out-of-proc COM, roughly in that order. It all operates on bus speeds so as long as you can buffer enough data, the context switch overhead shouldn't hurt too much. | I would just use sockets. It would allow you to use it over IP if you need it in the future, and you won't be tied down to one messaging API. If in the future you wish to implement this on another OS or language, you can. | Interprocess communication between 32- and 64-bit apps on Windows x64 | [
"",
"c++",
"winapi",
"interprocess",
""
] |
Let's say I have a generic member in a class or method, like so:
```
public class Foo<T>
{
public List<T> Bar { get; set; }
public void Baz()
{
// get type of T
}
}
```
When I instantiate the class, the `T` becomes `MyTypeObject1`, so the class has a generic list property: `List<MyTypeObject1>`. The same applies to a generic method in a non-generic class:
```
public class Foo
{
public void Bar<T>()
{
var baz = new List<T>();
// get type of T
}
}
```
I would like to know what type of objects the list of my class contains. So what type of `T` does the list property called `Bar` or the local variable `baz` contain?
I cannot do `Bar[0].GetType()`, because the list might contain zero elements. How can I do it? | If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:
```
Type typeParameterType = typeof(T);
```
If you are in the lucky situation of having `object` as a type parameter, see [Marc's answer](https://stackoverflow.com/a/557349/3649914). | (note: I'm assuming that all you know is `object` or `IList` or similar, and that the list could be any type at runtime)
If you know it is a `List<T>`, then:
```
Type type = abc.GetType().GetGenericArguments()[0];
```
Another option is to look at the indexer:
```
Type type = abc.GetType().GetProperty("Item").PropertyType;
```
Using new TypeInfo:
```
using System.Reflection;
// ...
var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0];
``` | How to get the type of T from a member of a generic class or method | [
"",
"c#",
".net",
"generics",
""
] |
I'm working with the [Java Sound API](http://java.sun.com/products/java-media/sound/), and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.
Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.
A thanks in advance to anyone that can assist :-)
```
import javax.sound.sampled.*;
public class SoundAudit {
public static void main(String[] args) { try {
System.out.println("OS: "+System.getProperty("os.name")+" "+
System.getProperty("os.version")+"/"+
System.getProperty("os.arch")+"\nJava: "+
System.getProperty("java.version")+" ("+
System.getProperty("java.vendor")+")\n");
for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
System.out.println("Mixer: "+thisMixerInfo.getDescription()+
" ["+thisMixerInfo.getName()+"]");
Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
if (thisLineInfo.getLineClass().getName().equals(
"javax.sound.sampled.Port")) {
Line thisLine = thisMixer.getLine(thisLineInfo);
thisLine.open();
System.out.println(" Source Port: "
+thisLineInfo.toString());
for (Control thisControl : thisLine.getControls()) {
System.out.println(AnalyzeControl(thisControl));}
thisLine.close();}}
for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
if (thisLineInfo.getLineClass().getName().equals(
"javax.sound.sampled.Port")) {
Line thisLine = thisMixer.getLine(thisLineInfo);
thisLine.open();
System.out.println(" Target Port: "
+thisLineInfo.toString());
for (Control thisControl : thisLine.getControls()) {
System.out.println(AnalyzeControl(thisControl));}
thisLine.close();}}}
} catch (Exception e) {e.printStackTrace();}}
public static String AnalyzeControl(Control thisControl) {
String type = thisControl.getType().toString();
if (thisControl instanceof BooleanControl) {
return " Control: "+type+" (boolean)"; }
if (thisControl instanceof CompoundControl) {
System.out.println(" Control: "+type+
" (compound - values below)");
String toReturn = "";
for (Control children:
((CompoundControl)thisControl).getMemberControls()) {
toReturn+=" "+AnalyzeControl(children)+"\n";}
return toReturn.substring(0, toReturn.length()-1);}
if (thisControl instanceof EnumControl) {
return " Control:"+type+" (enum: "+thisControl.toString()+")";}
if (thisControl instanceof FloatControl) {
return " Control: "+type+" (float: from "+
((FloatControl) thisControl).getMinimum()+" to "+
((FloatControl) thisControl).getMaximum()+")";}
return " Control: unknown type";}
}
```
All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:
OS: Windows XP 5.1/x86
Java: 1.6.0\_07 (Sun Microsystems Inc.)
```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
Source Port: MICROPHONE source port
Control: Microphone (compound - values below)
Control: Select (boolean)
Control: Microphone Boost (boolean)
Control: Front panel microphone (boolean)
Control: Volume (float: from 0.0 to 1.0)
Source Port: LINE_IN source port
Control: Line In (compound - values below)
Control: Select (boolean)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
``` | I've never messed with the sound API--this is a good thing to have seen. Thanks.
From a [Dell](http://en.wikipedia.org/wiki/Dell) laptop:
```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SigmaTel Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SigmaTel Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SigmaTel Audio]
Source Port: Stereo Mix source port
Control: Stereo Mix (compound - values below)
Control: Select (boolean)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Source Port: LINE_IN source port
Control: Line In (compound - values below)
Control: Select (boolean)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Source Port: MICROPHONE source port
Control: Microphone (compound - values below)
Control: Select (boolean)
Control: Microphone Boost (boolean)
Control: Volume (float: from 0.0 to 1.0)
Source Port: MICROPHONE source port
Control: Microphone (compound - values below)
Control: Select (boolean)
Control: Microphone Boost (boolean)
Control: Volume (float: from 0.0 to 1.0)
Target Port: SPEAKER target port
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Control: Mute (boolean)
Control: PC Spk Mute (boolean)
Control: SPDIF Interface (boolean)
Control: Wave (compound - values below)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Control: Mute (boolean)
Control: SW Synth (compound - values below)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Control: Mute (boolean)
Control: CD Player (compound - values below)
Control: Volume (float: from 0.0 to 1.0)
Control: Balance (float: from -1.0 to 1.0)
Control: Mute (boolean)
Control: PC Speaker (compound - values below)
Control: Volume (float: from 0.0 to 1.0)
Control: Mute (boolean)
``` | ```
OS: Mac OS X 10.5.6/i386
Java: 1.5.0_16 (Apple Inc.)
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: No details available [Built-in Microphone]
Mixer: No details available [Built-in Input]
``` | What output and recording ports does the Java Sound API find on your computer? | [
"",
"java",
"audio",
"javasound",
""
] |
For a programming class I am creating a blackjack program for the first homework assignment. The professor has given us a sample Card class, which includes the method to add them to a deck. For her deck, she uses an ArrayList, which you can easily Knuth Shuffle with the Collections.shuffle() method.
That method does not work for Stacks though (obviously), but I think a Stack structure would work best for this program because you may pop and push cards into and out of the deck. | Both [`java.util.ArrayList<E>`](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html) and [`java.util.stack<E>`](http://java.sun.com/javase/6/docs/api/java/util/Stack.html) implement the [`java.util.List<E>`](http://java.sun.com/javase/6/docs/api/java/util/List.html) interface, and [`Collections.shuffle()`](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)) takes a `java.util.List<?>` as a parameter. You should be able to pass a `Stack` into `Collections.shuffle()`, unless you're using a different stack implementation that does not implement `java.util.list<E>`. If you are, I would advise you to switch to a different stack implementation. | I guess it's much easier to do stack operations on an ArrayList. | Is there a way to apply the Knuth shuffle to a Stack data structure? | [
"",
"java",
"data-structures",
"stack",
"shuffle",
""
] |
here's my problem:
I want to check if a user insert a real name and surname by checking if they have only letters (of any alphabet) and ' or - in PHP.
I've found a solution here (but I don't remember the link) on how to check if a string has only letters:
```
preg_match('/^[\p{L} ]+$/u',$name)
```
but I'd like to admit ' and - too. (Charset is UTF8)
Can anyone help me please? | Looks like you just need to modify the regex: [\p{L}' -]+ | A little off-topic, but what exactly is the point of validating names?
It's not to prevent fraud; if people are trying to give you a fake name, they can easily type a string of random letters.
It's not to prevent mistakes; typing a punctuation character is only one of the many mistakes you could make, and an unlikely one at that.
It's not to prevent code injection; you should be preventing that by properly encoding your outputs, regardless of what characters they contain.
So why do we all do it? | How to check real names and surnames - PHP | [
"",
"php",
"regex",
"utf-8",
""
] |
I helped a friend out by doing a little web work for him. Part of what he needed was an easy way to change a couple pieces of text on his site. Rather than having him edit the HTML I decided to provide an XML file with the messages in it and I used jQuery to pull them out of the file and insert them into the page.
It works great... In Firefox and Chrome, not so great in IE7. I was hoping one of you could tell me why. I did a fair but of googling but couldn't find what I'm looking for.
Here's the XML:
```
<?xml version="1.0" encoding="utf-8" ?>
<messages>
<message type="HeaderMessage">
This message is put up in the header area.
</message>
<message type="FooterMessage">
This message is put in the lower left cell.
</message>
</messages>
```
And here's my jQuery call:
```
<script type="text/javascript">
$(document).ready(function() {
$.get('messages.xml', function(d) {
//I have confirmed that it gets to here in IE
//and it has the xml loaded.
//alert(d); gives me a message box with the xml text in it
//alert($(d).find('message')); gives me "[object Object]"
//alert($(d).find('message')[0]); gives me "undefined"
//alert($(d).find('message').Length); gives me "undefined"
$(d).find('message').each(function() {
//But it never gets to here in IE
var $msg = $(this);
var type = $msg.attr("type");
var message = $msg.text();
switch (type) {
case "HeaderMessage":
$("#HeaderMessageDiv").html(message);
break;
case "FooterMessage":
$("#footermessagecell").html(message);
break;
default:
}
});
});
});
</script>
```
Is there something I need to do differently in IE? Based on the message box with [object Object] I'm assumed that .find was working in IE but since I can't index into the array with [0] or check it's Length I'm guessing that means .find isn't returning any results. Any reason why that would work perfectly in Firefox and Chrome but fail in IE?
I'm a total newbie with jQuery so I hope I haven't just done something stupid. That code above was scraped out of a forum and modified to suit my needs. Since jQuery is cross-platform I figured I wouldn't have to deal with this mess.
Edit: I've found that if I load the page in Visual Studio 2008 and run it then it will work in IE. So it turns out it always works when run through the development web server. Now I'm thinking IE just doesn't like doing .find in XML loaded off of my local drive so maybe when this is on an actual web server it will work OK.
I have confirmed that it works fine when browsed from a web server. Must be a peculiarity with IE. I'm guessing it's because the web server sets the mime type for the xml data file transfer and without that IE doesn't parse the xml correctly. | Check the content type of the response. If you get messages.xml as the wrong mime type, Internet Explorer won't parse it as XML.
To check the content type, you need access to the XMLHttpRequest object. The normal success callback doesn't pass it as a parameter, so you need to add a generic ajaxComplete or ajaxSuccess event handler. The second parameter for those events is the XMLHttpRequest object. You can call the getResponseHeader method on it to get the content type.
```
$(document).ajaxComplete(function(e, x) {
alert(x.getResponseHeader("Content-Type"));
});
```
Unfortunately there's no way that I know of in Internet Explorer to override what the server sends, so if it's wrong you need to change the server to send "text/xml" for the content type.
Some browsers have a `overrideMimeType` method that you can call before `send` to force it to use "text/xml", but Internet Explorer doesn't support that as far as I know. | Since IE's problem is its xml parser chokes on xml files that are not passed down using the correct "text/xml" header, you can include a bit of code in the **Ajax complete** event:
```
complete: function( xhr, status )
{
alert( "COMPLETE. You got:\n\n" + xhr.responseText ) ;
if( status == 'parsererror' )
{
alert( "There was a PARSERERROR. Luckily, we know how to fix that.\n\n" +
"The complete server response text was " + xhr.responseText ) ;
xmlDoc = null;
// Create the xml document from the responseText string.
// This uses the w3schools method.
// see also
if( window.DOMParser )
{
parser=new DOMParser();
xmlDoc=parser.parseFromString( xhr.responseText,"text/xml" ) ;
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject( "Microsoft.XMLDOM" ) ;
xmlDoc.async = "false" ;
xmlDoc.loadXML( xhr.responseText ) ;
}
$( '#response' ).append( '<p>complete event/xmlDoc: ' + xmlDoc + '</p>' ) ;
$( '#response' ).append( '<p>complete event/status: ' + status + '</p>' ) ;
processXMLDoc( xmlDoc ) ;
}
},
```
## here's a more complete example
```
<!DOCTYPE html>
<html>
<head>
<title>Reading XML with jQuery</title>
<style>
#response
{
border: solid 1px black;
padding: 5px;
}
</style>
<script src="jquery-1.3.2.min.js"></script>
<script>
function processXMLDoc( xmlDoc )
{
var heading = $(xmlDoc).find('heading').text() ;
$( '#response' ).append( '<h1>' + heading + '</h1>' ) ;
var bodyText = $(xmlDoc).find('body').text() ;
$( '#response' ).append( '<p>' + bodyText + '</p>' ) ;
}
$(document).ready(function()
{
jQuery.ajax({
type: "GET",
url: "a.xml", // ! watch out for same
// origin type problems
dataType: "xml", // 'xml' passes it through the browser's xml parser
success: function( xmlDoc, status )
{
// The SUCCESS EVENT means that the xml document
// came down from the server AND got parsed successfully
// using the browser's own xml parsing caps.
processXMLDoc( xmlDoc );
// IE gets very upset when
// the mime-type of the document that
// gets passed down isn't text/xml.
// If you are missing the text/xml header
// apparently the xml parse fails,
// and in IE you don't get to execute this function AT ALL.
},
complete: function( xhr, status )
{
alert( "COMPLETE. You got:\n\n" + xhr.responseText ) ;
if( status == 'parsererror' )
{
alert( "There was a PARSERERROR. Luckily, we know how to fix that.\n\n" +
"The complete server response text was " + xhr.responseText ) ;
xmlDoc = null;
// Create the xml document from the responseText string.
// This uses the w3schools method.
// see also
if( window.DOMParser )
{
parser=new DOMParser();
xmlDoc=parser.parseFromString( xhr.responseText,"text/xml" ) ;
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject( "Microsoft.XMLDOM" ) ;
xmlDoc.async = "false" ;
xmlDoc.loadXML( xhr.responseText ) ;
}
$( '#response' ).append( '<p>complete event/xmlDoc: ' + xmlDoc + '</p>' ) ;
$( '#response' ).append( '<p>complete event/status: ' + status + '</p>' ) ;
processXMLDoc( xmlDoc ) ;
}
},
error: function( xhr, status, error )
{
alert( 'ERROR: ' + status ) ;
alert( xhr.responseText ) ;
}
});
});
</script>
</head>
<body>
<div>
<h1><a href="http://think2loud.com/reading-xml-with-jquery/">Reading XML with jQuery</a></h1>
<p>
<a href="http://docs.jquery.com/Ajax/jQuery.ajax#options">#1 jQuery.ajax ref</a>
</p>
</div>
<p>Server says:</p>
<pre id="response">
</pre>
</body>
</html>
```
## contents of a.xml
```
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
```
It extends [this example](http://marcgrabanski.com/article/jquery-makes-parsing-xml-easy). | jQuery .find() doesn't return data in IE but does in Firefox and Chrome | [
"",
"javascript",
"jquery",
"xml",
""
] |
I want to have a diagnostic log that is produced by several tasks managing data. These tasks may be in multiple threads. Each task needs to write an element (possibly with subelements) to the log; get in and get out quickly. If this were a single-task situation I'd use [XMLStreamWriter](http://java.sun.com/webservices/docs/1.5/api/javax/xml/stream/XMLStreamWriter.html) as it seems like the best match for simplicity/functionality without having to hold a ballooning XML document in memory.
But it's not a single-task situation, and I'm not sure how to best make sure this is "threadsafe", where "threadsafe" in this application means that each log element should be written to the log correctly and serially (one after the other and not interleaved in any way).
Any suggestions? I have a vague intuition that the way to go is to use a queue of log elements (with each one able to be produced quickly: my application is busy doing real work that's performance-sensitive), and have a separate thread which handles the log elements and sends them to a file so the logging doesn't interrupt the producers.
The logging doesn't necessarily have to be XML, but I do want it to be structured and machine-readable.
edit: I put "threadsafe" in quotes. Log4j seems to be the obvious choice (new to me but old to the community), why reinvent the wheel... | Use a logging framework, such as [Log4j](http://logging.apache.org/log4j/). | I think you are on the wrong path. You say “threadsafe” but you actually mean “serialized”. Threadsafe means that one thread will not interfere with data from other thread. Most of the time, threading issues are resolved beforehand and you should not worry about it just for logging sake. For example, if your write:
```
myVariableSum = 0 + myVariable;
//here comes other thread - Not very likely!
logger.info("Log some INFO; myVariable has value" + myVariable.toString());
```
You have to make sure that myVariable has not been changed by some other thread from the moment calculation (first line) was performed but before logging method was called. If this happens, you will log dirty value that was not used to perform the operation but value that was assigned by some other thread. This is generally taken care of; for example local (method level) variable can not be changed by other thread. Anyway, if you have to worry about this when logging, than 99% that your program has serious threading issues already.
All major logging frameworks are by themselves “threadsafe” meaning they can be deployed in multithreaded environments and will not display problems similar to one described above internally.
Getting traces to appear in log in order they happen is actually usually called “serialization” of calls. Serializing log writes will be a major performance bottleneck on any multithreaded app. If you use logging framework, like log4j, traces from all threads will appear in single place more or less in order they happen. However, one column is generally Thread name, so you can easily filter your log data by thread; each thread will log its data in chronological order. Check out this link:
<http://logging.apache.org/log4j/1.2/faq.html#1.7>
Finally, if serializing log writes is what you really need, then you could use some kind of structure, like java.util.concurrent.BlockingQueue to route your messages. | Best practices for Java logging from multiple threads? | [
"",
"java",
"multithreading",
"logging",
""
] |
I've been upgrading our solutions from VS 2005 to VS 2008; still targeting the .net 2.0 framework. The conversion wizard is simple and I've never had a conversion failure. The only beef that I've had so far is that I can't immediately compile after the upgrade because VS has changed some of my namespaces causing naming collisions.
For example, I have a DAL project (lets call it MyNameSpace) that has a "Clients" folder with a dataset named "dsClient".
Here is what the dataset designer class looks like before conversion:
```
namespace MyNameSpace
{
public partial class dsClient : global::System.Data.DataSet
{
}
}
```
During the conversion process, VS is changing my designer class and adding the folder name to the end of the namespace so now it looks like this:
```
namespace MyNameSpace.Clients
{
public partial class dsClient : global::System.Data.DataSet
{
}
}
```
The problem with this is that I have another class file in that folder with the same name:
```
namespace MyNameSpace
{
public class Clients
{
}
}
```
This causes a naming collision and I have to manually go fix the changes that VS made. In some cases, VS changes the namespace name to the name of the dataset rather than the name of the folder.
Is this a config thing in the conversion wizard? I'd like to have the wizard just update the project files and leave the code alone. | You can fix this by providing the namespace the code should be generated in:
Open the properties of the xsd file and put the namespace for the code next to "Custom Tool Namespace". Then click right on your xsd file and select "Run Custom Tool" and you're done. | I believe that the namespace comes from the location of the xsd file. I think all the way back to 2003 the folder you put the xsd into made it into the namespace.
In your case, if you move the xsd to the root of the DAL project, your code should be corrected. I realize this might not be ideal, but I think that's how the DataSet generator works.
The only thing that surprises me is that the namespace didn't include the "Clients" portion in your 2005 solution. It feels like it was generated in the root, but then moved to the subfolder without regenerating. | VS 2008 upgrade is changing my dataset designer namespaces | [
"",
"c#",
"visual-studio-2008",
"visual-studio-2005",
""
] |
I have a java application that uses some third party API. The third party jar files change fairly frequently because of all kinds of patches, but the API itself does not change that often.
Do I have to recompile my application every time the third party jar changes? | If the API changes, you should recompile even if you don't need to make any changes in your source code. If the API hasn't changed, you don't need to recompile.
The reason for the "even if you don't need to make any changes" is that some source-compatible changes may not be binary compatible. For instance, suppose you are currently calling:
```
public void foo(String x)
```
and in a later version this is changed to:
```
public void foo(Object x)
```
Obviously your code will still compile, but the method it resolves the call to will change.
This is a bit of an edge case, of course. Basically, so long as you know when the API changes, you should be okay. | Another case where a recompilation is theoretically necessary is constants. The value of a constant is literally compiled into the bytecode of classes that use it. If the value is changed in a new version of the API, anything compiled against the old version will continue using the old value, which may lead to different behaviour and very difficult to diagnose bugs.
Of course, no API designer with an ounce of brain will change the values of public constants if he can avoid it, but there may be cases where it is necessary. | Do I have to recompile my application when I upgrade a third party jar? | [
"",
"java",
""
] |
I am trying to see if a URL exists or not, and if it does not exist reset the variable containing the URL to an error page/image. However my attempt below sets every instance of PIC\_URL to noimage.gif, regardless of if it exists and is accessible or not. What am I missing?
```
if (@fopen($_REQUEST[$PIC_URL],"r"))
{
$status = "1";
}
else if (!(@fopen($_REQUEST[$PIC_URL],"r"))
{
$status = "2";
}
if ( $status == "2" ) $PIC_URL = "http://www.tricityhomes.com/assets/images/noimage.gif";
``` | The test on the else part looks redundant, and did you mean `$_REQUEST['PIC_URL']`?
```
if (@fopen($_REQUEST['PIC_URL'],"r"))
{
$status = "1";
}
else
{
$status = "2";
}
```
There's plenty more wrong with it though. To test if a remote file exists, you'd be better off using file\_exists, or even rolling your own method to perform a HEAD request. | You might want to try doing something similar to this
```
<?php
function url_exists($url) {
// Version 4.x supported
$handle = curl_init($url);
if (false === $handle)
{
return false;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = curl_exec($handle);
curl_close($handle);
return $connectable;
}
?>
```
Source: <http://uk.php.net/manual/en/function.file-exists.php#85246>
the reason being is that as has been mentioned checking against the raw value of fopen is not the best idea and also that method does not take account of being redirected to error pages etc. | Image URL error catching problem | [
"",
"php",
"http",
""
] |
I have interface in service layer with several methods starting with Get and FxCop's **Use properties where appropriate** rule complains that I should consider using properties instead.
I tried to use SuppressMessageAttribute but when it's defined on interface it has no effect on member methods. Do I need to put SuppressMessageAttribute to every method or is there a way to suppress **CA1024** for a whole type?
```
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate"]
public interface IProjectService
{
// Information and statistics about projects
IList<ProjectInfo> GetProjects();
ProjectsDashboard GetProjectsDashboard();
// Project's settings
ProjectSettings GetProjectSettings(Guid id);
void SaveProjectSettings(ProjectSettings settings);
}
``` | You will have to add the attribute for each method. | I understand the need to use methods here. While it is true that these methods probably don't change the state, using a method hints at a lengthy/outward operation, which is probably the case through Service Class methods.
Can't you rename your methods to LoadProjectSettings ?
Otherwise you will indeed have to add the attribute to each method, or disable the rule. | FxCop - Use properties where appropriate | [
"",
"c#",
"code-analysis",
"fxcop",
""
] |
I currently rely on anchor tags to perform AJAX requests on my web application (using jQuery). For example:
```
<script type="text/javascript">
$(document).ready(function() {
$("#test").click(function() {
// Perform AJAX call and manipulate the DOM
});
});
<a id="test" href="">Click me!</a>
</script>
```
However, these anchor tags pretty much become useless if the user disables javascript in their browser. What's the best way to handle graceful degradation of these anchor tags? Is my only option to switch them all to buttons inside form tags?
Edit: I should be more clear and specify that my AJAX call is an HTTP POST to a URL that I cannot, for security reasons, expose to normal HTTP GETs (e.g. think of a delete url "/items/delete/1"). With that in mind, I can't change the href of the anchor to be "/items/delete/1" in order to satisfy users with javascript turned off since it poses a security risk. | The answer I was looking for is buried in one of the comments:
> your use of the `<a>` tag to do an HTTP
> POST operation is conflicting. `<a>` was
> designed for HTTP GET. You won't find
> a satisfactory answer here if you keep
> the semantics of your operation
> embedded in an `<a>` tag. See
> <http://www.w3.org/2001/tag/doc/whenToUseGet.html> | One option (for which I'm sure I'll get downvoted), is to not bother with people who have javascript off. Display a message in a `<noscript>` tag informing the user that your site requires Javascript.
It'll affect two groups of people: those who have knowingly disabled javascript and presumably know how to turn it back on, and those who are viewing your site on an older mobile device.
Consider how important these groups of people are before you go on spending hours and hours developing for them. | Graceful degradation of anchor tags with javascript | [
"",
"javascript",
"jquery",
"html",
"graceful-degradation",
""
] |
I have a List`<string`> of variable count, and I want to query (via LINQ) a table to find any items that contain any of those strings in the Text column.
Tried this (doesn't work):
```
items = from dbt in database.Items
where (stringList.FindAll(s => dbt.Text.Contains(s)).Count > 0)
select dbt;
```
Query would be something like:
```
select * from items where text like '%string1%' or text like '%string2%'
```
Is this possible? | Check this article out to do what you want:
<http://www.albahari.com/nutshell/predicatebuilder.aspx>
This works like a dream. I essentially cut and pasted their code and got this back (with my own data-scheme of course):
```
SELECT [t0].[Id], [t0].[DateCreated], [t0].[Name] ...
FROM [dbo].[Companies] AS [t0]
WHERE ([t0].[Name] LIKE @p0) OR ([t0].[Name] LIKE @p1)
```
Here is the code I ran for the proof of concept:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace PredicateTest
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dataContext = new DataClasses1DataContext();
Program p = new Program();
Program.SearchCompanies("test", "test2");
var pr = from pi in dataContext.Companies.Where(Program.SearchCompanies("test", "test2")) select pi;
}
DataClasses1DataContext dataContext = new DataClasses1DataContext();
public static Expression<Func<Company, bool>> SearchCompanies(
params string[] keywords)
{
var predicate = PredicateBuilder.False<Company>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(p => p.Name.Contains(temp));
}
return predicate;
}
}
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}
```
I'd suggest going to the site for the code and explanation.
(I am leaving the first answer because it works well if you need an IN statement) | kind of new to the whole LINQ to SQL game, but does this syntax help?
```
string[] items = new string[] { "a", "b", "c", "d" };
var items = from i in db.Items
where items.Contains(p.text)
select i;
```
Got it from:
<http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/> | LINQ to SQL - select where text like string array | [
"",
"sql",
"linq",
"linq-to-sql",
"sql-like",
""
] |
Okay, so I have two classes, call them A and B--in that order in the code. Class B instantiates class A as an array, and class B also has an error message char\* variable, which class A must set in the event of an error. I created a third class with a pure virtual function to set the errorMessage variable in B, then made B a child of that third class. Class A creates a pointer to the third class, call it C--when B initializes the array of A objects, it loops through them and invokes a function in A to set A's pointer to C-- it passes "this" to that function, and then A sets the pointer to C to "this," and since C is B's parent, A can set C->errorMessage (I had to do all this because A and B couldn't simultaneously be aware of each other at compile time).
Anyways it works fine, however, and when I pass command line parameters to main(int,char\*\*), it works unless I pass seven, eight, or more than twelve parameters to it... I narrowed it down (through commenting out lines) to the line of code, in A, which sets the pointer to C, to the value passed to it by B. This made no sense to me... I suspected a memory leak or something, but it seems wrong and I have no idea how to fix it... Also I don't get why specifically seven, eight, and more than twelve arguments don't work, 1-6 and 9-12 work fine.
Here is my code (stripped down)--
```
//class C
class errorContainer{
public:
virtual ~errorContainer(){ }
virtual void reportError(int,char*)=0;
};
//Class A
class switchObject{
void reportError(int,char*);
errorContainer* errorReference;
public:
void bindErrorContainer(errorContainer*);
};
//Class A member function definitions
void switchObject::reportError(int errorCode,char* errorMessage){
errorReference->reportError(errorCode,errorMessage);
}
void switchObject::bindErrorContainer(errorContainer* newReference){
errorReference=newReference; //commenting out this line fixes the problem
}
//Class B
class switchSystem: public errorContainer{
int errorCode;
char* errorMessage;
public:
switchSystem(int); //MUST specify number of switches in this system.
void reportError(int,char*);
int errCode();
char* errMessage();
switchObject* switchList;
};
//Class B member function definitions
switchSystem::switchSystem(int swLimit){
int i;
switchList=new (nothrow) switchObject[swLimit];
for(i=0;i<swLimit;i++){
switchList[i].bindErrorContainer(this);
}
errorCode=0;
errorMessage="No errors.";
}
void switchSystem::reportError(int reportErrorCode,char* reportErrorMessage){
int len=0,i;
errorCode=reportErrorCode;
if(errorMessage){
delete[] errorMessage;
}
while(reportErrorMessage[len]!='\0'){
len++;
}
errorMessage=new char[len];
for(i=0;i<=len;i++){
errorMessage[i]=reportErrorMessage[i];
}
}
int switchSystem::errCode(){
return errorCode;
}
char* switchSystem::errMessage(){
return errorMessage;
}
```
Anyone know what I've done wrong here?
It's bugging the crap out of me... I can't seem to fix it.
---EDIT---
okay, I have it set up the way I do so that I can use it like this in main()
```
int main(int argc,char** argv){
switchSystem sw (2)
sw.switchList[0].argumentCount=2;
sw.switchList[1].argumentCount=0;
sw.switchList[0].identifier="a";
sw.switchList[1].identifier="switch";
sw.init(argc,argv);
if(sw.errCode()>0){
cout<< "Error "<< sw.errCode()<< ": "<< sw.errMessage()<< endl;
}
}
```
this program is supposed to read the command line arguments and handle user defined "switches"--like how most command line programs handle switches, but instead of testing for all of them at the beginning of main I wanted to try to write a class and some functions to do it for me--create a switchSystem object with the number of switches, set their identifiers, whether or not they take arguments, and then pass the command line arguments to "init()" to sort it out. Then test like,
```
if(sw.isSet("switch")){ ... }
```
etc. | * `reportError()` should be declared virtual in `switchSystem`, as it is in `errorContainer`.
* `char*` should instead be `std::string` to avoid all of that needless work.
* Is there some reason that you can't use an `std::vector<switchObject>` instead of `new[]`?
* You shouldn't `delete[] errorMessage` when it points to a static literal string. This leads to undefined behavior. (Translation: Bad Thing(TM).)
* Why are you iteratively counting and copying the contents of a `char*`? This is begging for trouble. You're not doing anything to protect yourself from harm.
* Why must `switchObject` pass a string to `switchSystem`? Wouldn't it be better to simply return an error code or `throw` some class derived from `std::exception`? Or perhaps it should send a string to a global logging facility?
I think perhaps you should rethink your design instead of trying to fix this. | It seems scary that you:
* Mix dynamic memory with static string constants ("No errors.") in the same pointer.
* Use an explicit `while`-loop to compute the string's length; have you not heard of `strlen()`?
* Use such low-level C-like string processing, for no good reason ... What's wrong with `std::string`?
* Don't properly account for the terminating '\0' in the string, when allocating space for it and copying it. The length is also not stored, leaving the resulting `char` array rather difficult to interpret. | Possible memory leak? | [
"",
"c++",
"inheritance",
"pointers",
"memory-leaks",
"class",
""
] |
How should I write error reporting modules in PHP?
Say, I want to write a function in PHP: 'bool isDuplicateEmail($email)'.
In that function, I want to check if the $email is already present in the database.
It will return 'true', if exists. Else 'false'.
Now, the query execution can also fail, In that time I want to report 'Internal Error' to the user.
The function should not die with typical mysql error: die(mysql\_error(). My web app has two interfaces: browser and email(You can perform certain actions by sending an email).
In both cases it should report error in good aesthetic.
Do I really have to use exception handling for this?
Can anyone point me to some good PHP project where I can learn how to design robust PHP web-app? | In my PHP projects, I have tried several different tacts. I've come to the following solution which seems to work well for me:
First, any major PHP application I write has some sort of central singleton that manages application-level data and behaviors. The "Application" object. I mention that here because I use this object to collect generated feedback from every other module. The rendering module can query the application object for the feedback it deems should be displayed to the user.
On a lower-level, every class is derived from some base class that contains error management methods. For example an "AddError(code,string,global)" and "GetErrors()" and "ClearErrors". The "AddError" method does two things: stores a local copy of that error in an instance-specific array for that object and (optionally) notifies the application object of this error ("global" is a boolean) which then stores that error for future use in rendering.
So now here's how it works in practice:
Note that 'Object' defines the following methods: *AddError* *ClearErrors* *GetErrorCodes* *GetErrorsAsStrings* *GetErrorCount* and maybe *HasError* for convenience
```
// $GLOBALS['app'] = new Application();
class MyObject extends Object
{
/**
* @return bool Returns false if failed
*/
public function DoThing()
{
$this->ClearErrors();
if ([something succeeded])
{
return true;
}
else
{
$this->AddError(ERR_OP_FAILED,"Thing could not be done");
return false;
}
}
}
$ob = new MyObject();
if ($ob->DoThing())
{
echo 'Success.';
}
else
{
// Right now, i may not really care *why* it didn't work (the user
// may want to know about the problem, though (see below).
$ob->TrySomethingElse();
}
// ...LATER ON IN THE RENDERING MODULE
echo implode('<br/>',$GLOBALS['app']->GetErrorsAsStrings());
```
The reason I like this is because:
1. I hate exceptions because I personally believe they make code more convoluted that it needs to be
2. Sometimes you just need to know that a function succeeded or failed and not exactly what went wrong
3. A lot of times you don't need a specific error code but you need a specific error string and you don't want to create an error code for every single possible error condition. Sometimes you really just want to use an "opfailed" code but go into some detail for the user's sake in the string itself. This allows for that flexibility
4. Having two error collection locations (the local level for use by the calling algorithm and global level for use by rendering modules for telling the user about them) has really worked for me to give each functional area exactly what it needs to get things done. | Using MVC, i always use some sort of default error/exception handler, where actions with exceptions (and no own error-/exceptionhandling) will be caught.
There you could decide to answer via email or browser-response, and it will always have the same look :) | How to design error reporting in PHP | [
"",
"php",
"error-handling",
""
] |
I need to do something like this but SQL Server 2008 doesn't like it. My query is actually more complex than this and I realize this isn't the best way to accomplish what I'm doing but my focus is on the functionality of the WITH statement and not the select and where statements.
> WITH stuff1 AS (
> select name, startdate, id from employees where startdate > 0 )
>
> WITH stuff2 AS (
> select name, startdate, id from stuff1 )
>
> select \* from stuff2 where id > 10 | I do it all the time:
```
WITH stuff1 AS (
SELECT name
,startdate
,id
FROM employees
WHERE startdate > 0
)
,stuff2 AS (
SELECT name
,startdate
,id
FROM stuff1
)
SELECT *
FROM stuff2
WHERE id > 10
```
As far as I can tell, I haven't reached a limit in CTEs.
The only thing you can't do (which would be pretty useful) is reuse CTEs in separate `SELECT`s:
```
WITH stuff1 AS (
SELECT name
,startdate
,id
FROM employees
WHERE startdate > 0
)
,stuff2 AS (
SELECT name
,startdate
,id
FROM stuff1
)
SELECT *
FROM stuff2
WHERE id > 10
;
SELECT *
FROM stuff2
WHERE id < 10
```
Say. Instead you have to copy and paste the entire CTE chain again. | You may be able to us a series of sub-queries.
Or sub-queries nested in a CTE.
An example of sub-queries using Northwind:
```
SELECT * FROM
(SELECT * FROM
(SELECT * FROM dbo.Employees WHERE Country = 'USA') as TableFiltered1
) AS TableFilterd2 WHERE City = 'Seattle'
```
You can use two CTEs, but maybe not the way you wanted to, see:
<https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml> | Can I use WITH in TSQL twice to filter a result set like my example? | [
"",
"sql",
"sql-server",
"common-table-expression",
""
] |
I plan to introduce a set of standards for writing unit tests into my team. But what to include?
These two posts ([Unit test naming best practices](https://stackoverflow.com/questions/155436/unit-test-naming-best-practices) and [Best practices for file system dependencies in unit/integration tests](https://stackoverflow.com/questions/377423/best-practices-for-file-system-dependencies-in-unit-integration-tests)) have given me some food for thought already.
Other domains that should be covered in my standards should be how test classes are set up and how to organize them. For example if you have class called OrderLineProcessor there should be a test class called OrderLineProcessorTest. If there's a method called Process() on that class then there should be a test called ProcessTest (maybe more to test different states).
Any other things to include?
Does your company have standards for unit testing?
EDIT: I'm using Visual Studio Team System 2008 and I develop in C#.Net | Have a look at [Michael Feathers on what is a unit test](http://www.artima.com/weblogs/viewpost.jsp?thread=126923) (or what makes unit tests bad unit tests)
Have a look at the idea of "Arrange, Act, Assert", i.e. the idea that a test does only three things, in a fixed order:
* **Arrange** any input data and processing classes needed for the test
* Perform the **action** under test
* Test the results with one or more **asserts**. Yes, it can be more than one assert, so long as they all work to test the action that was performed.
Have a Look at [Behaviour Driven Development](http://en.wikipedia.org/wiki/Behavior_Driven_Development) for a way to align test cases with requirements.
Also, my opinion of standard documents today is that you shouldn't write them unless you have to - there are lots of resources available already written. Link to them rather than rehashing their content. Provide a reading list for developers who want to know more. | You should probably take a look at the "Pragmatic Unit Testing" series. [This](https://rads.stackoverflow.com/amzn/click/com/0977616673) is the C# version but there is another for Java.
With respect to your spec, I would *not* go overboard. You have a very good start there - the naming conventions are very important. We also require that the directory structure match the original project. Coverage also needs to extend to boundary cases and illegal values (checking for exceptions). This is obvious but your spec is the place to write it down for that argument that you'll inevitably have in the future with the guy who doesn't want to test for someone passing an illegal value. But don't make the spec more than a few pages or no one will use it for a task that is so context-dependent.
Update: I disagree with Mr. Potato Head about only one assert per Unit Test. It sounds quite fine in theory but, in practice, it leads to either loads of mostly redundant tests or people doing tons of work in setup and tear-down that *itself* should be tested. | Writing standards for unit testing | [
"",
"c#",
"visual-studio-2008",
"unit-testing",
"coding-style",
""
] |
I've occasionally heard that with generics, Java didn't get it right. (nearest reference, [here](https://stackoverflow.com/questions/457822/what-are-the-things-java-got-right))
Pardon my inexperience, but what would have made them better? | Bad:
* Type information is lost at compile time, so at execution time you can't tell what type it's "meant" to be
* Can't be used for value types (this is a biggie - in .NET a `List<byte>` really is backed by a `byte[]` for example, and no boxing is required)
* Syntax for calling generic methods sucks (IMO)
* Syntax for constraints can get confusing
* Wildcarding is generally confusing
* Various restrictions due to the above - casting etc
Good:
* Wildcarding allows covariance/contravariance to be specified at calling side, which is very neat in many situations
* It's better than nothing! | The biggest problem is that Java generics are a compile-time only thing, and you can subvert it at run-time. C# is praised because it does more run-time checking. There is some really good discussion in [this post](https://stackoverflow.com/questions/355060/c-vs-java-generics), and it links to other discussions. | Why do some claim that Java's implementation of generics is bad? | [
"",
"java",
"generics",
""
] |
I want to make my WPF application open the default browser and go to a certain web page. How do I do that? | For desktop versions of .NET:
```
System.Diagnostics.Process.Start("http://www.webpage.com");
```
For .NET Core, the default for [`ProcessStartInfo.UseShellExecute`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.useshellexecute) has changed from `true` to `false`, and so you have to explicitly set it to `true` for this to work:
```
System.Diagnostics.Process.Start(new ProcessStartInfo
{
FileName = "http://www.webpage.com",
UseShellExecute = true
});
```
To further complicate matters, this property *cannot* be set to `true` for UWP apps (so none of these solutions are usable for UWP). | Accepted answer no longer works on **.NET Core 3**. To make it work, use the following method:
```
var psi = new ProcessStartInfo
{
FileName = url,
UseShellExecute = true
};
Process.Start (psi);
``` | How to open a web page from my application? | [
"",
"c#",
".net",
"wpf",
""
] |
I can proxy a single function in javascript by doing something like this (just jotted down from memory so bear with me)
```
function addAroundAdvice(target){
var targetFunction = target.aFunction;
target.aFunction = new function(){
invokePreCall();
targetFunction.apply(target, arguments);
invokePostCall();
}
}
```
Being a java programmer I'd think of this as a dynamic proxy. Every time I write code like this I think that *someone* must have made a really smart library that does the common proxying operations that is at least 10% better than what I can do in a hurry. I'd be expecting some stuff like correctly intercepting all methods for any given object, which may not be entirely trivial. Then there's different types of advice. So while I'm not expecting something the size of scriptaculous, it's certainly more than 6 lines of code.
So where are these libraries ? | Try [jQuery AOP plugin](http://code.google.com/p/jquery-aop/)
Looking at the [source](http://code.google.com/p/jquery-aop/source/browse/trunk/src/aop.js) it seems that only uses jQuery as a namespace, so you could try this *plugin* even if don't want to use jQuery. | The Dojo Toolkit has a lot of support for AOP constructs like this:
[Eugene Lazutkin's Blog Post on Aspect Oriented Programming with Dojo](http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/) | Dynamic proxies in javascript? | [
"",
"javascript",
""
] |
As by design an enum constant in java is a singleton, and for sake of concurrent usage I normally create stateless enum instances and use method parameters to inject the data as needed.
Example:
Currently I am creating a REST service which has Operations (implemented as an enum using a variant of the strategy pattern).
```
public enum Operation {
DO_THIS() {
public Result doSomething(Object theData) {
}
} ,
// Other Operations go here
;
public abstract Result doSomething(Object theData);
}
```
Now I want to collect data about how often an operation has been called and how often it succeeded and the like.
I could save the state externally when using the enum instance but it rather seems that the state should be saved in the Operation as the operation should contain it's own state.
Now my general question is:
**Is a stateful enum instance (besides from concurrency issues) a bad design?** | I think it violates the Principle of Least Astonishment.
People expect the common usage of enums as they were originally designed - as constants or tokens, and not as general purpose classes with state. | Yes. And by 'yes' I mean 'Always'.
If you want to collate stats on the number of operations called, implement some observability. | Should enum objects be stateless? | [
"",
"java",
"oop",
"enums",
""
] |
Though `java.util.properties` allows reading and writing properties file, the writing does not preserve the formatting. Not surprising, because it is not tied to the property file.
Is there a `PropertyFile` class out there -- or some such -- that preserves comments and blank lines and updates property values in place? | It doesn't get much better than Apache's Commons [Configuration](http://commons.apache.org/configuration/index.html) API. This provides a unified approach to configuration from Property files, XML, JNDI, JDBC datasources, etc.
It's handling of property files is very good. It allows you to generate a [PropertiesConfigurationLayout](http://commons.apache.org/configuration/apidocs/index.html) object from your property which preserves as much information about your property file as possible (whitespaces, comments etc). When you save changes to the property file, these will be preserved as best as possible.
---
Sample code:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.PropertiesConfigurationLayout;
public class PropertiesReader {
public static void main(String args[]) throws ConfigurationException, FileNotFoundException {
File file = new File(args[0] + ".properties");
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(file)));
config.setProperty("test", "testValue");
layout.save(new FileWriter("path\\to\\properties\\file.properties", false));
}
}
```
See also:
* <http://mvnrepository.com/artifact/commons-configuration/commons-configuration/>
* <https://commons.apache.org/proper/commons-configuration/apidocs/org/apache/commons/configuration2/PropertiesConfigurationLayout.html> | The sample code for using the Apache Commons Configuration library contributed by Patrick Boos is unnecessarily complicated. You don't need to use PropertiesConfigurationLayout explicitly unless you require some advanced control over the output. PropertiesConfiguration by itself is sufficient to preserve comments and formatting:
```
PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
config.setProperty("Foo", "Bar");
config.save();
```
(Note: This code works for the existing 1.10 stable version. I have not checked if it works on the 2.0 alpha builds currently available.) | A better class to update property files? | [
"",
"java",
"properties",
""
] |
I want to write a c array into a container and i prefer to modify it if possible.
I was thinking of using vector but it does seem to have a write(\*pchararray, len); function. String looked like the next best thing but that too doesnt have a write function? | Given
```
char myarray[10];
```
You can use an **STL `iterator`**:
```
vector <char> v;
copy(myarray, myarray + 10, back_inserter(v));
```
You can use a **constructor**:
```
vector <char> v(myarray, myarray + 10);
```
You can **resize and copy**:
```
vector<char> v(10);
copy(myarray, myarray + 10, v.begin());
```
(and all these work similarly for string)
Thanks to comments/other answers :) | Vector, string, and many other containers have a "two iterator" constructor for this purpose:
```
char raw_data[100];
std::vector<char> v(raw_data, raw_data + 100);
std::string s(raw_data, raw_data + 100);
``` | What container can I use to write binary? | [
"",
"c++",
"containers",
""
] |
I'm writing a tweak utility that modifies some keys under `HKEY_CLASSES_ROOT`.
All works fine under Windows XP and so on. But I'm getting error `Requested registry access is not allowed` under Windows 7. Vista and 2008 I guess too.
How should I modify my code to add UAC support? | `app.manifest` should be like this:
```
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
``` | You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-) | Requested registry access is not allowed | [
"",
"c#",
".net",
"security",
"uac",
"registry",
""
] |
I'm building a small program that acts as an XMPP client and I am using the [Smack](http://www.igniterealtime.org/projects/smack/index.jsp) library. Now, the server I am connecting to requires SSL (in Pidgin I have to check "Force old (port 5223) SSL"). I'm having trouble getting Smack to connect to this server. Is it possible? | Take a look at this thread.
<http://www.igniterealtime.org/community/thread/37678>
Essentially, you need to add these two lines to your code:
```
connConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
connConfig.setSocketFactory(new DummySSLSocketFactory());
```
where connConfig is your ConnectionConfiguration object. Get the DummySSLSocketFactory from the Spark source code repository. All it does is accept virtually any certificate. This seemed to work for me. Good luck! | You can achieve this by the following:
**Storing the CA Certificate in Keystore**
To store the certificate in a Keystore follow these steps.
**Step 1:** Download the bouncycastle JAR file. It can be downloaded from the here: Bouncy Castle JAVA Releases
**Step 2:** Use the following command to store the certificate in keystore
> ```
> keytool -importcert -v -trustcacerts -file "<certificate_file_with_path>" -alias "<some_name_for_certificate>" -keystore "<file_name_for_the_output_keystore>" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "<bouncy_castle_jar_file_with_path>" -storetype BKS -storepass "<password_for_the_keystore>"
> ```
**Step 3:** Verify the keystore file
> ```
> keytool -importcert -v -list -keystore "<file_name_for_the_keystore_with_path>" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "<bouncy_castle_jar_file_with_path>" -storetype BKS -storepass "<password_for_the_keystore>"
> ```
This shall list us the certificate included in the keystore.
We have a keystore which we can use in our code.
**Using the keystore**
After generating this keystore, save it in the raw folder of your application. The use the below code to get the certificate handshake with the openfire server.
To create a connection with openfire using XMPP, you may need to get the config. For the same, use the below method:
> ```
> public ConnectionConfiguration getConfigForXMPPCon(Context context) {
> ConnectionConfiguration config = new ConnectionConfiguration(URLConstants.XMPP_HOST, URLConstants.XMPP_PORT);
> config.setSASLAuthenticationEnabled(false);
> config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
> config.setCompressionEnabled(false);
> SSLContext sslContext = null;
> try {
> sslContext = createSSLContext(context);
> } catch (KeyStoreException e) {
> e.printStackTrace();
> } catch (NoSuchAlgorithmException e) {
> e.printStackTrace();
> } catch (KeyManagementException e) {
> e.printStackTrace();
> } catch (IOException e) {
> e.printStackTrace();
> } catch (CertificateException e) {
> e.printStackTrace();
> }
>
> config.setCustomSSLContext(sslContext);
> config.setSocketFactory(sslContext.getSocketFactory());
>
> return config;
> }
>
> private SSLContext createSSLContext(Context context) throws KeyStoreException,
> NoSuchAlgorithmException, KeyManagementException, IOException, CertificateException {
> KeyStore trustStore;
> InputStream in = null;
> trustStore = KeyStore.getInstance("BKS");
>
> if (StringConstants.DEV_SERVER_IP.equals(URLConstants.XMPP_HOST) || StringConstants.TEST_SERVER_IP.equals(URLConstants.XMPP_HOST))
> in = context.getResources().openRawResource(R.raw.ssl_keystore_dev_test);
> else if(StringConstants.STAGE_SERVER_IP.equals(URLConstants.XMPP_HOST) || StringConstants.STAGE2_SERVER_IP.equals(URLConstants.XMPP_HOST))
> in = context.getResources().openRawResource(R.raw.ssl_keystore_stage);
> else if(StringConstants.PROD_SERVER_IP.equals(URLConstants.XMPP_HOST) || StringConstants.PROD1_SERVER_IP.equals(URLConstants.XMPP_HOST))
> in = context.getResources().openRawResource(R.raw.ssl_keystore_prod);
>
> trustStore.load(in, "<keystore_password>".toCharArray());
>
> TrustManagerFactory trustManagerFactory = TrustManagerFactory
> .getInstance(KeyManagerFactory.getDefaultAlgorithm());
> trustManagerFactory.init(trustStore);
> SSLContext sslContext = SSLContext.getInstance("TLS");
> sslContext.init(null, trustManagerFactory.getTrustManagers(),
> new SecureRandom());
> return sslContext;
> }
> ```
All done..!! Just connect.. Now your connection is secured.
All follow the same in my blog at [smackssl.blogspot.in](http://smackssl.blogspot.in/2015/10/ssl-implementation-in-android-for-smack.html) | How to create an SSL connection using the Smack XMPP library? | [
"",
"java",
"ssl",
"xmpp",
""
] |
I have 4 '.cpp' files and 1 header files:
```
Tools.cpp
Code1.cpp
Code2.cpp
Code3.cpp
and Tools.hh
```
Now all `Code1.cpp, Code2.cpp, Code3.cpp`
use functions stored in `Tools.cpp`.
Currently, what I do to compile all of them is using
this simple shell script:
```
#!/bin/bash
echo "compiling Code1.cpp";
g++ Code1.cpp Tools.cpp -o Code1
echo "compiling Code2.cpp";
g++ Code2.cpp Tools.cpp -o Code2
echo "compiling Code3.cpp";
g++ Code3.cpp Tools.cpp -o Code3
```
It all works fine.
Now I want to do that using a standard makefile.
But why this doesnt' work:
```
CXX = g++
TOOLSRC = Tools.cpp Code1.cpp Code2.cpp \
Code3.cpp
TOOLSINC = Tools.hh
all: Code1 Code2 Code3
Code1: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
Code2: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
Code3: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
```
The error I got is this:
```
ld: warning in makefile, file is not of required architecture
ld: duplicate symbol neighbors(std::vector<int, std::allocator<int> >&, int, int)in /var/folders/Yx/YxKmmyVPGpakdPL4St7X6++++TI/-Tmp-//ccQCrGHe.o and /var/folders/Yx/YxKmmyVPGpakdPL4St7X6++++TI/-Tmp-//ccreq9YU.o
collect2: ld returned 1 exit status
make: *** [FindNeighbours] Error 1
```
How can I correct the mistakes? | In these targets:
```
Code1: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
```
The resulting command will be:
```
g++ Tools.cpp Code1.cpp Code2.cpp Code3.cpp Tools.hh makefile -o Code1
```
**This is clearly not what you want.** `g++` is attempting to compile both the header file and the makefile **and doesn't know what to do with the makefile**. You're also declaring dependencies on all three of your main units for each unit. So if Code3.cpp changes, Code1 will require recompilation. **This is also undesirable.**
Try something like this instead:
```
CXX = g++
all: Code1 Code2 Code3
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $^
Code1: Code1.o Tools.o
$(CXX) -o $@ $^
Code2: Code1.o Tools.o
$(CXX) -o $@ $^
Code3: Code1.o Tools.o
$(CXX) -o $@ $^
``` | In short, `$^` isn't what you want here. It evaluates to the "names of all the prerequisites, with spaces between them." In the problem Makefile, that causes all three targets to use almost identical command lines, that each look like
```
g++ Tools.cpp Code1.cpp Code2.cpp Code3.cpp Tools.hh makefile -o Code1
```
From the error message quoted, g++ has decided that makefile should be passed to the linker as if it were an object. It isn't. Without makefile on the line, you would still be compiling and linking all four of your source files, and quite likely leaving the linker to decide which of four `main()` functions to use.
You probably want to leverage the fact that make has a huge number of builtin rules for common cases. Compiling two source files and linking the result fits neatly into those common cases. Its untested, but the following should do all you want (assuming a recent build of gnu make, at least), and have the advantage of only compiling each object once.
```
all: Code1 Code2 Code3
Code1: Code1.o Tools.o
Code2: Code2.o Tools.o
Code3: Code3.o Tools.o
Code1.o Code2.o Code3.o Tools.o: Tools.hh
```
If you needed to set some compiler options you could add a definition for CXXFLAGS, traditionally near the top of the file. | Simple Makefile Problem (with a simple dependency) | [
"",
"c++",
"unix",
"makefile",
""
] |
INFO:
I have an Array of 100 nodes, [ 0 .. 99 ]. Each node can have an arbitrary number of linked nodes:
eg1, 0 links to 5, 10, 15, 20.
eg2, 1 links to 30, 40, 50.
eg3, etc..
All 100 nodes have at least one linked node, nodes do not know who links to them.
QUESTION:
How can I find the shortest link-path if provided with START and END.
eg. START=5, END=80, Link Path (example) : [5]->10->24->36->[80]?
I'm using Pascal and/or PHP, but understanding how is what I'm looking for [code helps too]. | Plenty of reading/algorithms:
[Shortest path problem](http://en.wikipedia.org/wiki/Shortest_path_problem). You effectively just have every edge ("link", as you called it) with an equal weight. | Do a Breadth First Traversal starting with the Start node and quit as soon as you find the end node. | Linear Array with nodes randomly linked to other nodes in array, shortest path | [
"",
"php",
"delphi",
"shortest-path",
""
] |
I have the following class declared:
```
public partial class MainWindow : Window
```
And I need to get the actual handle of the window once the window has one.
How can I do that and where should I put the query function.
What I tried so far was:
```
IntPtr hwnd = new WindowInteropHelper(this).Handle;
```
But the handle I get back is 0, which might be because it was planted in OnInitialized - maybe the window is not ready yet at that stage.
And, yes - it is connected via WPF, thank you for pointing it out!
Thanks | In the `OnInitialized` method the **handle** has not yet been created. But you are on the right track. If you put your call in the `Loaded` event the **handle** will have been created and it should return the correct **handle**. | The earliest place you can get the handle is OnSourceInitialized | Getting the handle of window in C# | [
"",
"c#",
"wpf",
"windows",
""
] |
Say I have the following 4 .net assemblies:
1. Winforms UI
2. Business Logic
3. SQL Server Data Access (implementing an IRepository)
4. Common Interfaces (definition of IRepository etc.)
My business logic (2) makes calls to the data access layer (3) through IRepository (defined in 4) using constructor dependency injection. However when I ceate a business object I need to pass in an actual repository. I do this by having a singleton class in my business logic layer return the currently in use concrete object implementing IRepository. I am coming to the conclusion that this is a bad thing, as my business logic layer now has to reference 3 as well as 4.
I think I need a IoC Container but the question is where I create/put it as it seems that wherever I create this (1 - UI)? will also need to hold a reference to 3 (SQL Server Data Access). Am I not just moving the problem rather than achieving actual decoupling?
Do I create the IoC Container in the UI. Or expose it through another new assembly.
(I'm using C#, .net 3.5 and AutoFac)
Thanks. | IoC container generally should be created in the **host project** (application entry point). For the Windows.Forms application that's the exe project.
Generally in simple solutions (under 10 projects), only a host project should have a reference to IoC library.
PS: [Structuring .NET Applications with Autofac IoC](http://abdullin.com/journal/2009/2/12/structuring-net-applications-with-autofac-ioc.html) | When registering components there are several possibilities:
1. Registration in code:
* directly
Problem: you have to reference everything ( you are here)
* indirectly
Problem : to find out what has to be registered
Solution:
1. use attributes
2. use marker interface as IService
3. use conventions (see StructureMap)
2. Registration with configuration file:
* let the container do everything
* read the file yourself | Not understanding where to create IoC Containers in system architecture | [
"",
"c#",
"architecture",
"ioc-container",
""
] |
It seems Suhosin patches and extends the PHP core as a means to protect users from flaws in the core. It also seems some smart people are using this system. Since it appears to be a good thing, I'm curious as to why its not part of the PHP core to begin with. Anybody know?
**Update:** Apparently some distributions of Linux also package PHP with Suhosin by default. This seems to be true for Debian (Lenny at least) and Arch Linux. Any other distributions package PHP with Suhosin by default? | One of the main guys behind Suhosin is Stefan Esser. Stefan seems to have had on ongoing disagreement with the PHP core developers with [regard to security](http://www.securityfocus.com/columnists/432) over the last few years. He was also one of the guys behind the [month of PHP bugs](http://www.php-security.org/) which was intended to draw attention to the (in Stefan's opinion) sad state of PHP core security.
Given that the Suhosin guys have decided to go their own way and work outside the PHP project, I can imagine that:
* It's possible that Suhosin hasn't been contributed back for inclusion.
* The Suhosin guys haven't been able to convince the PHP team of it's usefulness, or haven't tried.
* The core PHP team isn't open to contributions from the guys behind Suhosin.
Some Linux distributions such as Debian (Etch and Lenny), Ubuntu and Arch include the Suhosin patch in their PHP package, so on those systems you'll often find it's turned on by default. Red Hat derived distributions (Red Hat Enterprise, CentOS, Fedora, etc) don't include Suhosin in their PHP packages.
Note: I have no association with Core PHP devs, or Suhosin, but a reasonable guess based on some of the personalities involved. | I would guess the main reasons for the php team not to include Suhosin are:
* It may break existing (badly written) php code
* It may break (badly written) php extensions (I remember Zend Optimizer being problematic) | Why isn't Suhosin part of the PHP core? | [
"",
"php",
"security",
"suhosin",
""
] |
I have a file that contains some amount of plain text at the start followed by binary content at the end. The size of the binary content is determined by some one of the plain text lines I read.
I was using a `BufferedReader` to read the individual lines, however it exposes no methods to refer to read a byte array. The `readUTF` for a `DataInputStream` doesnt read all the way to the end of the line, and the `readLine` method is deprecated.
Using the underlying `FileInputStream` to read returns empty byte arrays. Any suggestions on how to go about this?
---
```
private DOTDataInfo parseFile(InputStream stream) throws IOException{
DOTDataInfo info = new DOTDataInfo();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
int binSize = 0;
String line;
while((line = reader.readLine()) != null){
if(line.length() == 0)
break;
DOTProperty prop = parseProperty(line);
info.getProperties().add(prop);
if(prop.getName().equals("ContentSize"))
binSize = Integer.parseInt(prop.getValue());
}
byte[] content = new byte[binSize];
stream.read(content); //Its all empty now. If I use a DataInputStream instead, its got the values from the file
return info;
}
``` | If you genuinely have a file (rather than something harder to seek in, e.g. a network stream) then I suggest something like this:
* Open the file as a FileInputStream
* Wrap it in InputStreamReader and a BufferedReader
* Read the text, so you can find out how much content there is
* Close the BufferedReader (which will close the InputStreamReader which will close the FileInputStream)
* Reopen the file
* Skip to (total file length - binary content length)
* Read the rest of the data as normal
You could just call `mark()` at the start of the FileInputStream and then `reset()` and `skip()` to get to the right place if you want to avoid reopening the file. (I was looking for an `InputStream.seek()` but I can't see one - I can't remember wanting it before in Java, but does it really not have one? Ick.) | You could use [**`RandomAccessFile`**](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html). Use [`readLine()`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#readLine()) to read the plain text at the start (note the limitations of this, as described in the API), and then [`readByte()`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#readByte()) or [`readFully()`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#readFully(byte%5b%5d)) to read the subsequent binary data.
> Using the underlying [`FileInputStream`](http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html)
> to read returns empty byte arrays.
That's because you have wrapped the stream in a [`BufferedReader`](http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html), which has probably consumed all the bytes from the stream when filling up its buffer. | Reading Strings and Binary from the same FileInputStream | [
"",
"java",
"io",
"stream",
""
] |
As per question, is it safe to store passwords on php pages such as
```
$password = 'pa$$w0rd';
```
If the users can't see it, it's safe, right?
EDIT:
Some people actually suggested using hash, however, there would be a problem with database server connection password, wouldn't it? | The short answer is both No, and It Depends.
It's almost never a good idea to store passwords in plain text, especially in a web accessible location, if for **no** other reason than a simple server misconfiguration or an echo in the wrong place could expose it to the world.
If you MUST store a password, (which is possible) you could try to store it outside the webroot, eg
`/var/www/public_html/` Put your codez here
`/var/www/includes/` Put your passwords here
Even better than that would be to have the system that you need the password for (eg a database wrapper ) return an object already instantiated. so rather than asking for `$databasepassword` you ask for a PDO object, and store your database classes outside the webroot.
The It Depends comes from what attack vectors would cause someone to have access to that password text, and would it require them to be already inside your filesystem, if so, you're probably screwed anyway.
Also, if its the password to your supa-secrit subscriber content, meh, all you've lost is some subscription fees, if its your database, you may have a problem, if it's your online banking details, um good for you.
How valuable is the thing the password is protecting? | Depending on how you define safe, any approach has its positive and negative aspects.
If you really want to store a password in your source, it might be a good idea to do something of the sort:
File: config.php
```
if( ! defined('IN_CODE') ) die( 'Hacking attempt' );
define( 'PASSWORD_HASH', '098f6bcd4621d373cade4e832627b4f6' );
```
File: index.php
```
define( 'IN_CODE', '1' );
include( 'passwd.php' );
if( md5($password) == PASSWORD_HASH )
...
```
Plain-text is never a good idea, always store a hash of the password you want to store.
Furthermore, try to seperate defines like this from your main sourcefile. | Is it ever ok to store password in plain text in a php variable or php constant? | [
"",
"php",
"security",
"passwords",
""
] |
First of all, the static keyword.
I've read several articles and past threads on here covering the static keyword. I haven't found many scenarios listed of when I should use it. All I know is it doesn't create an object on the heap which tells me it would be good from a performance point of view for an object used a lot.
Is there any other reason to use it?
Also, I have read something about the static keyword and how it shouldn't be used with instance variables or to alter state. Can someone clarify this? It seems like this is a case of 2+2 but I can't get an answer (missing a few fundamental and simple pieces of knowledge).
Lastly, on the topic of thread safety, what should I look for in my code to get an idea of thread safety?
I have posted this in VB.NET too because I don't think different languages (C#/VB.NET) will have different rules.
Thanks | The static keyword means something different in C, but in C# and Java it declares methods and variables to be of the class rather than an object.
You would want to use it for methods and variables that don't need any data from a particular object, but use the same data for each object of that type.
For example String.Format() is a static method of the String class. You call it in your code without creating a String instance. Likewise, Math.Pi would be a class variable.
But something like a length method doesn't make any sense unless it acts upon a specific instance of a string, so it would have to be an instance method. E.g., x = "hello".Length();
So if you want your method to be called with just the class name and not on an object, then you make a static method. Note that such a method can only reference static variables and call static methods, as it doesn't have an object with which to reference non-static members.
In C, the static keyword denotes file scope linkage. A top-level static variable or function does not get its name exported to other compiled object code. So two files can declare static variables of the same name and not create a conflict. We don't have this problem in C#, because there are namespaces, and private, protected, and public keywords to denote visibility.
Yet another meaning is for static variables within a function in C. These variables retain their value between calls to the function. For example, you could use one to count the number of times the function has been called. Static variables in C# also have this property, but you don't declare them within the method as in C, just within the class. | > Lastly, on the topic of thread safety, what should I look for in my code to get an idea of thread safety?
Writing thread-safe code is a hefty topic that I won't go into here, but I will say one thing on the topic of static & thread safety.
Most methods of ensuring code runs as intended for multiple calling threads involve some kind of locking on an object instance. You will notice that in the .NET framework (BCL), all static members are threadsafe. This is because there is no clear way of knowing what instance of an object ought to be locked on in order to share this resource between all conceivable callers.
Old guidelines used to suggest locking on the type itself, ie:
```
lock (typeof(SomeType))
{
SomeType.SomeStaticMethod(...);
}
```
This approach is now discouraged and is inadvisable because there is no way of controlling the order of accesses to these lock objects across all conceivable calling threads. Locking on public objects (including `ICollection.SyncRoot`, which is now deprecated for the same reason) is opening the door to deadlocks. In the case above, the type instance is publically available, and should not be locked upon.
Given that there is no single instance that all clients of static methods can reasonably agree upon using for their access of static members, Microsoft's BCL team has had to make all static members typesafe. Thankfully for them, static members are few and far between. | Static keyword, state/instance variables, and thread safety | [
"",
"c#",
".net",
"vb.net",
""
] |
I have a string containing the [UNIX Epoch time](https://en.wikipedia.org/wiki/Unix_time), and I need to convert it to a Java Date object.
```
String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
Date expiry = df.parse(date);
} catch (ParseException ex) {
ex.getStackTrace();
}
```
The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat(). | How about just:
```
Date expiry = new Date(Long.parseLong(date));
```
EDIT: as per [rde6173](https://stackoverflow.com/users/62195/rde6173)'s answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:
```
Date expiry = new Date(Long.parseLong(date) * 1000);
``` | Epoch is the number of **seconds** since Jan 1, 1970..
So:
```
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
```
For more information:
<http://www.epochconverter.com/> | Unix epoch time to Java Date object | [
"",
"java",
"date",
"java-time",
""
] |
Swing is good in many ways, then why do we need JavaFX? | I think Staale's answer is a good start but I would add...
Use JavaFX if
1) If you're interested in developing the application for mobile or TV (note this has yet to be released)
2) If you're working with a graphic designer who is creating the appearance of the application in photoshop and you want to be able to import their look directly.
3) If making the GUI filthy rich is important to you. (so if you want a panel to fade in or out, or slide upon demand)
Use Swing if
1) You're creating an application mainly for the desktop.
2) Performance matters and you know what you are doing (so if you're writing an IDE, Swing would be a better choice)
3) You're looking for a RPC (rich client platform) to build upon. | There is both a technology part of JavaFX that will help design UIs, and a language part that will make writing UIs easier.
The JavaFX technology brings a 2d scenegraph and video capabilities. Afaik these will also be made available generally to java. They are good advancements for creating client side application with fancy and interactive graphical UIs. The 2d scenegraph should make it possible to create more graphic heavy applications that are still responsive.
The JavaFX language is a much better way off creating UIs programatically. Java Swing code can get very verbose, while the same JavaFX code will be smaller and easier to maintain. Closure support makes creating event handlers easier. Declerative assignment of settings makes configuration of elements easier. Native list syntax makes adding components easier.
Please note that I haven't really written any JavaFX, but I have read code and paid attention to what's going on. I recommend trying it yourself to find out what's cooking. | Why do we need JavaFX though we have Swing? | [
"",
"java",
"swing",
"javafx",
""
] |
I'm trying to use java.util.Scanner to take Wikipedia contents and use it for word based searches.
The fact is that it's all fine but when reading some words it give me errors.
Looking at code and making some check it turned out that with some words it seems
not to recognize the encoding, or so, and the content is no more readable.
This is the code used to take the page:
// -Start-
```
try {
connection = new URL("http://it.wikipedia.org
wiki/"+word).openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
// if(word.equals("pubblico"))
// System.out.println(content);
System.out.println("Doing: "+ word);
//End
```
The problem arises with words as "pubblico" for the italian wikipedia.
the result of the println on word pubblico is like this (cutted):
ï¿ï¿½]Ksr>�~E
�1A���E�ER3tHZ�4v��&PZjtc�¿½ï¿½D�7\_|����=8��Ø}
Do you have any idea why? Yet looked at page source and headers are the same, with same encoding...
Turned Out that content is gzipped, so can i tell wikipedia not to send me teir pages zipped or it's the only way? thank you | Try using a `Reader` instead of an `InputStream` - I think it works something like this:
```
connection = new URL("http://it.wikipedia.org/wiki/"+word).openConnection();
String ctype = connection.getContentType();
int csi = ctype.indexOf("charset=");
Scanner scanner;
if (csi > 0)
scanner = new Scanner(new InputStreamReader(connection.getInputStream(), ctype.substring(csi + 8)));
else
scanner = new Scanner(new InputStreamReader(connection.getInputStream()));
scanner.useDelimiter("\\Z");
content = scanner.next();
if(word.equals("pubblico"))
System.out.println(content);
System.out.println("Doing: "+ word);
```
You could also just pass the charset to the Scanner constructor directly as indicated in another answer. | Try using the Scanner with a specified character set:
```
public Scanner(InputStream source, String charsetName)
```
For the default constructor:
> Bytes from the stream are converted into characters using the underlying platform's default charset.
[Scanner on java.sun.com](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#Scanner(java.io.InputStream,%20java.lang.String)) | java.util.Scanner and Wikipedia | [
"",
"java",
"wikipedia",
"java.util.scanner",
""
] |
When said this code need some optimization, or can be some how optimized, what does that mean? which kind of code need optimization? How to apply optimization to the code in c#? What the benefits from that? | *Optimization* is a very broad term. In general it implies modifying the system to make some of its aspect to work more efficiently or use fewer resources or be more robust. For example, a computer program may be optimized so that it will execute faster or use less memory or disk storage or be more responsive in terms of UI.
Although "optimization" has the same root as "optimal", the process of optimization does not produce a totally optimal system: there's always a trade-off, so only attributes of greatest interest are optimized.
And remember:
> The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet. ([Michael A. Jackson](http://en.wikipedia.org/wiki/Michael_A._Jackson)) | [Optimization](http://en.wikipedia.org/wiki/Software_optimization) is the process of modifying a system to make some aspect of it work more efficiently or use fewer resources.
In your case refers mainly to 2 levels:
> **Design level**
>
> At the highest level, the design may be optimized to make best use of the available resources. The implementation of this design will benefit from a good choice of efficient algorithms and the implementation of these algorithms will benefit from writing good quality code. The architectural design of a system overwhelmingly affects its performance. The choice of algorithm affects efficiency more than any other item of the design. In some cases, however, optimization relies on using fancier algorithms, making use of special cases and special tricks and performing complex trade-offs; thus, a fully optimized program can sometimes, if insufficiently commented, be more difficult for less experienced programmers to comprehend and hence may contain more faults than unoptimized versions.
>
> **Source code level**
>
> Avoiding bad quality coding can also improve performance, by avoiding obvious slowdowns. After that, however, some optimizations are possible which actually decrease maintainability; some, but not all of them can nowadays be performed by optimizing compilers. For instance, using more indirection is often needed to simplify or improve a software, but that indirection has a cost. | What is code optimization? | [
"",
"c#",
"optimization",
""
] |
I'm trying to work out if an account expires in less than 30 days. Am I using DateTime Compare correctly?
```
if (DateTime.Compare(expiryDate, now) < 30)
{
matchFound = true;
}
``` | > Am I using DateTime Compare correctly?
No. `Compare` only offers information about the relative position of two dates: less, equal or greater. What you want is something like this:
```
if ((expiryDate - DateTime.Now).TotalDays < 30)
matchFound = true;
```
This subtracts two `DateTime`s. The result is a [`TimeSpan`](http://msdn.microsoft.com/en-us/library/system.timespan(VS.80).aspx) object which has a `TotalDays` property.
Additionally, the conditional can be written directly as:
```
bool matchFound = (expiryDate - DateTime.Now).TotalDays < 30;
```
No `if` needed.
Alternatively, you can avoid naked numbers by using `TimeSpan.FromDays`:
```
bool matchFound = (expiryDate - DateTime.Now) < TimeSpan.FromDays(30);
```
This is slightly more verbose but I generally recommend using the appropriate types, and the appropriate type in this case is a `TimeSpan`, not an `int`. | should be
```
matchFound = (expiryDate - DateTime.Now).TotalDays < 30;
```
note the total days
otherwise you'll get werid behaviour | DateTime.Compare how to check if a date is less than 30 days old? | [
"",
"c#",
".net",
"datetime",
""
] |
I don't have much experience with using the yield keyword. I have these IEnumerable<T> extensions for Type Conversion.
My question is does the first overloaded method have the same yield return effect that I'm getting from the second method?
```
public static IEnumerable<TTo> ConvertFrom<TTo, TFrom>(this IEnumerable<TFrom> toList)
{
return ConvertFrom<TTo, TFrom>(toList, TypeDescriptor.GetConverter(typeof(TTo)));
}
public static IEnumerable<TTo> ConvertFrom<TTo, TFrom>(this IEnumerable<TFrom> toList, TypeConverter converter)
{
foreach (var t in toList)
yield return (TTo)converter.ConvertFrom(t);
}
``` | When you call the first overload, it will immediately call the second overload. That won't execute any of the code in its body, which will have been moved into a nested class implementing the iterator block. When `GetEnumerator()` and then `MoveNext()` are first called on the returned `IEnumerable<TTo>`, *then* the code in your second overload will begin executing.
I have a fairly long [article on the iterator block implementation](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx), which you may find interesting. | Yes, because **yield return** just generates an IEnumerator class on compile. `yield return` is just compiler magic. | Overloaded use of yield return | [
"",
"c#",
"yield",
""
] |
I am a newbie in C++ programming.
When compiling I never use any option.
This is my day to day command:
```
g++ MyCode.cc -o MyCode
```
For safety practice what's the best option
to use? | ```
g++ -W -Wall -Werror
```
Will display all errors and warnings possible and treat them as errors. | “-Werror”: treats all warnings as errors so you have to fix them. Incredibly valuable. | What's your favorite g++ option? | [
"",
"c++",
"unix",
"gcc",
"compiler-construction",
"g++",
""
] |
In a simulation server environment where users are allowed to submit their own code to be run by the server, it would clearly be advantageous for any user-submitted code to be run in side a sandbox, not unlike Applets are within a browser. I wanted to be able to leverage the JVM itself, rather than adding another VM layer to isolate these submitted components.
This kind of limitation appears to be possible using the existing Java sandbox model, but is there a dynamic way to enable that for just the user-submitted parts of a running application? | 1. Run the untrusted code in its own thread. This for example prevents problems with infinite loops and such, and makes the future steps easier. Have the main thread wait for the thread to finish, and if takes too long, kill it with Thread.stop. Thread.stop is deprecated, but since the untrusted code shouldn't have access to any resources, it would be safe to kill it.
2. Set a [SecurityManager](http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html) on that Thread. Create a subclass of SecurityManager which overrides [checkPermission(Permission perm)](http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html#checkPermission(java.security.Permission)) to simply throw a [SecurityException](http://java.sun.com/javase/6/docs/api/java/lang/SecurityException.html) for all permissions except a select few. There's a list of methods and the permissions they require here: [Permissions in the JavaTM 6 SDK](http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html).
3. Use a custom ClassLoader to load the untrusted code. Your class loader would get called for all classes which the untrusted code uses, so you can do things like disable access to individual JDK classes. The thing to do is have a white-list of allowed JDK classes.
4. You might want to run the untrusted code in a separate JVM. While the previous steps would make the code safe, there's one annoying thing the isolated code can still do: allocate as much memory as it can, which causes the visible footprint of the main application to grow.
[JSR 121: Application Isolation API Specification](http://jcp.org/en/jsr/detail?id=121) was designed to solve this, but unfortunately it doesn't have an implementation yet.
This is a pretty detailed topic, and I'm mostly writing this all off the top of my head.
But anyway, some imperfect, use-at-your-own-risk, probably buggy (pseudo) code:
*ClassLoader*
```
class MyClassLoader extends ClassLoader {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name is white-listed JDK class) return super.loadClass(name);
return findClass(name);
}
@Override
public Class findClass(String name) {
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name) {
// load the untrusted class data here
}
}
```
*SecurityManager*
```
class MySecurityManager extends SecurityManager {
private Object secret;
public MySecurityManager(Object pass) { secret = pass; }
private void disable(Object pass) {
if (pass == secret) secret = null;
}
// ... override checkXXX method(s) here.
// Always allow them to succeed when secret==null
}
```
*Thread*
```
class MyIsolatedThread extends Thread {
private Object pass = new Object();
private MyClassLoader loader = new MyClassLoader();
private MySecurityManager sm = new MySecurityManager(pass);
public void run() {
SecurityManager old = System.getSecurityManager();
System.setSecurityManager(sm);
runUntrustedCode();
sm.disable(pass);
System.setSecurityManager(old);
}
private void runUntrustedCode() {
try {
// run the custom class's main method for example:
loader.loadClass("customclassname")
.getMethod("main", String[].class)
.invoke(null, new Object[]{...});
} catch (Throwable t) {}
}
}
``` | Obviously such a scheme raises all sorts of security concerns. Java has a rigorous security framework, but it isn't trivial. The possibility of screwing it up and letting an unprivileged user access vital system components shouldn't be overlooked.
That warning aside, if you're taking user input in the form of source code, the first thing you need to do is compile it to Java bytecode. AFIAK, this cannot be done natively, so you'll need to make a system call to javac, and compile the source code to bytecode on disk. [Here's](http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml) a tutorial that can be used as a starting point for this.
**Edit**: as I learned in the comments, you actually can compile Java code from source natively using [javax.tools.JavaCompiler](http://java.sun.com/javase/6/docs/api/javax/tools/JavaCompiler.html)
Once you have JVM bytecode, you can load it into the JVM using a [ClassLoader's](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html) [defineClass](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html#defineClass(java.lang.String,%20byte[],%20int,%20int,%20java.security.ProtectionDomain)) function. To set a security context for this loaded class you will need to specify a [ProtectionDomain](http://java.sun.com/j2se/1.4.2/docs/api/java/security/ProtectionDomain.html). The minimal constructor for a [ProtectionDomain](http://java.sun.com/j2se/1.4.2/docs/api/java/security/ProtectionDomain.html) requires both a CodeSource and a [PermissionCollection](http://java.sun.com/j2se/1.4.2/docs/api/java/security/PermissionCollection.html). The PermissionCollection is the object of primary use to you here- you can use it to specify the exact permissions the loaded class has. These permissions should be ultimately enforced by the JVM's [AccessController](http://java.sun.com/javase/6/docs/api/java/security/AccessController.html).
There's a lot of possible points of error here, and you should be extremely careful to completely understand everything before you implement anything. | Sandbox against malicious code in a Java application | [
"",
"java",
"plugins",
"sandbox",
""
] |
In C++, I have a class A which is friend with a class B.
I looks like inherited classes of B are not friend of class A.
I this a limitation of C++ or my mistake ?
Here is an example. When compiling, I get an error on line "return new Memento":
Memento::Memento : impossible to access private member declared in Memento.
```
class Originator;
class Memento
{
friend class Originator;
Memento() {};
int m_Data;
public:
~Memento() {};
};
class Originator
{
public:
virtual Memento* createMemento() = 0;
};
class FooOriginator : public Originator
{
public:
Memento* createMemento()
{
return new Memento; // Impossible to access private member of Memento
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
```
I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.
Any idea ? | See: [Friend scope in C++](https://stackoverflow.com/questions/437250/friend-scope-in-c/437507)
Voted exact duplicate.
```
I looks like inherited classes of B are not friend of class A.
```
Correct
```
I this a limitation of C++ or my mistake ?
```
It is the way C++ works. I don't see it as a limitation. | Friendship is not inherited, you have to explicitly declare every friend relationship. (See also "[friendship isn't inherited, transitive, or reciprocal](http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4)") | friend class : inherited classes are not friend as well? | [
"",
"c++",
"class",
"friend",
""
] |
I have a web report needs to return multiple products from different regions.
The simplified query will be like:
```
Select ProductName, ProductPrice
from Product
where Region in (Region1, Region2, Region 3)
```
The regions are selected by users from UI. The result is bound to a datagrid. It could be multiple regions. But the result will be look like
```
ProductName, ProductPrice [Region 1] ProductPrice [Region 2] ...
Prod1
Prod2
....
```
Products are not as same as in the same region. Some might be null in some regions. To dynamically bound to a grid, I am using a DataTable, then dynamically add datacolumn for the region fields. The easiest approach is to loop the result queried by every region, then merge by the Product (1, 2, 3...) It works, but slow, especially for rows more than 2K. I am wondering if any way we can avoid doing nested loop. | Are you using SQL Server? If so, you can use the [`PIVOT` operator](http://msdn.microsoft.com/en-us/library/ms177410.aspx) to pivot on the region. | I think we may need a little more information about the queries and the loop you are using, but can you use AJAX? Sounds like you want to make the UI experience more enjoyable and could get the information for Regions "on demand" | How to merge the result from database call? | [
"",
"c#",
"asp.net",
"ado.net",
".net-2.0",
""
] |
I have a SELECT statement that works, and runs fast enough on my tables (<0.01sec on 50k+ products, 3k+ categories). But in my mind it's not very elegant and would like to hear any suggestions on making it better.
There are 3 tables of interest:
* products - key productID
* categories - key categoryID
* products\_tree - link table (categories contain many products, products can belong to many categories)
I have a list of excluded categoryIDs [e.g. 1040,1050,1168]
I want to select all the productIDs that belong to one of these excluded categories **only if the product doesn't belong to another NON-excluded category**
My Query looks like this:
```
SELECT DISTINCT productID
FROM products_tree
WHERE
categoryID IN (1040,1050,1168)
AND productID NOT IN
( SELECT DISTINCT productID
FROM products_tree
WHERE
categoryID NOT IN (1040,1050,1168)
);
``` | I can think of a few methods, each of which perform differently depending on indexes and your particular database implementation. Some that may look slow can be optimised in ways you may not have imagined and so it's worth trialling them all and comparing execution plans to see what is happening...
Note1: I use GROUP BY rather than DISTINCT, this is because it allows the omptimiser to make use of indexes. I've seen implementations work out that they can turn the DISTINCT in to a GROUP BY, but it's highly worth using GROUP BY in the fist place to be sure. It also gets you thinking about indexes, which is never a bad thing.
Note2: Some queries like this take a while to optimise, as there are many options for the optimiser to evaluate. It is therefore often worth compiling all the different options in to stored procedures and comparing the execution of those stored procedures. This ensures your compare actually Query Time and not different Compile Times.
```
SELECT
[tree].productID
FROM
products_tree AS [tree]
WHERE
[tree].productID IN (1040,1050,1168)
AND NOT EXISTS (SELECT * FROM products_tree WHERE productID = [tree].productID AND categoryID NOT IN (1040,1050,1168))
GROUP BY
[tree].productID
```
```
SELECT
[tree].productID
FROM
products_tree AS [tree]
LEFT OUTER JOIN
(
SELECT
productID
FROM
product_tree
WHERE
productID NOT IN (1040,1050,1168)
GROUP BY
productID
)
AS [ok_products]
ON [ok_products].productID = [tree].productID
WHERE
[tree].productID IN (1040,1050,1168)
AND [ok_products].productID IS NULL
GROUP BY
[tree].productID
```
```
SELECT
[tree].productID
FROM
products_tree AS [tree]
GROUP BY
[tree].productID
HAVING
MAX(CASE WHEN [tree].productID IN (1040,1050,1168) THEN 1 ELSE 0 END) = 1
AND MAX(CASE WHEN [tree].productID NOT IN (1040,1050,1168) THEN 1 ELSE 0 END) = 0
```
There are others, and variations of each, but this should give you a very good start. But I really would stress the use of GROUP BY and the consideration to INDEXES :) | I believe your query is quite good, but you could compare it with joins:
```
SELECT DISTINCT pt1.productID
FROM products_tree pt1
LEFT JOIN products_tree pt2 ON pt2.productID = pt1.productID
AND pt2.categoryID pt1.categoryID
WHERE pt1.categoryID IN (1040,1050,1168)
AND pt2.productID IS NULL
```
Not sure if I thought correctly, but I think you understand my approach. I would however select productinfo directly if you want that, then the joins would make more sense (inner join the categories you want, left join the ones you don't want and check for null) | SQL: Select records belonging to excluded category that ONLY belong to excluded category | [
"",
"sql",
"mysql",
"optimization",
""
] |
As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is `const`. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them? | Trying to collect some uses:
**Binding some temporary to reference-to-const, to lengthen its lifetime.** The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called:
```
ScopeGuard const& guard = MakeGuard(&cleanUpFunction);
```
*Explanation*, using code:
```
struct ScopeGuard {
~ScopeGuard() { } // not virtual
};
template<typename T> struct Derived : ScopeGuard {
T t;
Derived(T t):t(t) { }
~Derived() {
t(); // call function
}
};
template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }
```
This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it.
---
**Use const to tell others methods won't change the logical state of this object.**
```
struct SmartPtr {
int getCopies() const { return mCopiesMade; }
};
```
---
**Use const for copy-on-write classes**, to make the compiler help you to decide when and when not you need to copy.
```
struct MyString {
char * getData() { /* copy: caller might write */ return mData; }
char const* getData() const { return mData; }
};
```
*Explanation*: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you *copy* on a *write* to either object, so that they now both have their own version.
*Using code*:
```
int main() {
string const a = "1234";
string const b = a;
// outputs the same address for COW strings
cout << (void*)&a[0] << ", " << (void*)&b[0];
}
```
The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write `std::string`. Both strings, even though they are distinct objects, share the same memory for their string data. Making `b` non-const will prefer the non-const version of the `operator[]` and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of `a`!
```
int main() {
string const a = "1234";
string b = a;
// outputs different addresses!
cout << (void*)&a[0] << ", " << (void*)&b[0];
}
```
---
**For the copy-constructor to make copies from const objects and temporaries**:
```
struct MyClass {
MyClass(MyClass const& that) { /* make copy of that */ }
};
```
---
**For making constants that trivially can't change**
```
double const PI = 3.1415;
```
---
**For passing arbitrary objects by reference instead of by value** - to prevent possibly expensive or impossible by-value passing
```
void PrintIt(Object const& obj) {
// ...
}
``` | There are really 2 main uses of const in C++.
**Const values**
If a value is in the form of a variable, member, or parameter that will not (or should not) be altered during its lifetime you should mark it const. This helps prevent mutations on the object. For instance, in the following function I do not need to change the Student instance passed so I mark it const.
```
void PrintStudent(const Student& student) {
cout << student.GetName();
}
```
As to why you would do this. It's much easier to reason about an algorithm if you know that the underlying data cannot change. "const" helps, but does not guarantee this will be achieved.
Obviously, printing data to cout does not require much thought :)
**Marking a member method as const**
In the previous example I marked Student as const. But how did C++ know that calling the GetName() method on student would not mutate the object? The answer is that the method was marked as const.
```
class Student {
public:
string GetName() const { ... }
};
```
Marking a method "const" does 2 things. Primarily it tells C++ that this method will not mutate my object. The second thing is that all member variables will now be treated as if they were marked as const. This helps but does not prevent you from modifying the instance of your class.
This is an extremely simple example but hopefully it will help answer your questions. | How many and which are the uses of "const" in C++? | [
"",
"c++",
"constants",
""
] |
I'm having some difficulties creating a javascript appointment style calendar. While it does render, I know there's go to be a much more efficient way of doing it. Does anyone have a pattern they use for creating calendars? I will be using jQuery, but I don't want to use someone's calendar plugin as a) I haven't found one that works for what I need and b) I'm never going to get any better by using someone elses work.
Now, keep in mind my question is not about loading data in or getting repeat occurances or anything like that. I'm basically needing to know a good pattern on actually rendering the calendar markup. | Ive just published a new OS project called FullCalendar (<http://arshaw.com/fullcalendar/>)
Sounds like what you might want. Pass it an array of events/appointments and it will render. The plugin only provides the essentials, but you can use event hooks to extend it. | Start with the [date.js](http://www.datejs.com/) library, why reinvent things like figuring out the name of the day of the week, leap years and things like that. Build your own visualization on top of it. | Creating A Javascript Calendar (Full, not pop up) | [
"",
"javascript",
"jquery",
"jquery-plugins",
"calendar",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.