Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Hashtables have a syncroot property but generic dictionaries don't. If I have code that does this:
```
lock (hashtable.Syncroot)
{
....
}
```
How do I replicate this if I am removing the hashtable and changing to generic dictionaries? | If you are going strictly for compatability then Bryan is correct. This is the best way to maintain your current semantics on top of a Dictionary.
Expanding on it though. The reason the SyncRoot property was not directly added to the generic dictionary is that it's a dangerous way to do synchronization. It's only slighly better than "lock(this)" which is very dangerous and prone to deadlocks. Here are a couple of links that speak to why this is bad.
* <http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx>
* <http://blogs.msdn.com/ricom/archive/2006/05/01/587750.aspx> | The new thinking behind SyncRoot is that it was a mistake in the original design. If the only thing to lock is the dictionary and it's private, you can lock it or another object that serves as the synchronization object. The latter technique is useful when the state you are protecting is more than just the dictionary.
```
// used as you would have used SyncRoot before
object _syncLock = new object();
Dictionary<string, int> numberMapper = new Dictionary<string, int>();
// in some method...
lock (_syncLock)
{
// use the dictionary here.
}
``` | Hashtable to Dictionary<> syncroot . | [
"",
"c#",
"generics",
"dictionary",
"hashtable",
""
] |
I'm wanting to use google maps and see a million ways to do it on the web. Some are javascript methods and some are asp.net server components with which I have hit and miss luck. What's the easiest and most reliable way using c# and asp.net?
I have my location data including geocodes in a database. I want to provide users a method to do a lookup for certain locations. From there, my code will provide a table of geocodes to google maps with markers on the map corresponding to the found entries. Users can see each entry and need to be able to tell which is which if multiple rows are returned.
Is there a good way to do this? | The Google Maps API is accessed via JavaScript (any server controls are just abstracting this away from you). In the case you described, you would need to dynamically output the required JavaScript to tell the maps API what to display.
See <http://dotnet.sys-con.com/node/171162> | There are a few server controls to do it, like [this](http://googlemaps.subgurim.net/), but you have to learn how to do things in one way (server control) or another (Javascript Google API).
I recommend using the Google API, since it has more samples all over the web, and you can use new features implemented by Google right after they release them and don't have to wait for the server control developer to do it. | Google Maps - Easy way in ASP.Net? | [
"",
"c#",
"asp.net",
"google-maps",
""
] |
Is there a way or tool for Vista I can use to search for content in Java files? (I do not have an Eclipse project set up for it)
I used to be able to do it easily in the windows search tool when I had Windows 2000.
Edit: I have already enabled "search file contents" and added additional file types as recommended by xsl and Grant Wagner, the search still returns no results... | Personally, I just use [BareGrep](http://www.baremetalsoft.com/baregrep/ "BareGrep") (and previously, [Agent Ransack](http://www.mythicsoft.com/agentransack/ "Agent Ransack")), which is fast, supports regexes and show lines that match.
[grepWin](http://tools.tortoisesvn.net/grepWin "grepWin") is nice too (can replace strings) but doesn't show lines. | There are tons of search tools. Simplest and smallest is the GNU grep.
I personnally use Far (for many things, not just search). | How do I search in files (for example in Java files) in Vista? | [
"",
"java",
"search",
"windows-vista",
""
] |
I have checked the whole site and googled on the net but was unable to find a simple solution to this problem.
I have a datatable which has about 20 columns and 10K rows. I need to remove the duplicate rows in this datatable based on 4 key columns. Doesn't .Net have a function which does this? The function closest to what I am looking for was datatable.DefaultView.ToTable(true, array of columns to display), But this function does a distinct on **all** the columns.
It would be great if someone could help me with this.
EDIT: I am sorry for not being clear on this. This datatable is being created by reading a CSV file and not from a DB. So using an SQL query is not an option. | You can use Linq to Datasets. Check [this](http://msdn.microsoft.com/en-us/library/bb669119.aspx). Something like this:
```
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
List<DataRow> rows = new List<DataRow>();
DataTable contact = ds.Tables["Contact"];
// Get 100 rows from the Contact table.
IEnumerable<DataRow> query = (from c in contact.AsEnumerable()
select c).Take(100);
DataTable contactsTableWith100Rows = query.CopyToDataTable();
// Add 100 rows to the list.
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
// Create duplicate rows by adding the same 100 rows to the list.
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
DataTable table =
System.Data.DataTableExtensions.CopyToDataTable<DataRow>(rows);
// Find the unique contacts in the table.
IEnumerable<DataRow> uniqueContacts =
table.AsEnumerable().Distinct(DataRowComparer.Default);
Console.WriteLine("Unique contacts:");
foreach (DataRow uniqueContact in uniqueContacts)
{
Console.WriteLine(uniqueContact.Field<Int32>("ContactID"));
}
``` | [How can I remove duplicate rows?](https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows). (Adjust the query there to join on your 4 key columns)
EDIT: with your new information I believe the easiest way would be to implement IEqualityComparer<T> and use Distinct on your data rows. Otherwise if you're working with IEnumerable/IList instead of DataTable/DataRow, it is certainly possible with some LINQ-to-objects kung-fu.
EDIT: example IEqualityComparer
```
public class MyRowComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
return (x.Field<int>("ID") == y.Field<int>("ID")) &&
string.Compare(x.Field<string>("Name"), y.Field<string>("Name"), true) == 0 &&
... // extend this to include all your 4 keys...
}
public int GetHashCode(DataRow obj)
{
return obj.Field<int>("ID").GetHashCode() ^ obj.Field<string>("Name").GetHashCode() etc.
}
}
```
You can use it like this:
```
var uniqueRows = myTable.AsEnumerable().Distinct(MyRowComparer);
``` | What is the best way to remove duplicates from a datatable? | [
"",
"c#",
"datatable",
"duplicates",
""
] |
This is my first time using joomla. I don't know if I'm using the concept of a Contact in the wrong way, but I have a Contact Us menu that I've created and I've added the contact details in. I'm looking to add a sentence or two of text above the contact details & the e-mail contact form. There doesn't seem to be a way of doing this via the administration page. Am I doing the right thing? What do I need to do if I want this? | If you really want it above the contact details you have to work with a layout-override. There is no way to do this through the admin backend. In Joomla 1.0 it was only possible with a hack, now in Joomla 1.5 there is the possibility of layout override.
[This article](http://docs.joomla.org/How_to_override_the_output_from_the_Joomla!_core) shows how it's done.
If you want to see it live, install the beez template, which has overrides for nearly all core components of Joomla. So you can check how beez does it and then do something similar with your own template. | Not exactly above the contact information but above the e-mail form you can use the "Miscellaneous Info" field to put any extra Data. | How do i add additional text to a joomla contact page | [
"",
"php",
"joomla",
""
] |
I bet I've got elementary question, but I couldn't solve it for two nights.
I've got 1 "ul" element and I just want it to move any amount of pixels every e.g. 2 sec to the left. I want him to move like this step by step and then come back to the original position and start moving again.
I've been stucked, my script only moves it to the final position and finish.
```
window.onload = function moveUl(){
var eUl = document.getElementById('change');
var eLi = eUl.getElementsByTagName('li');
x = -300;
function move(){
for(i=0;i< eLi.length;i++){
eUl.style.marginLeft = i*x+'px';
}
}
setInterval(move,1000);
}
```
This is the simpliest I can think of. I know this script executes whole loop after 1 sec, but I try to do something like this : Move this element to the left, wait, move more to left and so on. | Do you mean something like this?
```
window.onload = function moveUl()
{
var eUl = document.getElementById('change');
var eLi = eUl.getElementsByTagName('li');
var delta = 0;
function move()
{
for(i=0;i< eLi.length;i++)
eUl.style.marginLeft = (-300*i+delta)+'px';
delta -= 100; // Prepares for the next step
if ( delta == -1000 )
delta = 0; // Resets after 10 steps
}
setInterval(move,1000);
}
``` | If you want it to slide, you have to timeout per iteration. Try writing a function that does a single shift, then calling this function every 10 ms. You can also look into a Javascript library like [jQuery](http://www.jquery.com) that provides a nice API for doing the moving. | I would like to move an element to the left using loop | [
"",
"javascript",
""
] |
What is classpath hell and is/was it really a problem for Java? | Classpath hell is an unfortunate consequence of dynamic linking of the kind carried out by Java.
Your program is not a fixed entity but rather the exact set of classes loaded by a JVM in a particular instance.
It is very possible to be in situations where the same command line on different platforms or even on the same one would result in completely different results because of the resolution rules.
There could be differences in standard libraries (very common). Libraries could be hidden by one another (an an older version may even be used instead of a newer one). The directory structure could mess resolution. A different version of the same class may appear in multiple libraries and the first one encountered will be used, etc. Since Java, by specification, uses a first-encountered policy, unknown ordering dependencies can lead to problems. Of course, since this is the command line and it is part of the spec, there are no real warnings.
It is very much still a problem. For example on Mac OS the horrible support from Apple means that you machine ends up with several JVMs and several JREs, and you can never easily poart things from place to place. If you have multiple libraries that were compiled against specific but different versions of other libraries, you coulld have problems, etc.
However, this problem is not inherent in Java. I remember my share of DLL hell situations while programming windows in the 90s. Any situation where you have to count on something in the file system to assemble your program rather than having a single well defined executable is a problem.
However, the benefits of this model are still great, so I'm willing to tolerate this hell. There are also steps in the right direction on the side of Sun. For example, Java6 allows you to simply specify a directory with jars rather than have to enumerate them.
BTW: Classpaths are also a problem if you are using an environment that uses a non-default classloader. For example, I have had a lot of problems running things like Hibernate or Digester under Eclipse because the classloaders were incompatible. | Classpath/jar-hell has a couple of escape hatches if they make sense for your project:
* [OSGi](http://en.wikipedia.org/wiki/OSGi)
* [JarJarLinks](http://code.google.com/p/jarjar/)
* [NetBeans Module System](http://www.antonioshome.net/kitchen/netbeans/nbms-theplatform.php) - Not sure if this is usable outside of NetBeans
* Others? | What is classpath hell and is/was it really a problem for Java? | [
"",
"java",
"history",
""
] |
I've come up with:
```
re.findall("([a-fA-F\d]*)", data)
```
but it's not very fool proof, is there a better way to grab all MD5-hash codes? | Well, since md5 is just a string of 32 hex digits, about all you could add to your expression is a check for "32 digits", perhaps something like this?
```
re.findall(r"([a-fA-F\d]{32})", data)
``` | When using regular expressions in Python, you should almost always use the raw string syntax `r"..."`:
```
re.findall(r"([a-fA-F\d]{32})", data)
```
This will ensure that the backslash in the string is not interpreted by the normal Python escaping, but is instead passed through to the `re.findall` function so it can see the `\d` verbatim. In this case you are lucky that `\d` is not interpreted by the Python escaping, but something like `\b` (which has completely different meanings in Python escaping and in regular expressions) would be.
See the [`re` module documentation](http://python.org/doc/2.5/lib/module-re.html) for more information. | Python regex for MD5 hash | [
"",
"python",
"regex",
"md5",
""
] |
I very rarely meet any other programmers!
My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.
So how do I say or read "=>" as in:-
```
IEnumerable<Person> Adults = people.Where(p => p.Age > 16)
```
Or is there even an agreed way of saying it? | I usually say 'such that' when reading that operator.
In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16."
In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying
> I usually read the => operator as "becomes" or "for which". For example,
> Func f = x => x \* 2;
> Func test = c => c.City == "London";
> reads as "x becomes x \* 2" and "c for which c.City equals London"
As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere.
In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, "p lambda p dot age greater-than sixteen."
In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example:
```
x => x * 2;
```
would read
> x maps to x times 2.
That does seem much closer to the actual intention of the code than 'becomes' for this case. | From [MSDN](http://msdn.microsoft.com/en-us/library/bb397687.aspx):
> All lambda expressions use the lambda
> operator =>, which is read as "goes
> to". | How do I pronounce "=>" as used in lambda expressions in .Net | [
"",
"c#",
".net",
"lambda",
"conventions",
""
] |
I've created a *very* simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input.
I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Windows window, top left of a Mac window) This button currently does nothing.
Taking a look at the easygui module I found this line:
```
root.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
```
This would seem to be the culprit. I'm no TKinter expert but I could probably work out how to alter this handler to act the way I want.
However, as I'd rather not mess about with the easygui module, Is there a way to override this behavior from my main script, and have the close button either close the program outright or return None? | It would require altering the easygui module, yes. I will get it modified!
\*\* I have sent in a e-mail to the EasyGUI creator explaning this [12:12 PM, January 23/09]
\*\* I just want to say that the possibility of this change happening - if at all, which I doubt - is very tiny. You see, EasyGUI is intended to be a simple, discrete way to create GUIs. I think that this addition wouldn't help any, especially since the interface is very sequential, so it would be confusing to new users. [12:19 PM, January 23/09]
\*\* The EasyGUI creator said this in reply to my e-mail:
> An easygui dialog should never exit
> the application -- it should pass back
> a value to the caller and let the
> caller decide what to do.
>
> But this is an interesting idea.
> Rather than simply ignoring a click on
> the "close" icon, easygui boxes could
> return the same value that a click on
> the "cancel" button would return.
> I'll meditate on this.
>
> -- Steve Ferg
I think that this is progress at least. [2:40 PM, January 23/09] | I don't know right now, but have you tried something like this?:
```
root.protocol('WM_DELETE_WINDOW', self.quit)
```
or
```
root.protocol('WM_DELETE_WINDOW', self.destroy)
```
I haven't tried, but google something like `"Tkinter protocol WM_DELETE_WINDOW"` | Close an easygui Python script with the standard 'close' button | [
"",
"python",
"user-interface",
"tkinter",
"easygui",
""
] |
Hi I'm using `System.Net.Mail` to send some HTML formatted emails.
What is the correct method for inserting css into the email message?
I know I can apply formatting to each item, but I'ld rather use style sheets..
**EDIT**
I should have mentioned that this is for an internal application, and I expect 99% of users to be using Outlook or other client, but never hotmail or gmail etc. | I've always found that strictly using **HTML 3.0 compatible tags and formatting** works best for all email readers and providers.
nevertheless here is a [**CSS in Email** article](http://www.alistapart.com/articles/cssemail) that may answer your question, you will find solutions to your css problems. | The email clients don't use CSS in a uniform way so it's difficult to use CSS. This article can help - <http://www.alistapart.com/articles/cssemail/> | What is the best method for formatting email when using System.Net.Mail | [
"",
"c#",
"asp.net",
"css",
"system.net.mail",
""
] |
I'm trying to get started with unit testing in Python and I was wondering if someone could explain the advantages and disadvantages of doctest and unittest.
What conditions would you use each for? | Both are valuable. I use both doctest and [nose](https://pypi.python.org/pypi/nose/) taking the place of unittest. I use doctest for cases where the test is giving an example of usage that is actually useful as documentation. Generally I don't make these tests comprehensive, aiming solely for informative. I'm effectively using doctest in reverse: not to test my code is correct based on my doctest, but to check that my documentation is correct based on the code.
The reason is that I find comprehensive doctests will clutter your documentation far too much, so you will either end up with either unusable docstrings, or incomplete testing.
For actually testing the *code*, the goal is to thoroughly test every case, rather than illustrate what is does by example, which is a different goal which I think is better met by other frameworks. | I use unittest almost exclusively.
Once in a while, I'll put some stuff in a docstring that's usable by doctest.
95% of the test cases are unittest.
Why? I like keeping docstrings somewhat shorter and more to the point. Sometimes test cases help clarify a docstring. Most of the time, the application's test cases are too long for a docstring. | Python - doctest vs. unittest | [
"",
"python",
"unit-testing",
"comparison",
"doctest",
""
] |
How do I check to see if a column exists in a `SqlDataReader` object? In my data access layer, I have create a method that builds the same object for multiple stored procedures calls. One of the stored procedures has an additional column that is not used by the other stored procedures. I want to modified the method to accommodate for every scenario.
My application is written in C#. | ```
public static class DataRecordExtensions
{
public static bool HasColumn(this IDataRecord dr, string columnName)
{
for (int i=0; i < dr.FieldCount; i++)
{
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
}
```
Using `Exception`s for control logic like in some other answers is [considered bad practice](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing) and has performance costs. It also sends false positives to the profiler of # exceptions thrown and god help anyone setting their debugger to break on exceptions thrown.
GetSchemaTable() is also another suggestion in many answers. This would not be a preffered way of checking for a field's existance as it is not implemented in all versions (it's abstract and throws NotSupportedException in some versions of dotnetcore). GetSchemaTable is also overkill performance wise as it's a pretty heavy duty function if you [check out the source](https://github.com/microsoft/referencesource/blob/24a17c0c3b23ddeac0926acc13b13c54b650d3be/System.Data/System/Data/SqlClient/SqlDataReader.cs#L422).
Looping through the fields can have a small performance hit if you use it a lot and you may want to consider caching the results. | The correct code is:
```
public static bool HasColumn(DbDataReader Reader, string ColumnName) {
foreach (DataRow row in Reader.GetSchemaTable().Rows) {
if (row["ColumnName"].ToString() == ColumnName)
return true;
} //Still here? Column not found.
return false;
}
``` | Check for column name in a SqlDataReader object | [
"",
"c#",
".net",
"sqldatareader",
""
] |
I'm creating a zip file using the class FastZip from SharpZipLib and once I after I close the program, I cannot delete the file because:
"Cannot delete zip.zip: It is being used by another person or program. Close any programs that might be using the file and try again."
The code that is generating the file is simply this:
```
fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
```
I tried using:
```
using (FastZip fZip = new FastZip())
{
try
{
fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
}
catch (Exception)
{
}
}
```
But it doesn't convert to iDisposable | Perhaps antivirus is busy checking the file? If not, then get a program that can tell you which programs have files open.
You can look at:
* [Unlocker](http://www.emptyloop.com/unlocker/)
* [IARSN TaskInfo](http://www.iarsn.com/) | It looks like it may be a bug with SharpZipLib. The FastZip.CreateZip method has three overloads and two of them create use File.Create such as:
```
CreateZip(File.Create(zipFileName), // ...
```
It seems it does not close the stream, so you may be better off using:
```
string zipFileName = System.IO.Path.Combine(filesPath, this.zipName);
using (Stream stream = File.Create(zipFileName))
{
fZip.CreateZip(stream, filesPath, false, this.zipFilter, null);
stream.Close();
}
```
Technically you shouldn't need to call Close in the using block, but I like to be explicit about it. | Cannot Delete Zip file Created by SharpZipLib (FastZip) | [
"",
"c#",
"file",
"sharpziplib",
""
] |
Can someone explain to me why this code prints 14? I was just asked by another student and couldn't figure it out.
```
int i = 5;
i = ++i + ++i;
cout<<i;
``` | The order of side effects is undefined in C++. Additionally, modifying a variable twice in a single expression has no defined behavior (See the [C++ standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf), §5.0.4, physical page 87 / logical page 73).
Solution: Don't use side effects in complex expression, don't use more than one in simple ones. And it does not hurt to enable all the warnings the compiler can give you: Adding `-Wall`(gcc) or `/Wall /W4`(Visual C++) to the command line yields a fitting warning:
```
test-so-side-effects.c: In function 'main':
test-so-side-effects.c:5: warning: operation on 'i' may be undefined
test-so-side-effects.c:5: warning: operation on 'i' may be undefined
```
Obviously, the code compiles to:
```
i = i + 1;
i = i + 1;
i = i + i;
``` | That's undefined behaviour, the result will vary depending on the compiler you use. See, for example, [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15). | i = ++i + ++i; in C++ | [
"",
"c++",
"puzzle",
"operator-precedence",
""
] |
Is it possible to cast an object in Java to a combined generic type?
I have a method like:
```
public static <T extends Foo & Bar> void doSomething(T object) {
//do stuff
}
```
Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar).
The problem is when I need to call this method the object I need to pass to it is received as `java.lang.Object` and I need to cast it to make the compiler happy. But I can't figure out how to make this cast.
edit:
The problem lies in a function like this:
```
public void problemFunction (Object o) {
if ( o instanceof Foo && o instanceof Bar) {
doSomething((Problematic cast) o);
}
}
```
} | Java 8 introduces the possibility of [casting with additional bounds](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16). You can cast an `Object` as a `class` with multiple `interfaces` (or just as multiple `interfaces`).
So this:
```
doSomething((Problematic cast) o);
```
simply becomes to this:
```
doSomething((Foo & Bar) o);
``` | Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type.
```
interface Baz extends Foo, Bar { }
public void caller(Object w) {
doSomething((Baz) w);
}
```
If other types are known, like `Baz`, to meet the bounds, you could test for those types, and have a branch in your caller that calls `doSomething` with a cast to those types. It's not pretty.
You could also use delegation, creating your own class `Baz` that meets the bounds required by `doSomething`. Then wrap the object you are passed in an instance of your `Baz` class, and pass that wrapper to `doSomething`.
```
private static class FooBarAdapter implements Foo, Bar {
private final Object adaptee;
FooBarAdapter(Object o) {
adaptee = (Foo) (Bar) o;
}
public int flip() { return ((Foo) adaptee).flip(); }
public void flop(int x) { ((Foo) adaptee).flop(x); }
public void blort() { ((Bar) adaptee).blort(); }
}
public void problemFunction (Object o) {
doSomething(new FooBarAdapter(o));
}
``` | How should I cast for Java generic with multiple bounds? | [
"",
"java",
"generics",
"casting",
"polymorphism",
""
] |
I'm trying to assert that one object is "equal" to another object.
The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties?
This is my current solution but I think there may be something better:
```
Assert.AreEqual(LeftObject.Property1, RightObject.Property1)
Assert.AreEqual(LeftObject.Property2, RightObject.Property2)
Assert.AreEqual(LeftObject.Property3, RightObject.Property3)
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN)
```
What I'm going for would be in the same spirit as the CollectionEquivalentConstraint wherein NUnit verifies that the contents of two collections are identical. | Override .Equals for your object and in the unit test you can then simply do this:
```
Assert.AreEqual(LeftObject, RightObject);
```
Of course, this might mean you just move all the individual comparisons to the .Equals method, but it would allow you to reuse that implementation for multiple tests, and probably makes sense to have if objects should be able to compare themselves with siblings anyway. | Do not override Equals just for testing purposes. It's tedious and affects domain logic.
Instead,
### Use JSON to compare the object's data
No additional logic on your objects. No extra tasks for testing.
Just use this simple method:
```
public static void AreEqualByJson(object expected, object actual)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var expectedJson = serializer.Serialize(expected);
var actualJson = serializer.Serialize(actual);
Assert.AreEqual(expectedJson, actualJson);
}
```
It seems to work out great. The test runner results info will show the JSON string comparison (the object graph) included so you see directly what's wrong.
**Also note!** If you have bigger complex objects and just want to compare parts of them you can (*use LINQ for sequence data*) create anonymous objects to use with above method.
```
public void SomeTest()
{
var expect = new { PropA = 12, PropB = 14 };
var sut = loc.Resolve<SomeSvc>();
var bigObjectResult = sut.Execute(); // This will return a big object with loads of properties
AssExt.AreEqualByJson(expect, new { bigObjectResult.PropA, bigObjectResult.PropB });
}
``` | Compare equality between two objects in NUnit | [
"",
"c#",
"unit-testing",
"automated-tests",
"nunit",
""
] |
Anticipating the day when multi-touch interfaces become more pervasive, are there libraries in Java that can be used for developing touch applications? I'm looking for interfaces similar to MouseListener / MouseMotionListener / MouseWheelListener. | The MT4j project has everything you need to develop multitouch applications in java.
All the well known multitouch gestures are already built in and can be accessed as simple
as listening to mouse events (for example: component.addGestureListener(..)).
It also features a hardware accelerated scene graph, similar to JavaFX.
You can even simulate multitouch input by connecting one ore more mice to your machine.
Check it out at <http://www.mt4j.org> | [Sparsh](http://code.google.com/p/sparsh-ui/) is still in my bookmarks from the last time I was investigating multitouch java solutions.
While not as straight forward as the typical mouse listener or click listener, it still provides a reasonable interface.
You need your listening class to implement `sparshui.client.Client`, which requires the `processEvent` method definition.
```
public void processEvent(int groupID, Event event) {
if(event instanceof TouchEvent) {
TouchEvent e = (TouchEvent)event;
if(e.getState() == TouchState.BIRTH) {
//do initial touch stuff
} else if(e.getState() == TouchState.MOVE) {
//do dragging stuff
}
}
else if(event instanceof DragEvent) {
DragEvent e = (DragEvent)event;
//do DragEvent specific stuff
} else if(event instanceof RotateEvent) {
RotateEvent e = (RotateEvent)event;
//do RotateEvent specific stuff
} else if(event instanceof ZoomEvent) {
ZoomEvent e = (ZoomEvent)event;
//do ZoomEvent specific stuff
}
//several other gesture types....
}
```
After that, you need to start up the gesture recognition server, passing in your component
```
new ServerConnection("localhost", objectImplementingClientInterface);
```
Looking at the code examples on the site should give you a pretty good idea of the framework. | How to develop multi-touch applications in Java? | [
"",
"java",
"touch",
"multi-touch",
""
] |
First, let me explain what I am doing. I need to take an order, which is split up into different databases, and print out this very large order. What I need from the orders is about 100 or so columns from different databases. The way I was doing in was querying with a join and assigning all of the column values to a variable in my one large Order class. This has started to become troublesome. I am wondering of instead of having one class that is comprised of 100 or so members that make up the order. Should I have just one class for every database I use, and then work with that?
Let me add to this. Basically, is it better to map you objects to the original database tables, or the result set. Because I have my object mapped to the result set and not the individual tables. | I'm going against the grain here, but I'd say that keeping this object mapped to the result set, and keeping the join in the database, might be a better idea.
For the business logic, an "order" is usually a single cohesive concept (at least, that's how you started out framing it). Could the fact that it is mapped into multiple tables (or databases) be an artifact of how the data is captured? I would ask myself these questions before breaking it up:
* Are there tangible benefits to composing the order out of other objects?
* Do the attributes have different cardinality? I.e. are some per-order and others per-line-item?
* Can you reuse existing code for the composed objects?
* Are you enabling some other interaction that's easier to do with multiple objects?
If you don't answer yes to any of those questions, I'd wager your code will be simpler and more readable if it deals with just the order as an atomic object, and lets the database hide the complexity of where it's coming from (you could even use a view for that).
Sheer number of attributes isn't usually a reason to break up an interface. But, if the complexity (or size) of the order object itself is what's getting you down, you might try to simplify it internally to use some sort of generic accessor method, like:
```
private object GetOrderAttribute(string attributeName){
// use a data structure (like a hash table) to store and access internally
}
...
output("Quantity: " + GetOrderAttribute("quantity"));
// etc.
```
One other note: while performance should rarely be your *starting* concern in logical system design, most cases involving database table joins will perform better if the database does the join, because the DBMS can use indexes and other mechanisms to perform the join efficiently and avoid loading pages from disk that aren't needed. Maybe all your individual queries do that too, but typically that's something the database can do an order of magnitude more efficiently than business logic code. (Of course, if the join is across physical database boundaries, that benefit might be lost.) | I would recommend an object-oriented solution to this. Presumably your database is designed with tables that represent logical groupings of data. Each of these tables can likely be mapped onto a class in your system, although in some cases, it may be more than one table that makes up an object or there might be multiple classes that a table maps onto using subclassing. If you need to display data from multiple tables -- say a list of orders with some data from the customer associated with the order -- then you can either use views, joins, or stored procedures to construct an object of a view class that represents the selected data in the view/join/sp.
Essentially what I am describing is an N-tier data architecture where you have a low-level data access layer that deals with data from a SQL orientation -- tables, views, stored procedures. Above this may be a generic object layer that deals with generic data objects and interfaces with the data access layer to store/retrieve objects from the database. Finally, above this you have a strongly-typed business object layer where your application works with classes that semantically linked to your application -- orders, customers, invoices, etc. There are many different patterns for implementing this type of general architecture and you should investigate several to see which fits your application needs the best. You might want to directly use an object-relational mapping like LINQ or nHibernate or you might want to layer a repository on top of an ORM.
Personally, I think that structuring your application to deal with objects within the context of your domain, rather than simply as table data, will improve your code. It should improve understandability and maintainability. You will be able to encapsulate behavior within your domain classes rather than have it spread throughout your application. Of course, this assumes that you follow good design practices, but using OO design will encourage this. Separating out the business and data logic from your display logic will also make your application much more testable, as will breaking down monolithic classes into smaller, more focused classes that are interrelated. | Should I have one class for every database I use? | [
"",
"c#",
"database",
"business-objects",
""
] |
I need to update a record in a database with the following fields
```
[ID] int (AutoIncr. PK)
[ScorerID] int
[Score] int
[DateCreated] smalldatetime
```
If a record exists for todays date (only the date portion should be checked, not the time) and a given scorer, I'd like to update the score value for this guy and this day. If the scorer doesn't have a record for today, I'd like to create a new one.
I'm getting grey hair trying to figure how to put this into a single (is this possible?) sql statement. By the way I'm using an MSSQl database and the `ExecuteNonQuery()` method to issue the query. | ```
IF EXISTS (SELECT NULL FROM MyTable WHERE ScorerID = @Blah AND CONVERT(VARCHAR, DateCreated, 101) = CONVERT(VARCHAR, GETDATE(), 101))
UPDATE MyTable SET blah blah blah
ELSE
INSERT INTO MyTable blah blah blah
``` | The other guys have covered 2005 (and prior) compatible T-SQL/apprroaches. I just wanted to add that if you are lucky enough to be working with SQL Server 2008, you could take advantage of the new Merge (sometimes referred to as Upsert) statement.
I had trouble finding a blog entry or article which explains it further, but I did find this rather [(1) helpful entry](http://www.sqlservercurry.com/2008/05/sql-server-2008-merge-statement.html). The official MSDN entry is [(2) here.](http://msdn.microsoft.com/en-us/library/bb510625.aspx)
(1) [<http://www.sqlservercurry.com/2008/05/sql-server-2008-merge-statement.html]>
(2) [<http://msdn.microsoft.com/en-us/library/bb510625.aspx]> | SQL Select: Update if exists, Insert if not - With date part comparison? | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
I've got a website (currently in development for a third party, I'm sorry I can't show) that requires users to confirm their contact information by, clicking on a link sent to their email address, upon registration for the website.
It's a pretty standard practice, not very technical or unique, which is why I was surprised to find that Hotmail and Yahoo (and maybe others, I'm not sure) are blocking any email messages that are generated dynamically via the PHP code that runs the website.
I'm using the PHP framework CodeIgniter, and making use of their email library. I've checked my code and everything looks great, and I've also looked over the email class and it looks tip-top as well.
Not to mention, the message sent are delivered to every other mail service I've tried, including gmail, and several POP accounts. This leads me to believe that the problem is on the Hotmail/Yahoo end.
I suspect they are purposefully rejecting/bouncing the message due to formatting, subject content, or some other arbitrary issue.
The HTML email design is minimal, only really utilizing HTML for header tags a link. The subject of the message simply states "Welcome to \_\_\_\_", and is addressed from "support@\_\_\_\_\_\_.com".
My question is, are there any articles relating to what could be causing this that I could read to better understand why the messages are being rejected, so I can fix the issue?
Preferably the article or document would be from Hotmail and Yahoo (with inside info), or from somebody who has experienced the same issue, and has come to a solution.
Also, are there any available utilities to test what is actually happening with the message once it hits their servers (i.e. Is it being bounced, or something else?)
Thank you very much! :) | Make sure you have [SPF records](http://www.openspf.org/) for your domain, and that they are set correctly. This will go a long way.
Email deliverability is a complex topic. At a previous gig, I was a member of the [ESPC](http://www.espcoalition.org/). This [PDF link](http://www.espcoalition.org/ESPC_Authentication_Report.pdf) may be helpful, or outdated. Also see this other [similar SO question](https://stackoverflow.com/questions/250234/sending-mail-with-php-escaping-hotmails-junk-folder). | My friend had a notification system that he has his PHP code send the notifications using a SMTP. So his notiifications were really sent from his Gmail account. He did this to prevent hotmail/etc from auto blocking the emails.
I don't know if this helps | Hotmail / Yahoo (Others?) blocking email notifications? | [
"",
"php",
"email-notifications",
"email-bounces",
""
] |
```
function a () {
return "foo";
}
a.b = function () {
return "bar";
}
function c () { };
c.prototype = a;
var d = new c();
d.b(); // returns "bar"
d(); // throws exception, d is not a function
```
Is there some way for `d` to be a function, and yet still inherit properties from `a`? | Based on a [discussion on meta](https://meta.stackoverflow.com/questions/356167/why-was-this-edit-rejected-with-a-seeming-unrelated-generic-response/356168?noredirect=1#comment511249_356168) [about a similar question](https://stackoverflow.com/questions/37625164/object-createfunction-prototype-create-function-which-inherits-properties) I'm posting this answer here based on [@alexander-mills](https://stackoverflow.com/users/1223975/alexander-mills) original
---
# This can now be done in a standards compliant way
First create an object which inherits `Function`
```
const obj = Object.create(Function.prototype); // Ensures availability of call, apply ext
```
Then add you custom methods and properties to `obj`
Next declare the function
```
const f = function(){
// Hello, World!
};
```
And set `obj` as the prototype of `f`
```
Object.setPrototypeOf(f,obj);
```
# Demonstraction
```
const obj = Object.create(Function.prototype);
// Define an 'answer' method on 'obj'
obj.answer = function() {
// Call this object
this.call(); // Logs 'Hello, World'
console.log('The ultimate answer is 42');
}
const f = function() {
// Standard example
console.log('Hello, World');
};
Object.setPrototypeOf(f, obj);
// 'f' is now an object with an 'answer' method
f.answer();
// But is still a callable function
f();
``` | Actually, it turns out that this **is possible**, albeit in a **non-standard** way.
Mozilla, Webkit, Blink/V8, Rhino and ActionScript provide a non-standard **`__proto__`** property, which allow changing the prototype of an object after it has been created. On these platforms, the following code is possible:
```
function a () {
return "foo";
}
a.b = function () {
return "bar";
}
function c () {
return "hatstand";
}
c.__proto__ = a;
c(); // returns "hatstand"
c.b(); // returns "bar"; inherited from a
```
This might be of use to anyone who doesn't need to worry about cross-platform compatibility.
However, note that only the **properties** of an object can be inherited. For example:
```
var d = {};
d.__proto__ = a;
d.b(); // returns "bar"
d(); // throws exception -- the fact that d is inheriting from a function
// doesn't make d itself a function.
``` | Can a JavaScript object have a prototype chain, but also be a function? | [
"",
"javascript",
"inheritance",
""
] |
How do I programmatically find out the width and height of the video in an mpeg-2 transport program stream file?
Edit: I am using C++, but am happy for examples in any language.
Edit: Corrected question - it was probably program streams I was asking about | Check out the source code to [libmpeg2](http://libmpeg2.sourceforge.net/), a F/OSS MPEG2 decoder. It appears that the width and height are set in the `mpeg2_header_sequence()` function in `header.c`. I'm not sure how control flows to that particular function, though. I'd suggest opening up an MPEG2 file in something using libmpeg2 (such as [MPlayer](http://www.mplayerhq.hu)) and attaching a debugger to see more closely exactly what it's doing. | If you are using DirectX, there is a method in the VMRWindowlessControl interface:
```
piwc->GetNativeVideoSize(&w, &h, NULL, NULL);
```
Or the IBasicVideo interface:
```
pivb->GetVideoSize(&w, &h);
``` | How to determine video dimensions of an mpeg-2 program stream file | [
"",
"c++",
"video",
"mpeg-2",
"transport-stream",
""
] |
Generally, I like to keep an application completely ignorant of the IoC container. However I have ran into problems where I needed to access it. To abstract away the pain I use a basic Singleton. Before you run for the hills or pull out the shotgun, let me go over my solution. Basically, the IoC singleton does absolutly nothing, it simply delegates to an internal interface that must be passed in. I've found this makes working with the Singleton less painful.
Below is the IoC wrapper:
```
public static class IoC
{
private static IDependencyResolver inner;
public static void InitWith(IDependencyResolver container)
{
inner = container;
}
/// <exception cref="InvalidOperationException">Container has not been initialized. Please supply an instance if IWindsorContainer.</exception>
public static T Resolve<T>()
{
if ( inner == null)
throw new InvalidOperationException("Container has not been initialized. Please supply an instance if IWindsorContainer.");
return inner.Resolve<T>();
}
public static T[] ResolveAll<T>()
{
return inner.ResolveAll<T>();
}
}
```
IDependencyResolver:
```
public interface IDependencyResolver
{
T Resolve<T>();
T[] ResolveAll<T>();
}
```
I've had great success so far with the few times I've used it (maybe once every few projects, I really prefer not having to use this at all) as I can inject anything I want: Castle, a Stub, fakes, etc.
Is this a slippery road? Am I going to run into potential issues down the road? | I've seen that even Ayende implements this pattern in the Rhino Commons code, but I'd advise against using it wherever possible. There's a reason Castle Windsor doesn't have this code by default. StructureMap does, but Jeremy Miller has been moving away from it. Ideally, you should regard the container itself with as much suspicion as any global variable.
However, as an alternative, you could always configure your container to resolve IDependencyResolver as a reference to your container. This may sound crazy, but it's significantly more flexible. Just remember the rule of thumb that an object should call "new" or perform processing, but not both. For "call new" replace with "resolve a reference". | That's not really a singleton class. That's a static class with static members. And yes that seems a good approach.
I think JP Boodhoo even has a name for this pattern. [The Static Gateway pattern](http://codebetter.com/jpboodhoo/2007/10/15/the-static-gateway-pattern). | Abstracting IoC Container Behind a Singleton - Doing it wrong? | [
"",
"c#",
"singleton",
"inversion-of-control",
""
] |
I would like to do something like this: a rotating cube on a form. I don't want to use any external library or dll, just pure .NET 3.5 (without directx). And a cube build with lines only. Could you please tell me how to do this?
I don't want to use external libraries because I don't need > 100 MB library to do this thing right? I want only to animate a rotating cube made with lines. | This is how you go about making a Cube in GDI+
C# 3D Drawing with GDI+ Euler Rotation
<http://www.vcskicks.com/3d-graphics-improved.html>
C# 3D-Drawing Cube with Shading
<http://www.vcskicks.com/3d_gdiplus_drawing.html> | Study assignment? This can be done with some simple 3D maths. You just need to understand the basics of matrix algebra, 3D transformations, and 3D->2D view transformation. The [DirectX tutorial](http://msdn.microsoft.com/en-us/library/bb172485.aspx) covers this, but you can google for it and you'll get plenty of other tutorials.
**Added:** Just to clarify - I'm not suggesting to use DirectX or anything. You can do this with standard System.Drawing tools. You just need to understand the math, and that's explained in the DirectX tutorials. | How to animate rotating cube in C#? | [
"",
"c#",
"animation",
"3d",
"cube",
""
] |
Does anyone know of an accurate source for an (E)BNF for the Java language? Preferably, it would be from an authorative source, e.g. Sun.
Thanks. | [First google result :)](http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html)
Though I can't speak for how up-to-date it might be. | i believe the 3rd edition is the latest:
[JLS 3rd edition](http://java.sun.com/docs/books/jls/third_edition/html/syntax.html) | Java EBNF? | [
"",
"java",
"bnf",
"ebnf",
""
] |
In what situations should one catch `java.lang.Error` on an application? | Generally, never.
However, sometimes you need to catch specific errors.
If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch `LinkageError` (no class def found, unsatisfied link, incompatible class change).
I've also seen some stupid 3rd-party code throwing subclasses of `Error`, so you'll have to handle those as well.
By the way, I'm not sure it isn't possible to recover from `OutOfMemoryError`. | Never. You can never be sure that the application is able to execute the next line of code. If you get an `OutOfMemoryError`, you have [no guarantee that you will be able to do anything reliably](https://stackoverflow.com/a/8729011/545127). Catch RuntimeException and checked Exceptions, but never Errors.
<http://pmd.sourceforge.net/rules/strictexception.html> | When to catch java.lang.Error? | [
"",
"java",
"error-handling",
"exception",
""
] |
How do type casting happen without loss of data inside the compiler?
For example:
```
int i = 10;
UINT k = (UINT) k;
float fl = 10.123;
UINT ufl = (UINT) fl; // data loss here?
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p;
```
How does the compiler handle this type of typecasting? A low-level example showing the bits would be highly appreciated. | Well, first note that a cast is an *explicit request to convert a value of one type to a value of another type*. A cast will also always produce a new object, which is a temporary returned by the cast operator. Casting to a reference type, however, will not create a new object. The object referenced by the value is reinterpreted as a reference of a different type.
Now to your question. Note that there are two major types of conversions:
* *Promotions*: This type can be thought of casting from a possibly more narrow type to a wider type. Casting from char to int, short to int, float to double are all promotions.
* *Conversions*: These allow casting from long to int, int to unsigned int and so forth. They can in principle cause loss of information. There are rules for what happens if you assign a `-1` to an unsigned typed object for example. In some cases, a wrong conversion can result in undefined behavior. If you assign a double larger than what a float can store to a float, the behavior is not defined.
Let's look at your casts:
```
int i = 10;
unsigned int k = (unsigned int) i; // :1
float fl = 10.123;
unsigned int ufl = (unsigned int) fl; // :2
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p; // :3
```
1. This cast causes a conversion to happen. No loss of data happens, since 10 is guaranteed to be stored by an `unsigned int`. If the integer were negative, the value would basically wrap around the maximal value of an unsigned int (see **4.7/2**).
2. The value `10.123` is truncated to 10. Here, it *does* cause lost of information, obviously. As 10 fits into an unsigned int, the behavior is defined.
3. This actually requires more attention. First, there is a deprecated conversion from a string literal to `char*`. But let's ignore that here. (see [here](https://stackoverflow.com/questions/308279/c-vs#308724)). More importantly, what does happen if you cast to an unsigned type? Actually, the result of that is unspecified per **5.2.10/7** (note the semantics of that cast is the same as using reinterpret\_cast in this case, since that is the only C++ cast being able to do that):
> A pointer to an object can be explicitly converted to a pointer to
> an object of different type. Except that converting an rvalue of type “pointer to T1” to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.
So you are only safe to use the pointer after you cast back to `char *` again. | The two C-style casts in your example are different kinds of cast. In C++, you'd normally write them
```
unsigned int uf1 = static_cast<unsigned int>(fl);
```
and
```
unsigned char* up = reinterpret_cast<unsigned char*>(p);
```
The first performs an arithmetic cast, which truncates the floating point number, so there is data loss.
The second makes no changes to data - it just instructs the compiler to treat the pointer as a different type. Care needs to be taken with this kind of cast: it can be very dangerous. | How do C/C++ compilers handle type casting between types with different value ranges? | [
"",
"c++",
"c",
"types",
"casting",
"compiler-construction",
""
] |
I'm new to regular expressions and would appreciate your help. I'm trying to put together an expression that will split the example string using all spaces that are not surrounded by single or double quotes. My last attempt looks like this: `(?!")` and isn't quite working. It's splitting on the space before the quote.
Example input:
```
This is a string that "will be" highlighted when your 'regular expression' matches something.
```
Desired output:
```
This
is
a
string
that
will be
highlighted
when
your
regular expression
matches
something.
```
Note that `"will be"` and `'regular expression'` retain the space between the words. | I don't understand why all the others are proposing such complex regular expressions or such long code. Essentially, you want to grab two kinds of things from your string: sequences of characters that aren't spaces or quotes, and sequences of characters that begin and end with a quote, with no quotes in between, for two kinds of quotes. You can easily match those things with this regular expression:
```
[^\s"']+|"([^"]*)"|'([^']*)'
```
I added the capturing groups because you don't want the quotes in the list.
This Java code builds the list, adding the capturing group if it matched to exclude the quotes, and adding the overall regex match if the capturing group didn't match (an unquoted word was matched).
```
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}
}
```
If you don't mind having the quotes in the returned list, you can use much simpler code:
```
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
``` | There are several questions on StackOverflow that cover this same question in various contexts using regular expressions. For instance:
* [parsings strings: extracting words and phrases](https://stackoverflow.com/questions/64904/)
* [Best way to parse Space Separated Text](https://stackoverflow.com/questions/54866/)
**UPDATE**: Sample regex to handle single and double quoted strings. Ref: [How can I split on a string except when inside quotes?](http://www.perlmonks.org/?node_id=29461)
```
m/('.*?'|".*?"|\S+)/g
```
Tested this with a quick Perl snippet and the output was as reproduced below. Also works for empty strings or whitespace-only strings if they are between quotes (not sure if that's desired or not).
```
This
is
a
string
that
"will be"
highlighted
when
your
'regular expression'
matches
something.
```
Note that this does include the quote characters themselves in the matched values, though you can remove that with a string replace, or modify the regex to not include them. I'll leave that as an exercise for the reader or another poster for now, as 2am is way too late to be messing with regular expressions anymore ;) | Regex for splitting a string using space when not surrounded by single or double quotes | [
"",
"java",
"regex",
"split",
""
] |
Here are the specs that I'm trying to implement in a nutshell:
1) Some Alerts have to be sent on certain events in the application.
2) These Alerts have Users subscribe to them.
3) And the Users have set their own Notification preferences (e.g. Email and/or SMS).
I have not been able to find an open source solution in Java so far.
Is JMX Notifications an option? The more I read about JMX, the more I feel that it is trying to achieve something different that my problem.
Any help would be useful. | JMX can be a mechanism to solve this problem, but it's not the complete solution.
JMX provides facilities and services to your programs to allow clients to access monitoring data as well as allowing clients to make control calls to the application.
As you mentioned, one aspect of JMX is the notification system. What this system provides is infrastructure to make it easy for your program to make alerts and notifications available to clients, and modern JVMs also provide a free JMX server to allow client to connect to your application remotely and subscribe to those events.
But its one thing to make a JMX alert, and it's another thing completely to act on it.
What you would need to do is have some JMX client, somewhere, "subscribe" to the JMX notifications of your programs, and then THAT client can act upon those notification by sending emails, or whatever.
The JMX client can be a remote client talking to your application via TCP, or it can be an internal JMX client within the program, running in a thread, say, and it can act on the notifications.
So, basically, JMX provides the plumbing and infrastructure for what you want to do, but doesn't take it "the last mile" to converting alerts in to emails.
As @fawce mentioned, there are some "generic" JMX clients of various sophistication that can act upon JMX data and may do what you want (I'm not familiar with them, so I can not say first hand), or you can code your own system to monitor the JMX data. | There is an article with sample code for using JMX in your app to raise alerts: [Delivering notification with JMX](https://www.zdnet.com/article/delivering-notification-with-jmx/ "delivering-notification-with-jmx").
Once you have that working with local monitoring, you need to set these properties when executing your program:
```
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
```
.. so that you can connect from a remote machine using `jconsole` or other tool with JMX capabilities.
[JManage](https://sourceforge.net/projects/jmanage/ "jmanage") is one of many programs to monitor JMX-enabled Java processes capable of:
* plotting webpages of moving graphs
* emitting e-mails when thresholds change
* remote control
You can easily upgrade to something more complex, such as ***Nagios*** or another commercial tool. Those tools have workflows, roles and other features suitable for big teams - which might be a distraction if you just starting out with getting the Java side of JMX working. | Can we use JMX for Alerts/Notification | [
"",
"java",
"notifications",
"jmx",
"alerts",
""
] |
A lot of programs log things into a text file in a format something like this:
11/19/2008 13:29:01 DEBUG Opening connection to localhost.
11/19/2008 13:29:01 DEBUG Sending login message for user 'ADMIN'.
11/19/2008 13:29:03 DEBUG Received login response 'OK' for user 'ADMIN'.
...
However, I prefer something more structured like XML so I can parse the logs more easily. I've been doing this in my VB6 / Asp Classic programs for years and I want to do it in .Net now. **Is there anything out there that will do this already or should I just re-write my VB6 code in C#?**
Here is how a call to my logging component looks for my VB6 programs:
```
Trace.Warn "MMain", "Main(command, other data)", "Deprecated command", _
sCommandName, sOtherData
```
resulting in the following log entry:
```
<Info time="11/17/2008 04:49:45 PM" mod="MMain" proc="Main" entry="Deprecated command" command="The_Bad_Command" other_data="The other data." />
```
When I want to open the log with my custom log viewer, I simply wrap the whole file in a root node, and then I can easily do this using MSXML to filter the entries that I'm seeing, find a specific user's login, etc. etc...
```
<Log>
...the log file text...
</Log>
``` | I'm not sure of any products that do that, but you could use [log4net](http://www.ondotnet.com/pub/a/dotnet/2003/06/16/log4net.html) and write your own [appender](http://logging.apache.org/log4net/release/features.html) (output handler). | Enteprise library Logging block provides different loggings formats such as xml but it is a long way to configure and deal with it | Logging component that produces xml logs | [
"",
"c#",
".net",
"xml",
"logging",
""
] |
I am writing a set of database-driven applications in PHP. These applications will run on a Linux server as its own user. Other users will likely be on the system at times, but have very controlled access. Other servers they will not have access to at all. I will also expose a limit stored procedure API to developers who need to write Perl scripts that access the database using a DBI and a set of functions I write.
My question is what the best way to secure the config files that have connection strings in them?
Is a different user with [4+]00 permissions on the file sufficient? Should I encrypt them? That seems to just shift the problem elsewhere so that I worry about where to store an encryption key. I realize the Perl developers will need to have a connection string of their own as they will only have execute database permissions. | If the machine really is being administered in the traditional Unix fashion, where J. Random user isn't off su-ing to root all the time, I'd say that filesystem permissions are your best bet. If someone gets unauthorized root access, no amount of encryption silliness is going to "secure" the connection string.
I'd mark the files w/ the connection string as owned by the "script user" and give them access as you describe.
(Bravo for realizing that encrypting the connection string doesn't buy you anything, in this example. Security through obscurity is counter-productive.) | Here's a link to a free Apache module that helps to manage access to a password store:
<http://uranus.it.swin.edu.au/~jn/linux/php/passwords.htm>
It seems a little elaborate to me, and requires you run PHP under mod\_php. And still it doesn't address the possibility that unauthorized people who have access to the server can just read your password file.
I think you have to rely on file permissions, and trust that unauthorized people don't have the ability to `sudo` to your PHP application UID, or to root. | What's best way to secure a database connection string? | [
"",
"php",
"database",
"linux",
"security",
"connection-string",
""
] |
Ought I to unit test constructors? Say I have a constructor like this:
```
IMapinfoWrapper wrapper;
public SystemInfo(IMapinfoWrapper mapinfoWrapper)
{
this.wrapper = mapinfoWrapper;
}
```
Do I need to write a unit test for this construtor? I don't have any getters for the wrapper variable, so I don't need to test that. | Unit testing is about testing the public states, behaviors, and interactions of your objects.
If you simply set a private field in your constructor, what is there to test?
Don't bother unit-testing your simple accessors and mutators. That's just silly, and it doesn't help anyone. | Yes. If you have logic in your constructor, you should test it. Simply setting properties is not logic IMO. Conditionals, control flow, etc IS logic.
**Edit:**
You should probably test for when IMapinfoWrapper is null, if that dependency is required. If so, then that is logic and you should have a test that catches your ArgumentNullException or whatever... your tests are specifications that define how the code behaves. If it throws an ArgumentNullException, then that should be specified in a test. | Is it important to unit test a constructor? | [
"",
"c#",
".net",
"unit-testing",
"constructor",
""
] |
Is it possible to send messages from a PHP script to the console in Eclipse? Has anyone attempted this already? I'm not very familiar with how the console works, so I'm not sure if there is a standardized method for communicating with it. | If you look at...
Main Menu -> Run -> External Tools -> Open External Tools Dialog.
In there I have set up PHP Codesniffer with the following...
* Name : Code Sniffer
* Location : /usr/bin/phpcs
* Working Directory : ${workspace\_loc}
* Arguments : --standard=${resource\_loc}
That runs the codesniffer as an external tool and all the messages it returns appear in the console. Once you have set it up, click the down arrow and choose "Code Sniffer" and then anything the external program (in this case codesniffer) outputs will be in the Eclipse console.
If you set it up like this...
* Name : PHP
* Location : /usr/bin/phpcs
* Working Directory : ${workspace\_loc}
* Arguments : ${workspace\_loc}${resource\_path}
It will just run php in CLI mode and if you run it with Wilco's code (above) you will get.
```
Hello World
```
In the terminal.
Hope that helps. | Any echo or print you do should go to the console automatically. This has been very unreliable for a long time, however. Please vote to have this bug fixed at:
<https://bugs.eclipse.org/bugs/show_bug.cgi?id=282997> | PHP: Messaging/Logging to Eclipse Console? | [
"",
"php",
"eclipse",
"logging",
"console",
""
] |
I need to store of 100-200 data in mysql, the data which would be separated by pipes..
any idea how to store it on mysql? should I use a single column or should I make many multiple columns? I don't know exactly how many data users will input.
I made a form, it halted at the part where multiple data needs to be stored.
Anyone know how to store multiple data in single column or is there any alternative way?
please help me..
thank you very much | You should implement your table with an ID for the source of the data. This ID will be used to group all those pieces of similar data so you don't need to know how many you have beforehand.
Your table columns and data could be set up like this:
```
sourceID data
-------- ----
1 100
1 200
1 300
2 100
3 100
3 200
```
When you query the database, you can just pull in all of the data with the same sourceID. With the data above, the following query would return two pieces of data.
```
SELECT data
FROM dataTable
WHERE sourceID = 3
```
If you have multiple tables, you'll need to associate them with each other using `JOIN` syntax. Say you have a main table with user data and you want to associate all of this input data with each user.
```
userID userName otherData
------ -------- ---------
1 Bob xyz
2 Jim abc
3 Sue lmnop
```
If you want to join data from this table (userTable) with data from the dataTable, use a query like this:
```
SELECT userID, userName, data, otherData
FROM userTable
LEFT JOIN dataTable
ON userTable.userID = dataTable.sourceID
WHERE userTable.userID = 1
```
This query will give you all of the data for the user with an ID of 1. This assumes that the sourceID in your data table is using the userID from the user table to keep track of who the extra data belongs to.
Note that this is not the only JOIN syntax in SQL. You can learn about other types of joins [here](http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php). | If you have a form where this data is coming from, store each input from your form into it's own separate column.
Look for relationships in your data: sounds like you have a "has many" relationship which indicates you may want a linking table where you could do a simple join query...
Storing multiple data in a single column will be a nightmare for queries and updates, unless you're storing XML, event then it would give me nightmares... | PHP MYSQL - Many data in one column | [
"",
"php",
"mysql",
"database-design",
""
] |
is it possible to create something like [this](https://web.archive.org/web/20200805044711/http://geekswithblogs.net/AzamSharp/archive/2008/02/24/119946.aspx) i ASP.NET MVC beta 1
i have tried but the
```
override bool OnPreAction(string actionName,
System.Reflection.MethodInfo methodInfo)
```
does not exsist anymore and
```
override void OnActionExecuting(ActionExecutingContext filterContext)
```
don't give me access to the action name | In the blogpost you are referring to, the author states that
> One way to solve this problem is by using the attribute based security as shown on this post. But then you will have to decorate your actions with the security attribute which is not a good idea.
I think it's a perfectly fine way to go about it and it is supported by the framework. It will give you a nice declarative implementation. Check out the AuthorizeAttribute in System.Web.Mvc. It will allow you to do something like this:
```
[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
(...)
}
```
Since the Delete action alters the state of your system, I would also add an AcceptVerbs attribute like so:
```
[AcceptVerbs(HttpVerbs.Post)]
[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
(...)
}
```
This will make sure that the action will not accept GET requests. | [Create a custom attribute](http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/) | ASP.NET MVC Authenticate | [
"",
"c#",
"asp.net-mvc",
".net-3.5",
"c#-3.0",
""
] |
I have the following values being returned in a column.. 0.250000 and 13.000000. I'd like to round the 0.250000 up to 1 and leave the 13 as is. Any easy way to do this since they both fall within the same column? | Your DBMS probably has a CEILING function. Try that. | The ceiling function will work well because you want to round to the nearest whole number. For more methods on rounding with SQL Server....
[SQL Server Rounding Methods](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-server-rounding-methods) | SQL Rounding Question | [
"",
"sql",
"rounding",
""
] |
Is is possible to have a local variable in an anonymous c# methods, i.e. in the following code I would like to perform the count only once.
```
IQueryable<Enquiry> linq = db.Enquiries;
if(...) linq = linq.Where(...);
if(...) linq = linq.Where(e =>
(x <= (from p in db.Orders where p.EnquiryId == e.Id select p).Count() &&
(from p in db.Orders where p.EnquiryId == e.Id select p).Count() <= y));
if(...) linq = linq.Where(...);
var result = (from e in linq select e);
```
Is there a "let" for anonymous functions?
Update:
Note that I'm adding several Where clauses after this statement so I can't close with a select.
/Niels | I've run into a similar problem. The solution is to create a custom expression tree generating method.
I asked my question on MSDN-forums. Please see the question and answer here: [Reusing Where expressions](http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/7256f2a6-71e2-40f5-9235-1bf71032f8b6/ "Reusing Where expressions").
This may give you an idea on how to proceed, but I must admit that custom expression trees are not for the faint-hearted ;-) | Yes, why not?! After all it's a function, just anonymous!
Example:
```
x => { int y = x + 1; return x + y; }
```
Or alternatively:
```
delegate(int x) {
int y = x + 1;
return x + y;
}
```
So your code can be written as:
```
... = linq.Where(e => {
var count = (from p in db.Orders where p.EnquiryId == e.Id select p).Count();
return x <= count && count <= y;
});
```
UPDATE: To clarify things about the comment, it's important to know the difference between anonymous methods and lambda expressions. An anonymous method is just like a normal method, without an explicit name. When you compile it, the compiler generates a normal method with a weird name for you instead, so it will not have any special limitations. However, one representation of an anonymous method is a lambda expression. Lambda expressions can be interpreted in a couple different ways. The first is a delegate. In that way, they are equal to an anonymous method. The second is an expression tree. This way is normally used by LINQ to SQL and some other LINQ providers. They don't execute your expression directly by any means. They parse it as an expression tree and use the tree as input data to generate the equivalent SQL statement to be run on the server. It's not executed like a method and it's not considered an anonymous method. In that case, you can't define a local variable as it's not possible to parse the lambda as an expression tree. | C#: Is it possible to declare a local variable in an anonymous method? | [
"",
"c#",
"linq-to-sql",
"lambda",
"anonymous-methods",
""
] |
I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255. | You probably want the [inet\_pton](http://man7.org/linux/man-pages/man3/inet_pton.3.html), which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard 32-bit hex number is a valid IP address. Not all IPv4 addresses are in dotted-decimal notation.
This function both verifies the address, and also allows you to use the same address in related socket calls. | [Boost.Asio](http://www.boost.org/doc/libs/release/doc/html/boost_asio.html) provides the class [ip::address](http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/ip__address.html). If you just want to verify the string, you can use it like this:
```
std::string ipAddress = "127.0.0.1";
boost::system::error_code ec;
boost::asio::ip::address::from_string( ipAddress, ec );
if ( ec )
std::cerr << ec.message( ) << std::endl;
```
This also works for hexadecimal and octal quads. This is also a much more portable solution. | How do you validate that a string is a valid IPv4 address in C++? | [
"",
"c++",
"string",
""
] |
Whilst trawling through some old code I came across something similar to the following:
```
class Base
{
public:
virtual int Func();
...
};
class Derived : public Base
{
public:
int Func(); // Missing 'virtual' qualifier
...
};
```
The code compiles fine (MS VS2008) with no warnings (level 4) and it works as expected - `Func` is virtual even though the virtual qualifier is missing in the derived class. Now, other than causing some confusion, are there any dangers with this code or should I change it all, adding the `virtual` qualifier? | The `virtual` will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that `Func` is virtual.
Even classes that extend Derived will have virtual Func methods.
Reference: [Virtual Functions](http://msdn.microsoft.com/en-us/library/0y01k918.aspx) on MSDN. Scroll down the page to see
> The **virtual** keyword can be used when
> declaring overriding functions in a
> derived class, but it is unnecessary;
> overrides of virtual functions are
> always virtual. | Here's an interesting consequence of not needing to declare overriding functions virtual:
```
template <typename Base>
struct Derived : Base
{
void f();
};
```
Whether Derived's f will be virtual depends on whether Derived is instantiated with a Base with a virtual function f of the right signature. | Missing 'virtual' qualifier in function declarations | [
"",
"c++",
"inheritance",
"virtual",
""
] |
First, context: I'm trying to create a command-line-based tool (Linux) that
requires login. Accounts on this tool have nothing to do with
system-level accounts -- none of this looks at /etc/passwd.
I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.
Despite not using the system-level password files, using crypt seemed
to be a good practice to use, as opposed to storing passwords in
cleartext. (While crypt is certainly better than storing passwords in
cleartext, I'm open to other ways of doing this.)
My crypt knowledge is based on this:
<https://docs.python.org/2/library/crypt.html>
The documentation seems to ask for something that isn't possible: "it
is recommended to use the full crypted password as salt when checking
for a password."
Huh? If I'm creating the crypted password (as in, when creating a user
record) how can I use the crypted password as a salt? It
doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)
I've tried using the plaintext password as a salt. This does
work, but has two problems; one easily overcome, and one serious:
1) The first two letters of the plaintext password are included in the
crypted password. You can fix this by not writing the first two
characters to the file:
```
user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type)
```
2) By using the plaintext password as the salt, you would seem to be
reducing the amount of entropy in the system. Possibly I'm
misunderstanding the purpose of the salt.
The best practice I've been able to derive is to use the first two
characters from the username as the salt. Would this be appropriate,
or is there something I've missed that makes that a bad move?
My understanding of a salt is that it prevents pre-computing password
hashes from a dictionary. I could use a standard salt for all
passwords (such as my initials, "JS,") but that seems to be less of a
burden for an attacker than using two characters from each user's username. | For the use of the crypt module:
When GENERATING the crypted password, you provide the salt. It might as well be random to increase resistance to brute-forcing, as long as it meets the listed conditions. When CHECKING a password, you should provide the value from getpwname, in case you are on a system that supports larger salt sizes and didn't generate it yourself.
General comments:
If this has nothing to do w/ actual system logins, there is nothing preventing you from using a stronger method than crypt. You could randomly generate N characters of per-user salt, to be combined with the user's password in a SHA-1 hash.
```
string_to_hash = user.stored_salt + entered_password
successful_login = (sha1(string_to_hash) == user.stored_password_hash)
```
UPDATE: While this is far more secure against rainbow tables, the method above still has cryptographic weaknesses. Correct application of an HMAC algorithm can yet further increase your security, but is beyond my realm of expertise. | Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page:
```
char *crypt(const char *key, const char *salt);
key is a user’s typed password.
salt is a two-character string chosen from the set [a–zA–Z0–9./].
This string is used to perturb the algorithm in one of 4096
different ways.
```
Emphasis is on "*two-character* string". Now, if you look at crypt()'s behavior in Python:
```
>>> crypt.crypt("Hello", "World")
'Wo5pEi/H5/mxU'
>>> crypt.crypt("Hello", "ABCDE")
'AB/uOsC7P93EI'
```
you discover that the first two characters of the result always coincide with the first two characters of the original salt, which indeed form the true two-character-salt itself.
That is, the result of crypt() has the form 2char-salt + encrypted-pass.
Hence, there is no difference in the result if instead of passing the two-character-salt or the original many-characters-salt you pass the whole encrypted password.
Note: the set [a–zA–Z0–9./] contains 64 characters, and 64\*64=4096. Here's how *two* characters relate to "*4096* different ways". | Python crypt module -- what's the correct use of salts? | [
"",
"python",
"linux",
"cryptography",
"crypt",
""
] |
I just ran across the following error:
> (.gnu.linkonce.[stuff]): undefined
> reference to [method] [object
> file]:(.gnu.linkonce.[stuff]):
> undefined reference to `typeinfo for
> [classname]'
Why might one get one of these "undefined reference to typeinfo" linker errors?
Can anyone explain what's going on behind the scenes? | One possible reason is because you are declaring a virtual function without defining it.
When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).
An example of defining the virtual function is:
```
virtual void fn() { /* insert code here */ }
```
In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.
The line
```
virtual void fn();
```
declares `fn()` without defining it and will cause the error message you asked about.
It's very similar to the code:
```
extern int i;
int *pi = &i;
```
which states that the integer `i` is declared in another compilation unit which must be resolved at link time (otherwise `pi` can't be set to it's address). | This can also happen when you mix `-fno-rtti` and `-frtti` code. Then you need to ensure that any class, which `type_info` is accessed in the `-frtti` code, have their key method compiled with `-frtti`. Such access can happen when you create an object of the class, use `dynamic_cast` etc.
[[source](http://web.archive.org/web/20100503172629/http://www.pubbs.net/201004/gcc/25970-linker-error-undefined-reference-to-typeinfo-for-a-with-no-rtti-option.html)] | g++ undefined reference to typeinfo | [
"",
"c++",
"linker",
"g++",
""
] |
Our development process is highly automated via a raft of bash and php scripts (including subversion hook scripts.) These scripts do a number of things to integrate with our Bugzilla 3.0 installation.
But the current integration approach is a bunch of SQL calls which update the bugzilla database directly - which obviously has a number of downsides - including making me nervous about upgrading to 3.2 in case the database schema has changed!
For example, to add a comment to a bug, I'm doing an INSERT into the longdescs table.
So my (slightly long-winded) question is:
* should I be using Bugzilla WebServices (and if so, is there any good documentation other than the Bugzilla API docs which aren't getting me up to speed quickly)
* or, should I be using some other Bugzilla API (direct perl calls?) - and, again, is there any decent doco on this?
* or, should I just keep doing what I'm doing (direct SQL calls) because the db doesn't change that much and it "does the job" | According to the Bugzilla WebServices API, some of the features needed (e.g. changing a bug status) are not yet available, so for the time being, direct SQL calls seem the most appropriate option.
The database schema has not changed significantly between version 3.0 and 3.2 so this is a practical way forward. | FYI, in the Bugzilla 3.2 distribution, there is a `contrib/bz_webservice_demo.pl` file whose intent is to "Show how to talk to Bugzilla via XMLRPC". | How can I update Bugzilla bugs from bash and php scripts? | [
"",
"php",
"web-services",
"bash",
"integration",
"bugzilla",
""
] |
I have XML files in a directory that I wish to get over to a webservice on a server that will validate them and return a true/false as to whether they are valid in construct and values etc.
Reason for server side processing is that the validation rules may change from time to time and need to adjust in one place as opposed to all client machines.
What would be the best mechanism to do this?
At the moment am wondering if passing the XMLDocument object from the client to the webservice as a parameter may be the way to go?
Am using .net 3 for this in C# | You might consider using something like a WCF service and streaming the xml up using the GZipStream. I am doing something similar to this and it is working pretty well. | Wouldn't a normal string be enough? It's overkill to serialize / deserialize an entire XDoc instance in my opinion. Of course, you can also zip the entire thing to reduce the size of the requests. | Best approach for passing XML to a webservice? | [
"",
"c#",
"xml",
"web-services",
"xml-serialization",
""
] |
During development (and for debugging) it is very useful to run a Java class' *public static void main(String[] argv)* method directly from inside Eclipse (using the Run As context menu).
Is there a similarily quick way to specify command line parameters for the run?
What I do now is go to the "Run Dialog", click through the various settings to the tab where I can specify VM and program arguments and enter them there.
Too many steps, plus I do not want to mix the more permanent runtime configuration settings with the one-off invokation parameters.
What I want instead is to check a box somewhere (or have a separate menu item "Run as Java application with command line") and then be prompted for the commandline every time (with a nice history). | This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string\_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments. | Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
1. Run your class once as is.
2. Go to `Run -> Run configurations...`
3. From the lefthand list, select your class from the list under `Java Application` or by typing its name to filter box.
4. Select Arguments tab and write your arguments to `Program arguments` box. Just in case it isn't clear, they're whitespace-separated so `"a b c"` (without quotes) would mean you'd pass arguments a, b and c to your program.
5. Run your class again just like in step 1.
I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this. | Invoking Java main method with parameters from Eclipse | [
"",
"java",
"eclipse",
"main-method",
""
] |
I have a Customer class.
```
public class Customer
{
private string _id;
private string _name;
// some more properties follow
```
I am inheriting the EqualityComparer form MyEqualityComparer(of Customer).
This I am intending to use in LINQ queries.
MyEqualityComparer is intended for partial check between two objects.
If the customer.id and customer.name matches I treat the objects the equal.
```
public class MyComparer : System.Collections.Generic.EqualityComparer<Customer>
{
public override bool Equals(Customer x, Customer y)
{
if (x.Id == y.Id && x.Name == y.Name)
return true;
else
return false;
}
public override int GetHashCode(Customer obj)
{
return string.Concat(obj.Id,obj.Name).GetHashCode();
}
}
```
I referred to [generating hashcode](https://stackoverflow.com/questions/16340/how-do-i-generate-a-hashcode-from-a-byte-array-in-c).
I am little unsure about concatenating strings and using that as a hashcode.
Is this safe and sound what I am trying to do ? | See [this question on hashcodes](https://stackoverflow.com/questions/263400) for a pretty simple way to return one hashcode based on multiple fields.
Having said that, I wouldn't derive from `EqualityComparer<T>` myself - I'd just implement `IEqualityComparer<T>` directly. I'm not sure what value `EqualityComparer<T>` is really giving you here, other than also implementing the non-generic `IEqualityComparer`.
A couple more things:
* You should handle nullity in Equals
* Your present Equals code can be simplified to:
```
return x.Id == y.Id && x.Name == y.Name;
```
A fuller implementation of Equals might be:
```
public override bool Equals(Customer x, Customer y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Id == y.Id && x.Name == y.Name;
}
``` | You should see it from the perspective of possible "collisions", e.g. when two different objects get the same hash code. This could be the case with such pairs as "1,2any" and "12, any", the values in the pairs being "id" and "name". If this is not possible with your data, you're good to go. Otherwise you can change it to something like:
```
return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
``` | Inheriting the equality comparer | [
"",
"c#",
".net",
"linq",
""
] |
I'm looking for a library in Python which will provide `at` and `cron` like functionality.
I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.
For those unfamiliar with `cron`: you can schedule tasks based upon an expression like:
```
0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday
0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays.
```
The cron time expression syntax is less important, but I would like to have something with this sort of flexibility.
If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.
**Edit**
I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.
To this end, I'm looking for the expressivity of the cron time expression, but in Python.
Cron *has* been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence. | If you're looking for something lightweight checkout [schedule](https://github.com/dbader/schedule):
```
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while 1:
schedule.run_pending()
time.sleep(1)
```
*Disclosure*: I'm the author of that library. | You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below:
```
from datetime import datetime, timedelta
import time
# Some utility classes / functions first
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item): return True
allMatch = AllMatch()
def conv_to_set(obj): # Allow single integer to be provided
if isinstance(obj, (int,long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
# The actual Event class
class Event(object):
def __init__(self, action, min=allMatch, hour=allMatch,
day=allMatch, month=allMatch, dow=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(min)
self.hours= conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.dow = conv_to_set(dow)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t):
"""Return True if this event should trigger at the specified datetime"""
return ((t.minute in self.mins) and
(t.hour in self.hours) and
(t.day in self.days) and
(t.month in self.months) and
(t.weekday() in self.dow))
def check(self, t):
if self.matchtime(t):
self.action(*self.args, **self.kwargs)
```
(Note: Not thoroughly tested)
Then your CronTab can be specified in normal python syntax as:
```
c = CronTab(
Event(perform_backup, 0, 2, dow=6 ),
Event(purge_temps, 0, range(9,18,2), dow=range(0,5))
)
```
This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months)
The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation:
```
class CronTab(object):
def __init__(self, *events):
self.events = events
def run(self):
t=datetime(*datetime.now().timetuple()[:5])
while 1:
for e in self.events:
e.check(t)
t += timedelta(minutes=1)
while datetime.now() < t:
time.sleep((t - datetime.now()).seconds)
```
A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however. | How do I get a Cron like scheduler in Python? | [
"",
"python",
"cron",
"scheduled-tasks",
""
] |
Is it acceptable to add types to the `std` namespace. For example, I want a TCHAR-friendly string, so is the following acceptable?
```
#include <string>
namespace std
{
typedef basic_string<TCHAR> tstring;
}
```
Or should I use my own namespace? | No ... part of the point of a namespace is to prevent name collisions on upgrade.
If you add things to the std namespace, then your code might break with the next release of the library if they decide to add something with the same name. | Only specializations are allowed. So for example, you are allowed to specialize `std::numeric_limits` for your type. And this of course must happen in namespace `std::`. But your typedef isn't a specialization so that's causing undefined behavior. | Adding types to the std namespace | [
"",
"c++",
"stl",
"namespaces",
""
] |
I wrote a program out, which was all in one file, and the methods were forward declared in a header. The program initially worked perfectly when it was in one file. But when I separated the program, I kept getting random occurrences for the destructor of one of the classes which was declared in the header file.
I have a static variable in my header to count the number of objects of a particular class. Whenever I construct the object I increment this variable. Then in my destructor I subtract 1 from that variable, check if it's 0 (meaning it's the last object) and do something. The value seems to be off sometimes, I'm not sure why. I do have random calls in my application but I don't see why that would effect what I have described above, thanks. Any help or insight is appreciated!
[Update]: have a base class, which contains the destructor.. which is implemented in the header, then I have two derived classes, which in their constructor increment the static var.. so what can I do?
What I am trying to do is the following: In my header I have this:
```
class A {
public:
virtual ~A() {
count --;
if (count == 0) { /* this is the last one, do something */ }
}
class B : public A {
public:
B();
}
```
Then in Class B I have
```
B::B() {
count++;
}
```
Where can I define count so I don't get misleading counts? Thanks. | ```
class A {
public:
virtual ~A() {
count --;
if (count == 0) { // this is the last one, do something }
}
protected:
static int count;
};
class B : public A{
public:
B();
};
```
And then, in one and only one of your source files you need to put the following. It should go in the source file that contains the code for class A.
```
int A::count(0);
```
You need to do this, because the header file declared that there was going to be a variable named count, but didn't allocate any storage for it. If you didn't put it in a source file, the linker would complain that it wasn't found. | You must define the constructor in A (all of them) to increment the count.
Note unless you define them the compiler automatically generate the following four methods:
* Default Constructor (if no other constructor is defined)
* Default Destructor
* Copy Constructor
* Assignment operator
The following code overrides the compiler defaults so that you should get an accurate count.
```
class A
{
static int count;
public:
A() // Default constructor.
{
++count;
}
A(A const& copy) // Copy constructor/
{ // Note If you do not define it the compiler
++count; // will automatically do it for you
}
virtual ~A()
{
--count;
if (count == 0)
{ // PLOP
}
}
// A& operator=(A const& copy)
// do not need to override this as object has
// already been created and accounted for.
};
```
////
In source file:
```
int A::count = 0;
``` | Static Variables, Separate Compilation | [
"",
"c++",
"file",
"variables",
"static",
""
] |
I am loading JSON data to my page and using `appendTo()` but I am trying to fade in my results, any ideas?
```
$("#posts").fadeIn();
$(content).appendTo("#posts");
```
I saw that there is a difference between `append` and `appendTo`, on the documents.
I tried this as well:
```
$("#posts").append(content).fadeIn();
```
***I got it, the above did the trick!***
But I get `"undefined"` as one of my JSON values. | If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
```
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
.hide()
// Appends the hidden elements to the "posts" element
.appendTo('#posts')
// Fades the new content into view
.fadeIn();
``` | I don't know if I fully understand the issue you're having, but something like this should work:
HTML:
```
<div id="posts">
<span id="post1">Something here</span>
</div>
```
Javascript:
```
var counter=0;
$.get("http://www.something/dir",
function(data){
$('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>" ) ;
$('#post' + counter).fadeIn();
counter += 1;
});
```
Basically you're wrapping each piece of the content (each "post") in a span, setting that span's display to none so it doesn't show up, and then fading it in. | Using fadein and append | [
"",
"javascript",
"jquery",
"fade",
""
] |
I'm trying to learn about Expression trees, and I've created a method that takes an
```
Expression<Func<bool>>
```
and executes it if it satisfies some conditions - see the code below.
```
private static void TryCommand(Expression<Func<bool>> expression)
{
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
{
throw new ArgumentException("expression must be a MethodCallExpression.");
}
if (methodCallExpression.Object.Type != typeof (MyClass))
{
throw new ArgumentException("expression must be operating on an instanceof MyClass.");
}
var func = expression.Compile();
var success = func.Invoke();
if(!success)
{
Console.WriteLine(methodCallExpression.Method.Name + "() failed with error code " + (func.Target as MyClass).GetError());
}
}
```
The problem that
```
(func.Target as MyClass)
```
is null. Clearly I'm doing something wrong! How do I access the instance that the method is operating on? | The target of the method call is an instance of MyClass, but the delegate itself isn't the method call. It's something which will perform the method call when it's executed.
If you look at func.Target, you'll see it's a [System.Runtime.CompilerServices.ExecutionScope](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.executionscope.aspx).
Now you *could* test for that, cast to it, and then fetch either the Locals or the Globals (not sure which) to get the target. However, I suspect it would be cleaner just to change to use a `Func<int>` (or whatever type your error code is) and return the error code when you execute the delegate in the first place. Then you wouldn't even need an expression tree.
EDIT: Given your comments, I'd suggest:
```
public static void TryCommand(Expression<Func<MyClass,bool>> command,
MyClass c)
{
// Code as before to find the method name etc.
Func<MyClass, bool> compiled = command.Compile();
if (!compiled(c))
{
Console.WriteLine(methodCallExpression.Method.Name
+ "() failed with error code " + c.GetError());
}
}
```
You'd then call it with:
```
TryCommand(x => x.SomeMethod(), myClass);
``` | Akash, once you have a MethodCallExpression it's simple to recover the method caller.
You must recover the MemberExpression and build an Expression tree that evaluates it.
See the code below:
```
MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
MemberExpression memberExpression = (MemberExpression)methodCallExpression.Object;
Expression<Func<Object>> getCallerExpression = Expression<Func<Object>>.Lambda<Func<Object>>(memberExpression);
Func<Object> getCaller = getCallerExpression.Compile();
MyClass caller = (MyClass)getCaller();
```
Hope this helps,
Ricardo Lacerda Castelo Branco | Accessing calling object from MethodCallExpression | [
"",
"c#",
""
] |
If both get and set are compulsory in C# automatic properties, why do I have to bother specifying "get; set;" at all? | **ERROR: A property or indexer may not be passed as an out or ref parameter**
If you didn't specify `{get; set;}` then the compiler wouldn't know if it's a field or a property.
This is important becasue while they "look" identical the compiler treats them differently. e.g. Calling "InitAnInt" on the property raises an error.
```
class Test
{
public int n;
public int i { get; set; }
public void InitAnInt(out int p)
{
p = 100;
}
public Test()
{
InitAnInt(out n); // This is OK
InitAnInt(out i); // ERROR: A property or indexer may not be passed
// as an out or ref parameter
}
}
```
You shouldn't create public fields/Variables on classes, you never know when you'll want to change it to have get & set accessors, and then you don't know what code you're going to break, especially if you have clients that program against your API.
Also you can have different access modifiers for the get & set, e.g. {get; **private** set;} makes the get public and the the set private to the declaring class. | Because you might want a read-only property:
```
public int Foo { get; private set; }
```
Or Write-only property:
```
public int Foo { private get; set; }
``` | C# Automatic Properties - Why Do I Have To Write "get; set;"? | [
"",
"c#",
"c#-3.0",
"automatic-properties",
""
] |
It is advised to use override instead of new key word in C#. Why that rule? | "new" means you've got two completely different methods as far as the CLR is concerned - they happen to have the same name, but they're unrelated in terms of inheritance. That means that if you run:
```
Base b = new Derived();
Derived d = new Derived();
b.MyMethod(); // Calls Base.MyMethod
d.MyMethod(); // Calls Derived.MyMethod
```
This can make for some very hard-to-understand code.
Usually if you want different methods, call them different things. The normal reason to use the same name (and signature) is to override the behaviour of a base class's method. At that point you don't have any choice but to keep the name/signature the same. | I'm still trying to work out what the use case is for "new" aside from horrid hackery. | How to chose between new and override in C#? | [
"",
"c#",
""
] |
I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place.
Is this ok:
```
public class Icons {
public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}
```
Or should I be doing this a different way? I don't mind relying on the existence of the image files at runtime since they're in the .jar
**Solution**
I've used Bent's idea for initialisation, and I've made the constants final:
```
public final class Icons {
private static final Logger logger = Logger.getLogger(Icons.class);
public static final Icon OK = icon("/icons/add.png");
public static final Icon CANCEL = icon("/icons/cancel.png");
private static Icon icon(String path) {
URL resource = Icons.class.getResource(path);
if(resource==null) {
logger.error("Resource "+path+" does not exist");
return new ImageIcon();
}
return new ImageIcon(resource);
}
}
``` | If you want to keep you icons as static constants, I would extract the instantiation of the ImageIcon objects into a static method;
```
public static final Icon ok = icon("ok.png");
private static Icon icon(String path) {
URL resource = Icons.class.getResource("/icons/" + path);
if (resource == null) {
// Log something...
return null;
}
return new ImageIcon(resource);
}
```
This way you have control whenever something fail, and you don't have to repeat yourself in the instantiation.
Also, I would make the constants final.
A more general approach could be to use reflection to inspect your Icons-class and load resources for each public static Icon field in the class. This way, you would only have to declare a new Icon constant, and the corresponding resource would be loaded automatically based on the name of the constant. Leave a comment if you want more tips for doing this. | I see two problems with that, both might be acceptable:
1. It will get hard to debug if your icons are not found or can't be loaded for some reasons. Code that runs in static initializers can be tricky, because it's easy to "loose" the exception.
2. The class will probably never be unloaded and therefore the resource used by the Icons will never bee freed.
Number 1 is probably acceptable if you can make sure that the icons are always there and can even be worked around by putting the initialization in a static initializer block and adding good exception handling and logging.
Number 2 is probably acceptable since icons are usually used throughout the entire runtime of the application and they wouldn't be freed long before the application quits anyway.
So all in all I'd say that's fine. | Java icon constants - Are static constants ok? | [
"",
"java",
"icons",
"constants",
""
] |
I want to write out a text file.
Instead of the default UTF-8, I want to write it encoded as ISO-8859-1 which is code page 28591. I have no idea how to do this...
I'm writing out my file with the following very simple code:
```
using (StreamWriter sw = File.CreateText(myfilename))
{
sw.WriteLine("my text...");
sw.Close();
}
``` | ```
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
```
An alternate way of getting your encoding:
```
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
```
Check out the docs for the StreamWriter constructor. | Simple!
```
System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
``` | How do I write out a text file in C# with a code page other than UTF-8? | [
"",
"c#",
"encoding",
"utf-8",
"iso-8859-1",
""
] |
The best I can come up with for now is this monstrosity:
```
>>> datetime.utcnow() \
... .replace(tzinfo=pytz.UTC) \
... .astimezone(pytz.timezone("Australia/Melbourne")) \
... .replace(hour=0,minute=0,second=0,microsecond=0) \
... .astimezone(pytz.UTC) \
... .replace(tzinfo=None)
datetime.datetime(2008, 12, 16, 13, 0)
```
I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.
I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.
I can't help feeling I'm missing something, any ideas? | I think you can shave off a few method calls if you do it like this:
```
>>> from datetime import datetime
>>> datetime.now(pytz.timezone("Australia/Melbourne")) \
.replace(hour=0, minute=0, second=0, microsecond=0) \
.astimezone(pytz.utc)
```
BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.
The reason for this is that neither the datetime constructors nor `replace()` take DST changes into account.
For example:
```
>>> now = datetime(2012, 4, 1, 5, 0, 0, 0, tzinfo=pytz.timezone("Australia/Melbourne"))
>>> print now
2012-04-01 05:00:00+10:00
>>> print now.replace(hour=0)
2012-04-01 00:00:00+10:00 # wrong! midnight was at 2012-04-01 00:00:00+11:00
>>> print datetime(2012, 3, 1, 0, 0, 0, 0, tzinfo=tz)
2012-03-01 00:00:00+10:00 # wrong again!
```
However, the documentation for `tz.localize()` states:
> This method should be used to construct localtimes, rather
> than passing a tzinfo argument to a datetime constructor.
Thus, your problem is solved like so:
```
>>> import pytz
>>> from datetime import datetime, date, time
>>> tz = pytz.timezone("Australia/Melbourne")
>>> the_date = date(2012, 4, 1) # use date.today() here
>>> midnight_without_tzinfo = datetime.combine(the_date, time())
>>> print midnight_without_tzinfo
2012-04-01 00:00:00
>>> midnight_with_tzinfo = tz.localize(midnight_without_tzinfo)
>>> print midnight_with_tzinfo
2012-04-01 00:00:00+11:00
>>> print midnight_with_tzinfo.astimezone(pytz.utc)
2012-03-31 13:00:00+00:00
```
No guarantees for dates before 1582, though. | [@hop's answer](https://stackoverflow.com/a/381788/4279) is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it [`tz.localize()`](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic) could be used:
```
tz = pytz.timezone("Australia/Melbourne")
today = datetime.now(tz).date()
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
utc_dt = midnight.astimezone(pytz.utc)
```
The same with comments:
```
#!/usr/bin/env python
from datetime import datetime, time
import pytz # pip instal pytz
tz = pytz.timezone("Australia/Melbourne") # choose timezone
# 1. get correct date for the midnight using given timezone.
today = datetime.now(tz).date()
# 2. get midnight in the correct timezone (taking into account DST)
#NOTE: tzinfo=None and tz.localize()
# assert that there is no dst transition at midnight (`is_dst=None`)
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
# 3. convert to UTC (no need to call `utc.normalize()` due to UTC has no
# DST transitions)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print midnight.astimezone(pytz.utc).strftime(fmt)
``` | How do I get the UTC time of "midnight" for a given timezone? | [
"",
"python",
"datetime",
"timezone",
"utc",
"pytz",
""
] |
If I create a UserControl and add some objects to it, how can I grab the HTML it would render?
ex.
```
UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());
// ...something happens
return strHTMLofControl;
```
I'd like to just convert a newly built UserControl to a string of HTML. | You can render the control using `Control.RenderControl(HtmlTextWriter)`.
Feed `StringWriter` to the `HtmlTextWriter`.
Feed `StringBuilder` to the `StringWriter`.
Your generated string will be inside the `StringBuilder` object.
Here's a code example for this solution:
```
string html = String.Empty;
using (TextWriter myTextWriter = new StringWriter(new StringBuilder()))
{
using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
{
myControl.RenderControl(myWriter);
html = myTextWriter.ToString();
}
}
``` | ```
//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();
``` | How do I get the HTML output of a UserControl in .NET (C#)? | [
"",
"c#",
"html",
".net",
"user-controls",
""
] |
I'm using python and I need to map locations like "Bloomington, IN" to GPS coordinates so I can measure distances between them.
What Geocoding libraries/APIs do you recommend? Solutions in other languages are also welcome. | The Google Maps API [supports geocoding](http://code.google.com/apis/maps/documentation/services.html#Geocoding), and the Python Cookbook has a simple [example](http://code.activestate.com/recipes/498128/) of accessing it from Python (although the recipe doesn't use the API directly, just simple maps.google.com URLs). | [Geopy](http://code.google.com/p/geopy/) lets you choose from several geocoders (including Google, Yahoo, Virtual Earth). | Geocoding libraries | [
"",
"python",
"api",
"rest",
"geocoding",
""
] |
I have a class with two methods defined in it.
```
public class Routines {
public static method1() {
/* set of statements */
}
public static method2() {
/* another set of statements.*/
}
}
```
Now I need to call method1() from method2()
Which one the following approaches is better? Or is this qualify as a question?
```
public static method2() {
method1();
}
```
OR
```
public static method2() {
Routines.method1();
}
``` | While I agree with the existing answers that this is primarily a style issue, it is enough of a style issue that both Eclipse and IntelliJ's code critics will flag "non-static references to static methods" in code that does not use the `Classname.method()` style.
I made it a habit to emphasize *intent* by using the classname to qualify references to static targets, `this` to qualify references to instance targets, and bare names for local references. A modern IDE will use different highlighting for these constructs, so I suppose it is less important these days. I like for the maintainer (often myself) to *know* what was intended, that yes, I knew that was a `static` reference.
Yeah, it does make for slightly more verbose code, but I think it is worth the extra characters. | I'd go with the first method. In my eyes, it's the equivalent of:
```
public void method2()
{
method1();
}
```
and:
```
public void method2()
{
this.method1();
}
```
I don't know many people who explicitly call **this** when calling another method in a class. So personally my taste is option 1 - no need to call ClassName explicitly. | calling method Versus class.method | [
"",
"java",
"coding-style",
""
] |
I'd like to split a string using one or more separator characters.
E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].
At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.
```
def my_split(string, split_chars):
if isinstance(string_L, basestring):
string_L = [string_L]
try:
split_char = split_chars[0]
except IndexError:
return string_L
res = []
for s in string_L:
res.extend(s.split(split_char))
return my_split(res, split_chars[1:])
print my_split("a b.c", [' ', '.'])
```
Horrible! Any better suggestions? | ```
>>> import re
>>> re.split('[ .]', 'a b.c')
['a', 'b', 'c']
``` | This one replaces all of the separators with the first separator in the list, and then "splits" using that character.
```
def split(string, divs):
for d in divs[1:]:
string = string.replace(d, divs[0])
return string.split(divs[0])
```
output:
```
>>> split("a b.c", " .")
['a', 'b', 'c']
>>> split("a b.c", ".")
['a b', 'c']
```
I do like that 're' solution though. | split string on a number of different characters | [
"",
"python",
"string",
"split",
""
] |
I'm trying to do a simple erase and keep getting errors.
Here is the snippet of code for my erase:
```
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--, iterMines++)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = onScreen.erase(iterMines);
iterMines--;
}
}
```
I keep getting a compiler message:
```
1>c:\users\owner\desktop\bosconian\code\bosconian\environment.cpp(158) : error C2664: 'std::list<_Ty>::_Iterator<_Secure_validation> std::list<_Ty>::erase(std::list<_Ty>::_Iterator<_Secure_validation>)' : cannot convert parameter 1 from 'std::list<_Ty>::_Iterator<_Secure_validation>' to 'std::list<_Ty>::_Iterator<_Secure_validation>'
1> with
1> [
1> _Ty=SpaceObject *,
1> _Secure_validation=true
1> ]
1> and
1> [
1> _Ty=Mine *,
1> _Secure_validation=true
1> ]
1> and
1> [
1> _Ty=SpaceObject *,
1> _Secure_validation=true
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
```
I'm puzzled because I believe I'm giving it the correct iterator.
Mine is a subclass of SpaceObject (a second generation subclass that is)
Does this have anything to do with it? And how would I fix it? | The problem is you are trying to use the iterator of mines as an iterator in the onScreen list. This will not work.
Did you mean to call mines.erase(iterMines) instead of onScreen.erase(iterMines)? | ```
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--, iterMines++)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = onScreen.erase(iterMines);
iterMines--;
}
}
```
One real problem, and one possible solution:
`erase` will give you the next iterator after the removed element. So if you are at the beginning, and erase, you will be given the new beginning. If you then decrement the iterator, you decrement before the begin. And this is invalid. Better factor out the `iterMines++` into the body of the loop:
```
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = mines.erase(iterMines); // change to mines!!
} else {
++iterMines; // better to use ++it instead of it++
}
}
```
Better use pre-increment for that since you never know what an iterator does behind the scene when it creates a copy of itself. `++it` will return the new iterator, while `it++` will return a copy of the iterator before the increment. I have commented the part where the possible solution is too :) | Help with C++ List erase function | [
"",
"c++",
"iterator",
""
] |
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?
Scenario:
My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?
Target platform is \*nix, however I would like to do it on a Win host also. | ```
>>> import os
>>> os.times()
(1.296875, 0.765625, 0.0, 0.0, 0.0)
>>> print os.times.__doc__
times() -> (utime, stime, cutime, cstime, elapsed_time)
Return a tuple of floating point numbers indicating process times.
```
From the (2.5) manual:
> times( )
>
> Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows. | By using [psutil](http://code.google.com/p/psutil):
```
>>> import psutil
>>> p = psutil.Process()
>>> p.cpu_times()
cputimes(user=0.06, system=0.03)
>>> p.cpu_percent(interval=1)
0.0
>>>
``` | CPU Usage Per Process in Python | [
"",
"python",
"monitoring",
"cpu-usage",
""
] |
I have an application that has to deal with getting "special" characters in its URL (like &, +, %, etc). When I'm sending a request to the application using these characters (of course I'm sending them escaped) I'm getting "Bad Request" response code with the message "ASP.NET detected invalid characters in the URL". Tracing the request shown me that the error was thrown from the "Authentication Module".
I've searched a bit and found that every page has a ValidateRequest and changing its value to false solves the problem. Unfortunately I'm using Httphandler. Does anyone know how to stop the request validation using http handler? | I ran into the same problem (creating an IHttpHandler that needed to receive requests with special characters in the URL). I had to do two things to fix it:
1. Create the following DWORD registration entry with a value of 1: `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\VerificationCompatibility`
2. In the web.config, set the allowDoubleEscaping attribute of the requestFiltering element to true. | I had the same problem and got it working by setting validateRequest="false" as well as requestValidationMode="2.0", like below. No registry edits.
```
<system.web>
<httpRuntime requestValidationMode="2.0" />
...
<pages ... validateRequest="false" />
</system.web>
``` | Canceling request validation using HttpHandler on IIS 7 | [
"",
"c#",
".net",
"asp.net",
"iis",
"iis-7",
""
] |
I'm using the appengine webapp framework ([link](http://code.google.com/appengine/docs/webapp/)). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work ([link](http://github.com/woid/firepython/tree/master)). | It's easy: You create the WSGI application as per normal, then wrap that application in your WSGI middleware before executing it.
See [this code](http://github.com/Arachnid/bloog/blob/bb777426376d298765d5dee5b88f53964cc6b5f3/main.py#L71) from Bloog to see how firepython is added as middleware. | The GAE webapp framework does not map one to one to the Django framework. It would be hard to do what you want without implementing some kind of adapter yourself, I do not know of any third party handler adapters to do this.
That said, I generally use the app-engine-patch so I can use the latest 1.0.2 Django release with AppEngine, and then you can just include the Django middleware the normal way with the setup.py file. If you needed to, you could probably look through the app-engine-patch's adapter to see how they do it, and start with that as a framework. | How to adding middleware to Appengine's webapp framework? | [
"",
"python",
"django",
"google-app-engine",
"middleware",
"django-middleware",
""
] |
I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently:
```
std::ifstream stream;
stream.open("rules.ini");
if (!stream.is_open())
{
throw new std::exception("Rule file could not be opened");
}
// read file contents here
stream.close();
```
However, my stream never opens succesfully. Diving deep into the STL source during debugging reveals that \_getstream() (as defined in stream.c) keeps on returning NULL, but I just can't figure out why this is. Help, anyone?
Edit: Rules.ini is in the same directory as the .exe file. | You are assuming that the **working directory** is the directory that your executable resides in. That is a bad assumption.
Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software.
If you want to be able to access files relative to the location of your executable, you should first determine the path of your executable and create a fully qualified path from that.
You can get the name of your executable by examining the `argv[0]` parameter passed to `main()`. Alternatively, if you're on Windows, you can get it with [`GetModuleFileName()`](http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx) by passing NULL as the first parameter. | Is the scope of your open stream correct.
"rules.ini" isn't a full path so it has to be relative so what is it relative to. Or do you need to use full path there. | std::ifstream::open() not working | [
"",
"c++",
"stl",
"iostream",
""
] |
Is there any good way to unit test destructors? Like say I have a class like this (contrived) example:
```
class X
{
private:
int *x;
public:
X()
{
x = new int;
}
~X()
{
delete x;
}
int *getX() {return x;}
const int *getX() const {return x;}
};
```
Is there any good way to unit test this to make sure x gets deleted without cluttering up my hpp file with #ifdef TESTs or breaking encapsulation? The main problem that I'm seeing is that it's difficult to tell if x really got deleted, especially because the object is out of scope at the time the destructor is called. | There may be something to be said for dependency injection. Instead of creating an object (in this case an int, but in a non-contrived case more likely a user-defined type) in its constructor, the object is passed as a parameter to the constructor. If the object is created later, then a factory is passed to the constructor of X.
Then when you're unit testing, you pass in a mock object (or a mock factory which creates mock objects), and the destructor records the fact that it has been called. The test fails if it isn't.
Of course you can't mock (or otherwise replace) a builtin type, so in this particular case it's no good, but if you define the object/factory with an interface then you can.
Checking for memory leaks in unit tests can often be done at a higher level, as others have said. But that only checks that *a* destructor was called, it doesn't prove that the *right* destructor was called. So it wouldn't e.g. catch a missing "virtual" declaration on the destructor of the type of the x member (again, not relevant if it's just an int). | I think your problem is that your current example isn't testable. Since you want to know if `x` was deleted, you really need to be able to replace `x` with a mock. This is probably a bit OTT for an int but I guess in your real example you have some other class. To make it testable, the `X` constructor needs to ask for the object implementing the `int` interface:
```
template<class T>
class X
{
T *x;
public:
X(T* inx)
: x(inx)
{
}
// etc
};
```
Now it becomes simple to mock in the value for `x`, and the mock can handle checking for correct destruction.
Please pay no attention to the people who say you should break encapsulation or resort to horrible hacks in order to result in testable code. While it is true that tested code is better than untested code, testable code is the best of all and it always results in clearer code with fewer hacks and lower coupling. | Unit testing destructors? | [
"",
"c++",
"unit-testing",
"destructor",
"cppunit",
""
] |
I have an application which is a relatively old. Through some minor changes, it builds nearly perfectly with Visual C++ 2008. One thing that I've noticed is that my "debug console" isn't quite working right. Basically in the past, I've use `AllocConsole()` to create a console for my debug output to go to. Then I would use `freopen` to redirect `stdout` to it. This worked perfectly with both C and C++ style IO.
Now, it seems that it will only work with C style IO. What is the proper way to redirect things like `cout` to a console allocated with `AllocConsole()`?
Here's the code which used to work:
```
if(AllocConsole()) {
freopen("CONOUT$", "wt", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
```
**EDIT**: one thing which occurred to me is that I could make a custom streambuf whose overflow method writes using C style IO and replace `std::cout`'s default stream buffer with it. But that seems like a cop-out. Is there a proper way to do this in 2008? Or is this perhaps something that MS overlooked?
**EDIT2**: OK, so I've made an implementaiton of the idea I spelled out above. Basically it looks like this:
```
class outbuf : public std::streambuf {
public:
outbuf() {
setp(0, 0);
}
virtual int_type overflow(int_type c = traits_type::eof()) {
return fputc(c, stdout) == EOF ? traits_type::eof() : c;
}
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
// create the console
if(AllocConsole()) {
freopen("CONOUT$", "w", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
// set std::cout to use my custom streambuf
outbuf ob;
std::streambuf *sb = std::cout.rdbuf(&ob);
// do some work here
// make sure to restore the original so we don't get a crash on close!
std::cout.rdbuf(sb);
return 0;
}
```
Anyone have a better/cleaner solution than just forcing `std::cout` to be a glorified `fputc`? | ## Updated Feb 2018:
Here is the latest version of a function which fixes this problem:
```
void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr)
{
// Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been
// observed that the file number of our standard handle file objects can be assigned internally to a value of -2
// when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our
// call to "_dup2" fails, as it specifically tests to ensure that the target file number isn't equal to this value
// before allowing the operation to continue. We can resolve this issue by first "re-opening" the target files to
// use the "nul" device, which will place them into a valid state, after which we can redirect them to our target
// using the "_dup2" function.
if (bindStdIn)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "r", stdin);
}
if (bindStdOut)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "w", stdout);
}
if (bindStdErr)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "w", stderr);
}
// Redirect unbuffered stdin from the current standard input handle
if (bindStdIn)
{
HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "r");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stdin));
if (dup2Result == 0)
{
setvbuf(stdin, NULL, _IONBF, 0);
}
}
}
}
}
// Redirect unbuffered stdout to the current standard output handle
if (bindStdOut)
{
HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "w");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stdout));
if (dup2Result == 0)
{
setvbuf(stdout, NULL, _IONBF, 0);
}
}
}
}
}
// Redirect unbuffered stderr to the current standard error handle
if (bindStdErr)
{
HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "w");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stderr));
if (dup2Result == 0)
{
setvbuf(stderr, NULL, _IONBF, 0);
}
}
}
}
}
// Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the
// standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In
// versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything
// has been read from or written to the targets or not.
if (bindStdIn)
{
std::wcin.clear();
std::cin.clear();
}
if (bindStdOut)
{
std::wcout.clear();
std::cout.clear();
}
if (bindStdErr)
{
std::wcerr.clear();
std::cerr.clear();
}
}
```
In order to define this function, you'll need the following set of includes:
```
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
```
In a nutshell, this function synchronizes the C/C++ runtime standard input/output/error handles with the current standard handles associated with the Win32 process. As mentioned in [the documentation](https://learn.microsoft.com/en-us/windows/console/allocconsole), AllocConsole changes these process handles for us, so all that's required is to call this function after AllocConsole to update the runtime handles, otherwise we'll be left with the handles that were latched when the runtime was initialized. Basic usage is as follows:
```
// Allocate a console window for this process
AllocConsole();
// Update the C/C++ runtime standard input, output, and error targets to use the console window
BindCrtHandlesToStdHandles(true, true, true);
```
This function has gone through several revisions, so check the edits to this answer if you're interested in historical information or alternatives. The current answer is the best solution to this problem however, giving the most flexibility and working on any Visual Studio version. | I'm posting a portable solution in answer form so it can be accepted. Basically I replaced `cout`'s `streambuf` with one that is implemented using c file I/O which does end up being redirected. Thanks to everyone for your input.
```
class outbuf : public std::streambuf {
public:
outbuf() {
setp(0, 0);
}
virtual int_type overflow(int_type c = traits_type::eof()) {
return fputc(c, stdout) == EOF ? traits_type::eof() : c;
}
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
// create the console
if(AllocConsole()) {
freopen("CONOUT$", "w", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
// set std::cout to use my custom streambuf
outbuf ob;
std::streambuf *sb = std::cout.rdbuf(&ob);
// do some work here
// make sure to restore the original so we don't get a crash on close!
std::cout.rdbuf(sb);
return 0;
}
``` | Redirecting cout to a console in windows | [
"",
"c++",
"winapi",
""
] |
How do I set environment variables from Java? I see that I can do this for subprocesses using [`ProcessBuilder`](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html). I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit it.
There's a `System.getenv(String)` for getting a single environment variable. I can also get a `Map` of the complete set of environment variables with `System.getenv()`. But, calling `put()` on that `Map` throws an `UnsupportedOperationException` -- apparently they mean for the environment to be read only. And, there's no `System.setenv()`.
So, is there any way to set environment variables in the currently running process? If so, how? If not, what's the rationale? (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?) And if not, any good suggestions for managing the environment variable changes that I'm going to need to be feeding to several subprocesses? | > (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?)
I think you've hit the nail on the head.
A possible way to ease the burden would be to factor out a method
```
void setUpEnvironment(ProcessBuilder builder) {
Map<String, String> env = builder.environment();
// blah blah
}
```
and pass any `ProcessBuilder`s through it before starting them.
Also, you probably already know this, but you can start more than one process with the same `ProcessBuilder`. So if your subprocesses are the same, you don't need to do this setup over and over. | For use in scenarios where you need to set specific environment values for unit tests, you might find the following hack useful. It will change the environment variables throughout the JVM (so make sure you reset any changes after your test), but will not alter your system environment.
I found that a combination of the two dirty hacks by Edward Campbell and anonymous works best, as one does not work under linux, and the other does not work under windows 7. So to get a multiplatform evil hack I combined them:
```
protected static void setEnv(Map<String, String> newenv) throws Exception {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
}
```
This Works like a charm. Full credits to the two authors of these hacks. | How do I set environment variables from Java? | [
"",
"java",
"environment-variables",
""
] |
Is there a way to detect if a mouse button is currently down in JavaScript?
I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.
Is this possible? | Regarding [Pax' solution](https://stackoverflow.com/a/322650/2750743): it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.
The correct code should be like that:
```
var mouseDown = 0;
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
```
With the test like this:
```
if(mouseDown){
// crikey! isn't she a beauty?
}
```
If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:
```
// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
document.body.onmousedown = function(evt) {
++mouseDown[evt.button];
++mouseDownCount;
}
document.body.onmouseup = function(evt) {
--mouseDown[evt.button];
--mouseDownCount;
}
```
Now you can check what buttons were pressed exactly:
```
if(mouseDownCount){
// alright, let's lift the little bugger up!
for(var i = 0; i < mouseDown.length; ++i){
if(mouseDown[i]){
// we found it right there!
}
}
}
```
Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:
* 0 for "nothing is pressed"
* 1 for left
* 2 for right
* 4 for middle
* and any combination of above, e.g., 5 for left + middle
So adjust your code accordingly! I leave it as an exercise.
**And remember: IE uses a global event object called … "event".**
Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:
```
// for IE only!
document.body.onmousemove = function(){
if(event.button){
// aha! we caught a feisty little sheila!
}
};
```
Of course you get nothing if she plays dead and not moving.
Relevant links:
* [MouseEvent's button (DOM 2)](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent-button)
* [MSDN's button](http://msdn.microsoft.com/en-us/library/ms533544(VS.85).aspx)
***Update #1**: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.* | This is an old question, and the answers here seem to mostly advocate for using `mousedown` and `mouseup` to keep track of whether a button is pressed. But as others have pointed out, `mouseup` will only fire when performed within the browser, which can lead to losing track of the button state.
However, [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) (now) indicates which buttons are currently pushed:
* For all modern browsers (including Safari v11.1+ [v11.3+ on iOS]), use [`MouseEvent.buttons`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons)
* For Safari < 11.1 (11.3 on iOS), use [`MouseEvent.which`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which) (`buttons` will be undefined for Safari) Note: `which` uses different numbers from `buttons` for Right and Middle clicks.
When registered on `document`, `mousemove` will fire immediately as soon as the cursor reenters the browser, so if the user releases outside then the state will be updated as soon as they mouse back inside.
A simple implementation might look like:
```
var primaryMouseButtonDown = false;
function setPrimaryButtonState(e) {
var flags = e.buttons !== undefined ? e.buttons : e.which;
primaryMouseButtonDown = (flags & 1) === 1;
}
document.addEventListener("mousedown", setPrimaryButtonState);
document.addEventListener("mousemove", setPrimaryButtonState);
document.addEventListener("mouseup", setPrimaryButtonState);
```
That code tracks the state of the primary mouse button (typically the left), ignoring the state of other mouse buttons.
If more complicated scenarios are required (different buttons/multiple buttons/control keys), check out the `MouseEvent` docs. | JavaScript: Check if mouse button down? | [
"",
"javascript",
"input",
"mouse",
"user-input",
"input-devices",
""
] |
This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
```
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
```
These files have different original file types such as png, zip, doc, pdf etc.
Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the `file` command?
## Answer:
[J.F. Sebastian's](https://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973) script will work for both ouput of the filenames as well as the actual renaming. | Here's mimetypes' version:
```
#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.
`ext` is mime-based.
"""
import fileinput
import mimetypes
import os
import sys
from subprocess import Popen, PIPE
if len(sys.argv) > 1 and sys.argv[1] == '--rename':
do_rename = True
del sys.argv[1]
else:
do_rename = False
for filename in (line.rstrip() for line in fileinput.input()):
output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
mime = output.split(';', 1)[0].lower().strip()
ext = mimetypes.guess_extension(mime, strict=False)
if ext is None:
ext = os.path.extsep + 'undefined'
filename_ext = filename + ext
print filename_ext
if do_rename:
os.rename(filename, filename_ext)
```
Example:
```
$ ls *.file? | python add-ext.py --rename
avi.file.avi
djvu.file.undefined
doc.file.dot
gif.file.gif
html.file.html
ico.file.obj
jpg.file.jpe
m3u.file.ksh
mp3.file.mp3
mpg.file.m1v
pdf.file.pdf
pdf.file2.pdf
pdf.file3.pdf
png.file.png
tar.bz2.file.undefined
```
---
Following @Phil H's response that follows @csl' response:
```
#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.
`ext` is mime-based.
"""
# Mapping of mime-types to extensions is taken form here:
# http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as
mime2exts_list = [
["application/andrew-inset","ez"],
["application/atom+xml","atom"],
["application/mac-binhex40","hqx"],
["application/mac-compactpro","cpt"],
["application/mathml+xml","mathml"],
["application/msword","doc"],
["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
["application/oda","oda"],
["application/ogg","ogg"],
["application/pdf","pdf"],
["application/postscript","ai","eps","ps"],
["application/rdf+xml","rdf"],
["application/smil","smi","smil"],
["application/srgs","gram"],
["application/srgs+xml","grxml"],
["application/vnd.adobe.apollo-application-installer-package+zip","air"],
["application/vnd.mif","mif"],
["application/vnd.mozilla.xul+xml","xul"],
["application/vnd.ms-excel","xls"],
["application/vnd.ms-powerpoint","ppt"],
["application/vnd.rn-realmedia","rm"],
["application/vnd.wap.wbxml","wbxml"],
["application/vnd.wap.wmlc","wmlc"],
["application/vnd.wap.wmlscriptc","wmlsc"],
["application/voicexml+xml","vxml"],
["application/x-bcpio","bcpio"],
["application/x-cdlink","vcd"],
["application/x-chess-pgn","pgn"],
["application/x-cpio","cpio"],
["application/x-csh","csh"],
["application/x-director","dcr","dir","dxr"],
["application/x-dvi","dvi"],
["application/x-futuresplash","spl"],
["application/x-gtar","gtar"],
["application/x-hdf","hdf"],
["application/x-javascript","js"],
["application/x-koan","skp","skd","skt","skm"],
["application/x-latex","latex"],
["application/x-netcdf","nc","cdf"],
["application/x-sh","sh"],
["application/x-shar","shar"],
["application/x-shockwave-flash","swf"],
["application/x-stuffit","sit"],
["application/x-sv4cpio","sv4cpio"],
["application/x-sv4crc","sv4crc"],
["application/x-tar","tar"],
["application/x-tcl","tcl"],
["application/x-tex","tex"],
["application/x-texinfo","texinfo","texi"],
["application/x-troff","t","tr","roff"],
["application/x-troff-man","man"],
["application/x-troff-me","me"],
["application/x-troff-ms","ms"],
["application/x-ustar","ustar"],
["application/x-wais-source","src"],
["application/xhtml+xml","xhtml","xht"],
["application/xml","xml","xsl"],
["application/xml-dtd","dtd"],
["application/xslt+xml","xslt"],
["application/zip","zip"],
["audio/basic","au","snd"],
["audio/midi","mid","midi","kar"],
["audio/mpeg","mp3","mpga","mp2"],
["audio/x-aiff","aif","aiff","aifc"],
["audio/x-mpegurl","m3u"],
["audio/x-pn-realaudio","ram","ra"],
["audio/x-wav","wav"],
["chemical/x-pdb","pdb"],
["chemical/x-xyz","xyz"],
["image/bmp","bmp"],
["image/cgm","cgm"],
["image/gif","gif"],
["image/ief","ief"],
["image/jpeg","jpg","jpeg","jpe"],
["image/png","png"],
["image/svg+xml","svg"],
["image/tiff","tiff","tif"],
["image/vnd.djvu","djvu","djv"],
["image/vnd.wap.wbmp","wbmp"],
["image/x-cmu-raster","ras"],
["image/x-icon","ico"],
["image/x-portable-anymap","pnm"],
["image/x-portable-bitmap","pbm"],
["image/x-portable-graymap","pgm"],
["image/x-portable-pixmap","ppm"],
["image/x-rgb","rgb"],
["image/x-xbitmap","xbm"],
["image/x-xpixmap","xpm"],
["image/x-xwindowdump","xwd"],
["model/iges","igs","iges"],
["model/mesh","msh","mesh","silo"],
["model/vrml","wrl","vrml"],
["text/calendar","ics","ifb"],
["text/css","css"],
["text/html","html","htm"],
["text/plain","txt","asc"],
["text/richtext","rtx"],
["text/rtf","rtf"],
["text/sgml","sgml","sgm"],
["text/tab-separated-values","tsv"],
["text/vnd.wap.wml","wml"],
["text/vnd.wap.wmlscript","wmls"],
["text/x-setext","etx"],
["video/mpeg","mpg","mpeg","mpe"],
["video/quicktime","mov","qt"],
["video/vnd.mpegurl","m4u","mxu"],
["video/x-flv","flv"],
["video/x-msvideo","avi"],
["video/x-sgi-movie","movie"],
["x-conference/x-cooltalk","ice"]]
#NOTE: take only the first extension
mime2ext = dict(x[:2] for x in mime2exts_list)
if __name__ == '__main__':
import fileinput, os.path
from subprocess import Popen, PIPE
for filename in (line.rstrip() for line in fileinput.input()):
output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
mime = output.split(';', 1)[0].lower().strip()
print filename + os.path.extsep + mime2ext.get(mime, 'undefined')
```
---
Here's a snippet for old python's versions (not tested):
```
#NOTE: take only the first extension
mime2ext = {}
for x in mime2exts_list:
mime2ext[x[0]] = x[1]
if __name__ == '__main__':
import os
import sys
# this version supports only stdin (part of fileinput.input() functionality)
lines = sys.stdin.read().split('\n')
for line in lines:
filename = line.rstrip()
output = os.popen('file -bi ' + filename).read()
mime = output.split(';')[0].lower().strip()
try: ext = mime2ext[mime]
except KeyError:
ext = 'undefined'
print filename + '.' + ext
```
It should work on Python 2.3.5 (I guess). | You can use
```
file -i filename
```
to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a [list of MIME-types](http://www.iana.org/assignments/media-types/media-types.xhtml) and [example file extensions](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) on the net. | How to add file extensions based on file type on Linux/Unix? | [
"",
"python",
"linux",
"bash",
"unix",
"shell",
""
] |
I need to pick up list items from an list, and then perform operations like adding event handlers on them. I can think of two ways of doing this.
HTML:
```
<ul id="list">
<li id="listItem-0"> first item </li>
<li id="listItem-1"> second item </li>
<li id="listItem-2"> third item </li>
</ul>
```
1. Using the IDs-
```
for(i=0;i<3;i++)
{
document.getElementById("listItem-"+i).addEventListener("click",foo,false);
}
```
2. Using childNodes property-
```
for(i=0;i<3;i++)
{
document.getElementById("list").childNodes[i]
.addEventListener("click",foo,false);
}
```
The reason i'm using the first approach is that in the function foo, if I want the index at which the item is located in the list, i can do it by splitting the id -
```
function foo()
{
tempArr = this.id.split('-');
index = tempArr[tempArr.length-1]; // the last element in the array
}
```
I can't think of a way of doing it by using the second method, that is, without using the id naming scheme.
The questions:
1. How do I get the index using the second method or any better method
2. Are there some very bad affects of following the first method ? | You can avoid adding event handlers to each list item by adding a single event handler to the containing element (the unordered list) and leveraging the concept of event bubbling. In this single event handler, you can use properties of the event object to determine what was clicked.
It appears that you are wanting to map data in an array to list items. While parsing out an array index out of the list item id would work, another approach would be to store a "key" value on the list item as an expando, and use javascript object properties to do a lookup for your data.
Partial Example:
```
<li key="myKey">
//oData is a object (eg. var oData = {};) that has been populated with properties
//whose value is the desired data (eg. oData["myKey"] = 123;)
alert(oData[event.srcElement.key]); // alerts 123
```
As far as bad effects of the first technique you showed, one bad effect is that with many list items you end up with many event handlers being defined, which at some point would have an impact on performance.
Also note that you may be unintentionally creating a global var in your loops by omitting the var keyword for "i". | If you opt to use jQuery it comes as simple as:
```
$('ul#list li').click(function () {
var i = this.id.split('-').pop();
alert( i );
});
``` | Identifying list item index - which is a better approach? | [
"",
"javascript",
"html",
"dom",
""
] |
I am thinking about something like this:
```
public static <T extends Comparable<T>> T minOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.first();
}
public static <T extends Comparable<T>> T maxOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.last();
}
```
But is not null safe, which is something I want too.
Do you know a better way to solve this problem?
EDIT:
After the comments I have also tried min():
```
public static <T extends Comparable<T>> T minOf(T...ts){
return Collections.min(Arrays.asList(ts), new Comparator<T>(){
public int compare(T o1, T o2) {
if(o1!=null && o2!=null){
return o1.compareTo(o2);
}else if(o1!=null){
return 1;
}else{
return -1;
}
}});
}
```
What do you think of that? | What's wrong with [Collections.max](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection))?
And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection? | If you really need to exclude "null" from the result, and you can't prevent it from being in your array, then maybe you should just iterate through the array with a simple loop and keep track of the "min" and "max" in separate variables. You can still use the "compare()" method on each object to compare it with your current "min" and "max" values. This way, you can add your own code for checking for nulls and ignoring them.
EDIT: here's some code to illustrate what I'm talking about. Unfortunately there is an edge case you need to consider - what if all of the arguments passed in are null? What does your method return?
```
public static <T extends Comparable<T>> T minOf(T...ts){
T min = null;
for (T t : ts) {
if (t != null && (min == null || t.compareTo(min) < 0)) {
min = t;
}
}
return min;
}
public static <T extends Comparable<T>> T maxOf(T...ts){
T max = null;
for (T t : ts) {
if (t != null && (max == null || t.compareTo(max) > 0)) {
max = t;
}
}
return max;
}
``` | What is the best way to get min and max value from a list of Comparables that main contain null values? | [
"",
"java",
"collections",
"comparable",
""
] |
I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D
If you don't know any (I've done my google search...), yacc/bison is the only way?
Thx | None of these listed in [TheFreeCountry](http://www.thefreecountry.com/compilers/basic.shtml) are acceptable? None of them are in Python, but I should think that starting from [XBLite](http://www.xblite.com/) might be more helpful than starting from Yacc/Bison/[PLY](http://www.dabeaz.com/ply/).
Also, [Vb2py](http://vb2py.sourceforge.net/) might be a better starting position than PLY.
If you must go the PLY route, however, consider the [MOLE Basic](http://www.xs4all.nl/~merty/mole/) grammar as a starting point rather than trying to roll your own from scratch. | [PLY](http://www.dabeaz.com/ply/) is a great parser-creation library for Python. It has a simple BASIC interpreter as one of its example scripts. You could start there. | Is there an OpenSource BASIC interpreter in Ruby/Python? | [
"",
"python",
"ruby",
"interpreter",
""
] |
I need to do a LINQ2DataSet query that does a join on more than one field (as
```
var result = from x in entity
join y in entity2
on x.field1 = y.field1
and
x.field2 = y.field2
```
I have yet found a suitable solution (I can add the extra constraints to a where clause, but this is far from a suitable solution, or use [this](https://stackoverflow.com/questions/345427/linq-to-sql-join-multiple-columns-from-the-same-table) solution, but that assumes an equijoin).
Is it possible in LINQ to join on multiple fields in a single join?
**EDIT**
```
var result = from x in entity
join y in entity2
on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
```
is the solution I referenced as assuming an equijoin above.
Further **EDIT**
To answer criticism that my original example was an equijoin, I do acknowledge that, My current requirement is for an equijoin and I have already employed the solution I referenced above.
I am, however, trying to understand what possibilities and best practices I have / should employ with LINQ. I am going to need to do a Date range query join with a table ID soon, and was just pre-empting that issue, It looks like I shall have to add the date range in the where clause.
Thanks, as always, for all suggestions and comments given | The solution with the anonymous type should work fine. LINQ *can* only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.
If you don't like the version with the anonymous type for some specific reason, you should explain that reason.
If you want to do something other than what you originally asked for, please give an example of what you *really* want to do.
EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.
Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something *similar* - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a `where` clause (after a second `from` clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue. | ```
var result = from x in entity
join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
``` | How to do joins in LINQ on multiple fields in single join | [
"",
"c#",
"linq",
"join",
""
] |
**For a particular segment of Java code, I'd like to measure:**
* **Execution time (most likely *thread execution time*)**
* **Memory usage**
* **CPU load (specifically attributable to the code segment)**
I'm a relative Java novice and am not familiar with how this might be achieved. I've been referred to [JMX](http://en.wikipedia.org/wiki/JMX), however I'm not sure how that might be used, and JMX looks a bit 'heavy' for what I'm looking to do.
Ideally I'd like some measurement class that can be told what I would like to measure, with the option of calling a `start()` method prior to a code segment and a `stop()` method after. Relevant metrics would be logged to a file I specify.
For example:
```
import com.example.metricLogger;
metricLogger logger = new metricLogger();
logger.setLogPath(pathToLogFile);
logger.monitor(executionTime);
logger.monitor(memoryUsage);
logger.monitor(cpuLoad);
logger.start();
/* Code to be measured */
logger.stop();
```
**Is there any standard/common/conventional way of achieving this in Java?**
Such measurements are for one-off performance comparisons, and so I'm not looking for any in-production long-term monitoring processes.
I'm more than happy to be referred to tutorials or external examples and don't expect a full answer here. That said, if anything as simple as the above can be achieved a realistic example would go down really well. | Profiling may be an easier option since you don't require in-production stats. Profiling also doesn't require code modification. VisualVM (which ships w/ the JDK 1.6.06+) is a simple tool. If you want something more in-depth I'd go with Eclipse TPTP, Netbeans profiler, or JProfiler(pay).
If you want to write you own, consider the following:
Simple measurments like execution time can be done by "clocking" the section you're interested in:
```
long start = System.nanoTime(); // requires java 1.5
// Segment to monitor
double elapsedTimeInSec = (System.nanoTime() - start) * 1.0e-9;
```
You can use a similar technique to monitor memory via Runtime.getRuntime().\*memory() methods. Keep in mind that tracking memory usage in a garbage collected environment is trickier than simple subtraction.
CPU load is hard to measure in Java, I typically stick with execution time and optimize the longer / repetitive sections | With the ThreadMXBean you can get CPU usage of individual threads and cpu time consumed rather than elapse time which may be useful.
However, its often simpler to use a profiler as this process often generates a lot of data and you need a good visualisation tool to see what is going on.
I use Yourkit as I find it easier to solve problems that other profilers I have used.
I also use the builtin hprof as this can give you a different view on the profile of your application (but not as useful) | Measuring Java execution time, memory usage and CPU load for a code segment | [
"",
"java",
"performance",
"monitoring",
"jmx",
"measurement",
""
] |
I need to put an LDAP contextSource into my Java EE container's JNDI tree so it can be used by applications inside the container.
I'm using Spring-LDAP to perform queries against ORACLE OVD. For development, I simply set up the contextSource in the Spring xml configuration file. For production, however, I need to be able to use a JNDI lookup to grab the connection/context from the container (as suggested here: <http://forum.springframework.org/showthread.php?t=35122&highlight=jndi>). I'm not allowed to have access to the URL/username/pwd for the production OVD instance, so that seems to rule out putting it in a jndi.properties file.
Ideally, I'd like to have a pool of connections (just like JDBC), as my application may have many LDAP queries executing at the same time. Grabbing the object from a JNDI lookup and injecting it into my SimpleLdapTemplate seems pretty straightforward, but I'm at a loss as to how to get the connection/context/pool into the JNDI tree. Would I need to construct it and package it into a RAR? If so, what are some options for letting the operations team specify the URL/username/pwd in a way that they are not accessible to the developers?
The specific container I'm using is OAS/OC4J, though I welcome strategies that have worked on other containers as well. | Specifically in reference to the actual pooling of LDAP connections, if you are using the built in JNDI LDAP provider, the connections are pooled already using semantics similar to JDBC data sources where separate pools are maintained for different LDAP URLs and security properties.
When creating a JNDI `DirContext`, configure the property com.sun.jndi.ldap.connect.pool to be **true** and pooling will be enabled.
There is more information on LDAP pooling [here](http://java.sun.com/products/jndi/tutorial/ldap/connect/pool.html).
Details on configuring LDAP pooling are [here](http://java.sun.com/products/jndi/tutorial/ldap/connect/config.html). | Any chance you can setup a dev version of LDAP and use that? Then you can use a jndi.properties file, which would be environment specific, but agnostic to your system.
Edit: the difference here is that when you build your app, your admin can deploy it to the production system, thereby protecting the precious ldap password as it only exists in the properties file on the production box. | How can I set up an LDAP connection pool in a Java EE Container? | [
"",
"java",
"spring",
"jakarta-ee",
"ldap",
"jndi",
""
] |
I have a gallery I quickly coded up for a small site, and under Firefox 3 and Safari 3 works fine. But when I test on my old best friend IE7, it seems to not fire the imageVar.onload = function() { // code here }.. which I want to use to stop the load effect and load the image.
Please bear in mind...
* I know the thumbnails are just scaled down version of the larger images. When the images are finalised by the client I am going to create proper thumbnails.
* This is my first attempt to try and get out of procedural JavaScript for the most part.. so please go easy and kindly let me know where my code sucks! | For successful use of Image.onload, you must register the event handler method before the src attribute is set.
**Related Information in this Question:**
**[Javascript callback for Image Loading](https://stackoverflow.com/questions/280049/javascript-callback-for-knowing-when-an-image-is-loading#280087)** | Cross browser event support is not so straightforward due to implementation differences. Since you are using jQuery at your site, you are better off using its events methods to normalize browser support:
instead of:
```
window.load = function(){
//actions to be performed on window load
}
imageViewer.image.onload = function(){
//actions to be performed on image load
}
```
Do:
```
$(window).load(function(){
//actions to be performed on window load
});
$(imageViewer.image).load(function(){
//actions to be performed on image load
});
``` | JavaScript & IE7 - Why won't my *.onload = function() { } fire? | [
"",
"javascript",
"xhtml",
"internet-explorer-7",
""
] |
I'm trying to attach a PDF attachment to an email being sent with System.Net.Mail. The attachment-adding part looks like this:
```
using (MemoryStream pdfStream = new MemoryStream())
{
pdfStream.Write(pdfData, 0, pdfData.Length);
Attachment a = new Attachment(pdfStream,
string.Format("Receipt_{0}_{1}.pdf", jobId, DateTime.UtcNow.ToString("yyyyMMddHHmm")));
msg.Attachments.Add(a);
SmtpClient smtp = new SmtpClient(serverName, port);
smtp.Credentials = new NetworkCredential(fromEmailName, fromEmailPassword);
smtp.Send(msg);
}
```
The problem is that the attachment gets corrupted on the other end. I found some discussion of this problem [here](http://www.systemwebmail.com/faq/4.4.8.aspx), however the solution mentioned on that page used System.Web.Mail.MailAttachment, which was made obsolete in .NET 2.0.
I've tried changing the TransferEncoding in the Attachment class (which replaces MailAttachment), but had no luck. Has anyone solved this on .NET 2.0? | Have you tried doing a `pdfStream.Seek(0,SeekOrigin.Begin)` before creating the attachment to reset the stream to the beginning? | Have you checked to make sure that the PDF document isn't already corrupted in the pdfData array? Try writing that to a file then opening it. | corrupted email attachments in .NET | [
"",
"c#",
".net",
"smtp",
""
] |
Does python have the ability to create dynamic keywords?
For example:
```
qset.filter(min_price__usd__range=(min_price, max_price))
```
I want to be able to change the **usd** part based on a selected currency. | Yes, It does. Use `**kwargs` in a function definition.
Example:
```
def f(**kwargs):
print kwargs.keys()
f(a=2, b="b") # -> ['a', 'b']
f(**{'d'+'e': 1}) # -> ['de']
```
But why do you need that? | If I understand what you're asking correctly,
```
qset.filter(**{
'min_price_' + selected_currency + '_range' :
(min_price, max_price)})
```
does what you need. | Dynamic Keyword Arguments in Python? | [
"",
"python",
""
] |
I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec\_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?
```
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
```
Does anyone know how this can addressed? Thank you. | The full paramiko distribution ships with a lot of good [demos](https://github.com/paramiko/paramiko/tree/master/demos).
In the demos subdirectory, `demo.py` and `interactive.py` have full interactive TTY examples which would probably be overkill for your situation.
In your example above `ssh_stdin` acts like a standard Python file object, so `ssh_stdin.write` should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard `stdin.write` method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the [`SSHClient.exec_command`](http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.exec_command) method is implemented for all the gory details. | I had the same problem trying to make an interactive ssh session using [ssh](https://github.com/bitprophet/ssh/), a fork of Paramiko.
I dug around and found this article:
**Updated link** (last version before the link generated a 404): <http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/>
To continue your example you could do
```
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()
```
The article goes more in depth, describing a fully interactive shell around exec\_command. I found this a lot easier to use than the examples in the source.
**Original link**: <http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/> | Running interactive commands in Paramiko | [
"",
"python",
"ssh",
"paramiko",
""
] |
I'm have a ADO DataSet that I'm loading from its XML file via ReadXml. The data and the schema are in separate files.
Right now, it takes close to 13 seconds to load this DataSet. I can cut this to 700 milliseconds if I don't read the DataSet's schema and just let ReadXml infer the schema, but then the resulting DataSet doesn't contain any constraints.
I've tried doing this:
```
Console.WriteLine("Reading dataset with external schema.");
ds.ReadXmlSchema(xsdPath);
Console.WriteLine("Reading the schema took {0} milliseconds.", sw.ElapsedMilliseconds);
foreach (DataTable dt in ds.Tables)
{
dt.BeginLoadData();
}
ds.ReadXml(xmlPath);
Console.WriteLine("ReadXml completed after {0} milliseconds.", sw.ElapsedMilliseconds);
foreach (DataTable dt in ds.Tables)
{
dt.EndLoadData();
}
Console.WriteLine("Process complete at {0} milliseconds.", sw.ElapsedMilliseconds);
```
When I do this, reading the schema takes 27ms, and reading the DataSet takes 12000+ milliseconds. And that's the time reported *before* I call EndLoadData on all the DataTables.
This is not an enormous amount of data - it's about 1.5mb, there are no nested relations, and all of the tables contain two or three columns of 6-30 characters. The only thing I can figure that's different if I read the schema up front is that the schema includes all of the unique constraints. But BeginLoadData is supposed to turn constraints off (as well as change notification, etc.). So that shouldn't apply here. (And yes, I've tried just setting EnforceConstraints to false.)
I've read many reports of people improving the load time of DataSets by reading the schema first instead of having the object infer the schema. In my case, inferring the schema makes for a process that's about 20 times faster than having the schema provided explicitly.
This is making me a little crazy. This DataSet's schema is generated off of metainformation, and I'm tempted to write a method that creates it programatically and just deseralizes it with an XmlReader. But I'd much prefer not to.
What am I missing? What else can I do to improve the speed here? | It's not an answer, exactly (though it's better than nothing, which is what I've gotten so far), but after a long time struggling with this problem I discovered that it's completely absent when my program's not running inside Visual Studio.
Something I didn't mention before, which makes this even more mystifying, is that when I loaded a different (but comparably large) XML document into the DataSet, the program performed just fine. I'm now wondering if one of my DataSets has some kind of metainformation attached to it that Visual Studio is checking at runtime while the other one doesn't. I dunno. | I will try to give you a performance comparison between storing data in text plain files and xml files.
The first function creates two files: one file with 1000000 records in plain text and one file with 1000000 (same data) records in xml. First you have to notice the difference in file size: ~64MB(plain text) vs ~102MB (xml file).
```
void create_files()
{
//create text file with data
StreamWriter sr = new StreamWriter("plain_text.txt");
for(int i=0;i<1000000;i++)
{
sr.WriteLine(i.ToString() + "<SEP>" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbb" + i.ToString());
}
sr.Flush();
sr.Close();
//create xml file with data
DataSet ds = new DataSet("DS1");
DataTable dt = new DataTable("T1");
DataColumn c1 = new DataColumn("c1", typeof(int));
DataColumn c2 = new DataColumn("c2", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
ds.Tables.Add(dt);
DataRow dr;
for(int j=0; j< 1000000; j++)
{
dr = dt.NewRow();
dr[0]=j;
dr[1] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbb" + j.ToString();
dt.Rows.Add(dr);
}
ds.WriteXml("xml_text.xml");
}
```
The second function reads these two files: first it reads the plain text into a dictionary (just to simulate the real world of using it) and after that it reads the XML file. Both steps are measured in milliseconds (and results are written to console):
*Start read Text file into memory
Text file loaded into memory in 7628 milliseconds
Start read XML file into memory
XML file loaded into memory in 21018 milliseconds*
```
void read_files()
{
//timers
Stopwatch stw = new Stopwatch();
long milliseconds;
//read text file in a dictionary
Debug.WriteLine("Start read Text file into memory");
stw.Start();
milliseconds = 0;
StreamReader sr = new StreamReader("plain_text.txt");
Dictionary<int, string> dict = new Dictionary<int, string>(1000000);
string line;
string[] sep = new string[]{"<SEP>"};
string [] arValues;
while (sr.EndOfStream!=true)
{
line = sr.ReadLine();
arValues = line.Split(sep,StringSplitOptions.None);
dict.Add(Convert.ToInt32(arValues[0]),arValues[1]);
}
stw.Stop();
milliseconds = stw.ElapsedMilliseconds;
Debug.WriteLine("Text file loaded into memory in " + milliseconds.ToString() + " milliseconds" );
//create xml structure
DataSet ds = new DataSet("DS1");
DataTable dt = new DataTable("T1");
DataColumn c1 = new DataColumn("c1", typeof(int));
DataColumn c2 = new DataColumn("c2", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
ds.Tables.Add(dt);
//read xml file
Debug.WriteLine("Start read XML file into memory");
stw.Restart();
milliseconds = 0;
ds.ReadXml("xml_text.xml");
stw.Stop();
milliseconds = stw.ElapsedMilliseconds;
Debug.WriteLine("XML file loaded into memory in " + milliseconds.ToString() + " milliseconds");
}
```
Conclusion: the XML file size is almost double than the text file size and is loaded three times slower than the text file.
XML handling is more convenient (because of the abstraction level) than plain text but it is more CPU/disk consuming.
So, if you have small files and is acceptable from the performance point of view, XML data Sets are more than ok. But, if you need performance, I don't know if XML Data set ( with any kind of method available) is faster that plain text files. And basically, it start from the very first reason: XML file is bigger because it has more tags. | How do I improve performance of DataSet.ReadXml if I'm using a schema? | [
"",
"c#",
"performance",
"ado.net",
"dataset",
"readxml",
""
] |
This is a follow-up question to [this one](https://stackoverflow.com/questions/369220/why-should-you-not-use-number-as-a-constructor).
Take a look at these two examples:
```
var number1 = new Number(3.123);
number1 = number1.toFixed(2);
alert(number1);
var number2 = 3.123;
number2 = number2.toFixed(2);
alert(number2);
```
I realize they both end up with the same value, but is it correct thinking to refer to a method of a primitive value? (In other words, 3.123.method as opposed to object.method?) | In JavaScript, everything is an object, even functions and integers. It is perfectly OK to think of methods on numbers and strings. For example:
```
>>> (3.123).toString()
"3.123"
``` | Technically, no. You can treat it like it is a method of the primative value, because number2 is will be converted to a `Number` object, then `toFixed` is gets called on that object.
The same thing happens when you call methods on strings.
To illustrate what's happening, you can run this code:
```
Object.prototype.type = function() { return typeof this; }
var string = "a string";
var number = 42;
alert(typeof string); // string
alert(string.type()); // object
alert(typeof number); // number
alert(number.type()); // object
``` | Question about object.method in JavaScript | [
"",
"javascript",
"oop",
"methods",
""
] |
Let's start with the following snippet:
```
Foreach(Record item in RecordList){
..
item = UpdateRecord(item, 5);
..
}
```
The UpdateRecode function changes some field of item and returns the altered object. In this case the compiler throws an exception saying that the item can not be updated in a foreach iteration.
Now the UpdateRecord method is changed so that it returns void and the snippet would look like this:
```
Foreach(Record item in RecordList){
..
UpdateRecord(item, 5);
..
}
```
In this case the item would be updated because Record is a reference type. But it makes the code unreadable.
The project I'm working on has lots of foreach-loops with the almost the same code over and over, so I would like to create methods that update parts of the records. Is there a nice way to do this? One that make the code more readable instead of trashing it further more? | If you need to update a collection, don't use an iterator pattern, like you said, its either error prone, or smells bad.
I find that using a for loop with an index a bit clearer in this situation, as its very obvious what you are trying to do that way. | The compiler is complaining that you can't update the *collection*, not the record. By doing item = UpdateRecord, you are reassigning the iterator variable item.
I disagree that UpdateRecord(item, 5) is in any way unreadable - but if it makes you feel better, an extension method may make it more clear that you are changing the contents of item.
```
static void Update(this Record item, int value) {
// do logic
}
foreach (Record item in RecordList) {
item.Update(5);
}
``` | Changing item in foreach thru method | [
"",
"c#",
"methods",
"foreach",
""
] |
I have a textbox with an onchange event. Why does this event not fire when the user uses the autocomplete feature to populate the textbox?
I am working with Internet Explorer. Is there a standard and relatively simple solution to workaround this problem, without me having to disable the autocomplete feature? | Last time I had that issue, I ended up using the `onpropertychange` event for Internet Explorer instead. I read about that [here on MSDN](http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx): it is the recommended way to get around it. | I've encountered this annoying feature before and my solution at the time was to use the onfocus event to record the current value of the text box, and then use the onblur event to check whether the current value now matches the value saved during onfocus. For example
```
<input type="text" name="txtTest" value="" onfocus="this.originalvalue=this.value" onblur="if (this.value != this.originalvalue) alert('Test has changed')"/>
``` | Why does the javascript onchange event not fire if autocomplete is on? | [
"",
"asp.net",
"javascript",
""
] |
I am building a small wpf app in C#. When a button gets clicked a third
party dll function constructs a tree like object. This object is bound
to a treeview. This works fine but takes a bit of time to load. As the
dll function constructs the object it prints progress info to the
console. I want to redirect this into a TextBlock so that the user
gets to see the progress messages.
My window ctor looks like this:
```
InitializeComponent();
StringRedir s = new StringRedir(ref ProgressTextBlock);
Console.SetOut(s);
Console.SetError(s);
this.DataContext = s;
```
xaml:
```
<TextBlock Text="{Binding Path=Text}" Width="244"
x:Name="ProgressTextBlock" TextWrapping="Wrap" />
<TreeView >...</TreeView>
```
The StringRedir class is shown below. The problem is the TextBlock for
some reason does not get updated with the messages until the TreeView
gets loaded. Stepping through I see the Text property being updated
but the TextBlock is not getting refreshed. I added a MessageBox.Show
() at the point where Text gets updated and this seems to cause the
window to refresh each time and I am able to see each message. So I
guess I need some way to explicitly refresh the screen...but this
doesnt make sense I thought the databinding would cause a visual
refresh when the property changed. What am I missing here? How do I
get it to refresh? Any advice is appreciated!
```
public class StringRedir : StringWriter , INotifyPropertyChanged
{
private string text;
private TextBlock local;
public string Text {
get{ return text;}
set{
text = text + value;
OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public StringRedir(ref TextBlock t)
{
local = t;
Text = "";
}
public override void WriteLine(string x)
{
Text = x +"\n";
//MessageBox.Show("hello");
}
}
``` | You haven't included the code that is loading the data for the `TreeView`, but I'm guessing it's being done on the UI thread. If so, this will block any UI updates (including changes to the `TextBlock`) until it has completed. | So after doing some reading on the WPF threading model ( <http://msdn.microsoft.com/en-us/library/ms741870.aspx> ) I finally got it to refresh by calling Dispatcher Invoke() with Dispatch priority set to Render. As Kent suggested above UI updates in the dispatcher queue were probably low priority. I ended up doing something like this.
XAML
```
<TextBox VerticalScrollBarVisibility="Auto"
Text="{Binding Path=Text, NotifyOnTargetUpdated=True}"
x:Name="test" TextWrapping="Wrap" AcceptsReturn="True"
TargetUpdated="test_TargetUpdated"/>
```
C# target updated handler code
```
private void test_TargetUpdated(object sender, DataTransferEventArgs e)
{
TextBox t = sender as TextBox;
t.ScrollToEnd();
t.Dispatcher.Invoke(new EmptyDelegate(() => { }), System.Windows.Threading.DispatcherPriority.Render);
}
```
Note: Earlier I was using a TextBlock but I changed to a TextBox as it comes with scrolling
I still feel uneasy about the whole flow though. Is there a better way to do this?
Thanks to Matt and Kent for their comments. If I had points would mark their answers as helpful. | WPF problems refreshing textblock bound to console.stdout | [
"",
"c#",
"wpf",
"user-interface",
"console",
"refresh",
""
] |
I am using Hibernate 3.x, MySQL 4.1.20 with Java 1.6. I am mapping a Hibernate Timestamp to a MySQL TIMESTAMP. So far so good. The problem is that MySQL stores the TIMESTAMP in seconds and discards the milliseconds and I now need millisecond precision. I figure I can use a BIGINT instead of TIMESTAMP in my table and convert the types in my Java code. I'm trying to figure out if there is a better way of doing this using hibernate, mysql, JDBC or some combination so I can still use date functions in my HSQL and/or SQL queries? | Also, look at creating a custom Hibernate Type implementation. Something along the lines of (psuedocode as I don't have a handy environment to make it bulletproof):
```
public class CalendarBigIntType extends org.hibernate.type.CalendarType {
public Object get(ResultSet rs, String name) {
return cal = new GregorianCalendar(rs.getLong(name));
}
public void set(PreparedStatement stmt, Object value, int index) {
stmt.setParameter(index, ((Calendar) value).getTime());
}
}
```
Then, you'll need to map your new object using a hibernate TypeDef and Type mappings. If you are using Hibernate annotations, it be along the lines of:
```
@TypeDef (name="bigIntCalendar", typeClass=CalendarBigIntType.class)
@Entity
public class MyEntity {
@Type(type="bigIntCalendar")
private Calendar myDate;
}
``` | For those who are still interested in this issue: MySQL 5.6.4 supports timestamps with precision. Subclassing MySQL5Dialect to override the used MySQL type solves the problem. | How do I map a hibernate Timestamp to a MySQL BIGINT? | [
"",
"java",
"mysql",
"hibernate",
"orm",
"jdbc",
""
] |
**What in C#.NET makes it more suitable** for some projects than VB.NET?
Performance?, Capabilities?, Libraries/Components?, Reputation?, Reliability? Maintainability?, Ease?
---
Basically anything **C# can do, that is impossible using VB,** or vice versa.
Things you just **have to consider** when choosing C#/VB for a project. | C# and VB are basically the same however there are some minor differences. Aside from the obvious grammar differences you have the following differences:
1. C# can call unsafe code
2. VB has optional parameters (Coming in C#4.0)
3. VB is easier to use when making late bound calls (Coming in C# 4.0) This and number make 2 make using VB to do office automation much cleaner.
4. VB has a bunch of "helper" functions and class like the My namespace; however, all of this are accessible to C#
5. VB is case insensitive
C#'s syntax follow a similar grammar to c and java, which make it a much more comfortable transition from those languages, where as VB can be more comfortable to VB users. As far performance, and libraries or components they are nearly identical.
As for which one to choose, unless you have a need to do unsafe operations, then choose the language which is most natural to you. After years of being a VB developer I loved not having to write If yadada then.....End If if (yadaya){....} saves my carpal tunnel a few extra keystrokes (Which can then be used on answering SO questions)
# Edit
Just learned one more difference btw C# and VB is that VB supports filtered exceptions so you could something like this pseudo:
```
try
{
//do something that fails
}
catch(Exception ex when ArgumentException,
ArgumentNullException, FormatException)
{
//Only handle these three types
}
```
This should not be confused with the ability to do:
```
try
{
//something that fails
}
catch(ArgumentException)
{
//Log Error
}
catch(ArgumentNullException)
{
//Log Error
}
```
In this case you are going to handle the exceptions differently in the VB world you could define one piece of code to handle multiple types of Exceptions.
# Edit
Some more differences.
7. VB's Is operator compares two objects to determine if they are the same it compiles to the CEQ IL instruction where as C# compiles to isinst IL. So the following are equivalent statements
c#
`if (foo is FooObject){}`
vb
`If TypeOf foo is FooObject then`
8. Also as mentioned in the comments and I wish I could see them to give you credit but C# doesn't have a like parameter. You need to use the RegEx class. | I think this blog post by Kathleen Dollard provides an excellent overview to the question:
[**What a C# Coder Should Know Before They Write VB**](http://msmvps.com/blogs/kathleen/archive/2008/07/25/what-a-c-coder-should-know-before-they-write-vb-updated.aspx)
and her first advice is:
> 1) Get over the respect thing or quit
> before you start. VB is a great
> language. | C#'s edge over VB | [
"",
"c#",
".net",
"vb.net",
""
] |
I want to examine the contents of a std::vector in gdb but I don't have access to \_M\_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity.
There is a very nice answer [here](https://stackoverflow.com/questions/253099/how-do-i-print-the-elements-of-a-c-vector-in-gdb) but this doesn't work if I use icc, the error message is "There is no member or method named \_M\_impl". There appears to be a nice debug toolset [here](http://www.yolinux.com/TUTORIALS/GDB-Commands.html#STLDEREF) but it also relies on \_M\_impl. | Not sure this will work with your vector, but it worked for me.
```
#include <string>
#include <vector>
int main() {
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("world");
vec.push_back("!");
return 0;
}
```
gdb:
```
(gdb) break source.cpp:8
(gdb) run
(gdb) p vec.begin()
$1 = {
_M_current = 0x300340
}
(gdb) p $1._M_current->c_str()
$2 = 0x3002fc "Hello"
(gdb) p $1._M_current +1
$3 = (string *) 0x300344
(gdb) p $3->c_str()
$4 = 0x30032c "world"
``` | Generally when I deal with the container classes in a debugger, I build a reference to the element, as a local variable, so it is easy to see in the debugger, without mucking about in the container implementation.
Here is a contrived example.
```
vector<WeirdStructure> myWeird;
/* push back a lot of stuff into the vector */
size_t z;
for (z = 0; z < myWeird.size(); z++)
{
WeirdStructure& weird = myWeird[z];
/* at this point weird is directly observable by the debugger */
/* your code to manipulate weird goes here */
}
```
That is the idiom I use. | How do I examine the contents of an std::vector in gdb, using the icc compiler? | [
"",
"c++",
"stl",
"vector",
"gdb",
"icc",
""
] |
First a little intro:
Last year i wrote this <http://dragan.yourtree.org/code/canvas-3d-graph/>
Now, i want to make complete rewrite of it, because that old version have some limitations, for example: sometimes it happens that bars are not visible, because they are drawn one behind another.
In this old version there is no real 3d, just bunck of 2D lines, which emulate 3D.
Now, what i want is to go to full blown 3D scene, i want to keep all the objects in memory, and add some kind of 3D navigation buttons that will enable users to rotate whole scene on all 3 axis, and zoom camera in and out.
I've already decided that i will use <http://sylvester.jcoglan.com/> for vector/matrix stuff, but i'm still unable to find good tutorial for 3D. There are tons of texts on the Internet, most of them date from the 90s, an are incomplete or written really bad.
So, my question is: what is the best online resource/tutorial that will enable me to write my own JS 3D engine from scratch.
It should cover all relevant topics:
* vectors
* matrices
* objects
* camera
* scene rendering
* lighting
* rotating objects on scene
* moving the camera
etc..
(i'm fairly familiar with first two)
Thank you for your time. | If this is specifically for a JavaScript related project then I understand but if you are simply doing this to grasp the basics of 3d rendering there might be more mature platforms out there for you.
In any case..
Links that might be useful to your learning:
* [Prototyping A Simple 3d Renderer In JavaScript](http://hem.spray.se/vilius/js3Dtutor.html)
* [3D Basics - A Primer](http://www.gamedev.net/reference/articles/article673.asp)
* [The JavaScript Raytracer](http://www.slimeland.com/raytrace/help.html)
* [JavaScript 3D Renderer](http://www.nihilogic.dk/labs/canvas3dtexture_0.2/)
Also, some fun JavaScript 3d examples:
* [Rotating 3D Cube in JavaScript](http://maettig.com/code/javascript/3d_dots.html)
* [Wolfenstein 3D in JavaScript](http://blog.nihilogic.dk/2008/04/javascript-wolfenstein-3d.html)
* Anything else in this SO Question: [Stunning graphic effects with JavaScript?](https://stackoverflow.com/questions/254535/stunning-graphic-effects-with-javascript) | Just a couple of suggestions, but probably not exactly what you're looking for:
I suggest that you take a look at Jacob Seidelin's canvas examples at nihilogic.dk : [<http://blog.nihilogic.dk/search/label/canvas>](http://blog.nihilogic.dk/search/label/canvas) .
If you're willing to abandon canvas and go with an existing flash library, take a look at Sandy3D : <http://www.flashsandy.org/demos> . | What is the best online resource for 3D rendering in JavaScript? | [
"",
"javascript",
"3d",
"rendering",
""
] |
I've been lately trying to learn more and generally test Java's serialization for both work and personal projects and I must say that the more I know about it, the less I like it. This may be caused by misinformation though so that's why I'm asking these two things from you all:
**1:** On byte level, how does serialization know how to match serialized values with some class?
One of my problems right here is that I made a small test with ArrayList containing values "one", "two", "three". After serialization the byte array took 78 bytes which seems awfully lot for such low amount of information(19+3+3+4 bytes). Granted there's bound to be some overhead but this leads to my second question:
**2:** Can serialization be considered a good method for persisting objects at all? Now obviously if I'd use some homemade XML format the persistence data would be something like this
```
<object>
<class="java.util.ArrayList">
<!-- Object array inside Arraylist is called elementData -->
<field name="elementData">
<value>One</value>
<value>Two</value>
<value>Three</value>
</field>
</object>
```
which, like XML in general, is a bit bloated and takes 138 bytes(without whitespaces, that is). The same in JSON could be
```
{
"java.util.ArrayList": {
"elementData": [
"one",
"two",
"three"
]
}
}
```
which is 75 bytes so already slightly smaller than Java's serialization. With these text-based formats it's of course obvious that there has to be a way to represent your basic data as text, numbers or any combination of both.
So to recap, how does serialization work on byte/bit level, when it should be used and when it shouldn't be used and what are real benefits of serialization besides that it comes standard in Java? | I would personally try to avoid Java's "built-in" serialization:
* It's not portable to other platforms
* It's not hugely efficient
* It's fragile - getting it to cope with multiple versions of a class is somewhat tricky. Even changing compilers can break serialization unless you're careful.
For details of what the actual bytes mean, see the [Java Object Serialization Specification](http://java.sun.com/javase/6/docs/platform/serialization/spec/serialTOC.html).
There are various alternatives, such as:
* XML and JSON, as you've shown (various XML flavours, of course)
* [YAML](http://en.wikipedia.org/wiki/Yaml)
* Facebook's [Thrift](http://incubator.apache.org/thrift/) (RPC as well as serialization)
* [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/)
* [Hessian](http://hessian.caucho.com/) (web services as well as serialization)
* [Apache Avro](http://avro.apache.org/)
* Your own custom format
(Disclaimer: I work for Google, and I'm doing a port of Protocol Buffers to C# as my 20% project, so clearly I think that's a good bit of technology :)
Cross-platform formats are almost always more restrictive than platform-specific formats for obvious reasons - Protocol Buffers has a pretty limited set of native types, for example - but the interoperability can be incredibly useful. You also need to consider the impact of versioning, with backward and forward compatibility, etc. The text formats are generally hand-editable, but tend to be less efficient in both space and time.
Basically, you need to look at your requirements carefully. | The main advantage of serialization is that it is extremely easy to use, relatively fast, and preserves actual Java object meshes.
But you have to realize that it's not really meant to be used for storing data, but mainly as a way for different JVM instances to communicate over a network using the RMI protocol. | How does Java's serialization work and when it should be used instead of some other persistence technique? | [
"",
"java",
"serialization",
""
] |
I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site.
There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an overkill in my scenario.
So I've got two questions, really:
* is there another OpenID plugin for Symfony supporting OpenID 2.0?
* what would be the hack required to make sfOpenID support OpenID 2.0?
I suppose I could study OpenID specs and hack it myself, but then, I am a lazy programmer :) | I think you've covered all your options with sfOpenID and taOpenIDsfGuardPlugin for Symfony's plugins.
Without studying OpenID's specs in detail though, you could try one of those PHP libraries (<http://wiki.openid.net/Libraries>) by dropping it in your lib and connecting to a `sfUser`, or whatever you're using for authentication. There is also the OpenID Enabled library (<http://openidenabled.com/php-openid/>) which still uses PHP4 although compatible with PHP5 if you [tweak the error reporting level](http://www.php.net/manual/en/errorfunc.configuration.php) to exclude some warnings.
There are a few tutorials out there that explains how to enable OpenID on your site with PHP: <http://www.saeven.net/openid.htm> or <http://www.plaxo.com/api/openid_recipe>.
And better yet, use this knowledge to [make a sfPlugin out of it](http://www.symfony-project.org/book/1_1/17-Extending-Symfony#How%20to%20Write%20a%20Plug-In) afterwards. | There is an easier way. JanRain offers OpenID (and facebook) as a service <http://rpxnow.com> . Vastly easier/quicker than going native with the libraries. | Is there an OpenID 2.0 plugin for Symfony? | [
"",
"php",
"symfony1",
"openid",
""
] |
Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.
It would be nice to be able to do this using SharpZipLib. | Use `ZipEntry` and `PutNextEntry()` for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream
```
FileStream fZip = File.Create(compressedOutputFile);
ZipOutputStream zipOStream = new ZipOutputStream(fZip);
foreach (FileInfo fi in allfiles)
{
ZipEntry entry = new ZipEntry((fi.Name));
zipOStream.PutNextEntry(entry);
FileStream fs = File.OpenRead(fi.FullName);
try
{
byte[] transferBuffer[1024];
do
{
bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);
zipOStream.Write(transferBuffer, 0, bytesRead);
}
while (bytesRead > 0);
}
finally
{
fs.Close();
}
}
zipOStream.Finish();
zipOStream.Close();
``` | Using SharpZipLib for this seems pretty complicated. This is so much easier in [DotNetZip](http://www.codeplex.com/DotNetZip). In v1.9, the code looks like this:
```
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("Readme.txt", stringContent1);
zip.AddEntry("readings/Data.csv", stringContent2);
zip.AddEntry("readings/Index.xml", stringContent3);
zip.Save("Archive1.zip");
}
```
The code above assumes stringContent{1,2,3} contains the data to be stored in the files (or entries) in the zip archive. The first entry is "Readme.txt" and it is stored in the top level "Directory" in the zip archive. The next two entries are stored in the "readings" directory in the zip archive.
The strings are encoded in the default encoding. There is an overload of AddEntry(), not shown here, that allows you to explicitly specify the encoding to use.
If you have the content in a stream or byte array, not a string, there are overloads for AddEntry() that accept those types. There are also overloads that accept a Write delegate, a method of yours that is invoked to write data into the zip. This works for easily saving a DataSet into a zip file, for example.
DotNetZip is free and open source. | Create Zip archive from multiple in memory files in C# | [
"",
"c#",
"compression",
"zip",
""
] |
I am new to Python, and I'm working on writing some database code using the `cx_Oracle` module. In the [cx\_Oracle documentation](http://cx-oracle.sourceforge.net/html/module.html) they have a code example like this:
```
import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc.args
print >> sys.stderr, "Oracle-Error-Code:", error.code
print >> sys.stderr, "Oracle-Error-Message:", error.message
```
My question has to do with where the "error" object is created. What does the "`, =`" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)
I know that the exc.args is a singleton tuple, but I just don't understand the "`, =`" syntax. If I remove the comma, I get the error message, "`AttributeError: 'tuple' object has no attribute 'code'`".
Can someone point me to where this is documented? Thanks!
**EDIT:**
This works without having to unpack the tuple:
```
import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code
print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message
``` | ```
error, = exc.args
```
This is a case of [sequence unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences).
A more readable way to write the same, and the style I personally favor, is:
```
[error] = exc.args
```
There are two bits required to understand the previous example:
1. When the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS.
2. A one-item tuple in python is written `(foo,)`. In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator. | [http://www.python.org/doc/2.5.2/tut/node7.html](http://www.python.org/doc/2.5.2/tut/node7.html#SECTION007300000000000000000)
Look for "sequence unpacking" in section 5.3. | Newbie Python Question about tuples | [
"",
"python",
"tuples",
"cx-oracle",
""
] |
Any idea on how to check whether that list is a subset of another?
Specifically, I have
```
List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };
```
How to check that t2 is a subset of t1, using LINQ? | ```
bool isSubset = !t2.Except(t1).Any();
``` | Use HashSet instead of List if working with sets. Then you can simply use [IsSubsetOf()](http://msdn.microsoft.com/en-us/library/bb358446.aspx)
```
HashSet<double> t1 = new HashSet<double>{1,3,5};
HashSet<double> t2 = new HashSet<double>{1,5};
bool isSubset = t2.IsSubsetOf(t1);
```
Sorry that it doesn't use LINQ. :-(
If you need to use lists, then @Jared's solution works with the caveat that you will need to remove any repeated elements that exist. | Check whether an array is a subset of another | [
"",
"c#",
"list",
"linq",
"subset",
""
] |
I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do:
```
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
vector<int*> vec;
int i = 1;
int j = 2;
int k = 3;
vec.push_back(&i);
vec.push_back(&j);
vec.push_back(&k);
copy(deref_iterator(vec.begin()),
deref_iterator(vec.end()),
ostream_iterator<int>(cout, " ")); // prints "1 2 3"
return 0;
}
``` | Try Boost's [`indirect_iterator`](http://www.boost.org/doc/libs/1_37_0/libs/iterator/doc/indirect_iterator.html).
An `indirect_iterator` has the same category as the iterator it is wrapping. For example, an `indirect_iterator<int**>` is a random access iterator. | Assuming your actual use case is a bit more complex than a container of integer pointers!
You could check out the boost ptr containers
<http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/reference.html>
The containers contain dynamically allocated objects (ie pointers).
But all access to the objects (direct or via iterator) returns a reference to the object.
```
#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
boost::ptr_vector<int> vec;
vec.push_back(new int(1));
vec.push_back(new int(2));
vec.push_back(new int(3));
copy(vec.begin(),vec.end(),
ostream_iterator<int>(std::cout, " ")); // prints "1 2 3 "
return 0;
}
``` | Is there a dereference_iterator in the STL? | [
"",
"c++",
"stl",
"iterator",
""
] |
Unlike C++, in C# you can't overload the assignment operator.
I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...
Here's an example:
```
Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference
```
Is there a workaround for that issue? | It's still not at all clear to me that you really need this. Either:
* Your Number type should be a struct (which is probable - numbers are the most common example of structs). Note that all the types you want your type to act like (int, decimal etc) are structs.
or:
* Your Number type should be immutable, making every mutation operation return a new instance, in which case you don't need the data to be copied on assignment anyway. (In fact, your type should be immutable whether or not it's a struct. Mutable structs are evil, and a number certainly shouldn't be a mutable reference type.) | you can use the 'implicit' keyword to create an overload for the assignment:
Suppose you have a type like Foo, that you feel is implicitly convertable from a string.
You would write the following static method in your Foo class:
```
public static implicit operator Foo(string normalString)
{
//write your code here to go from string to Foo and return the new Foo.
}
```
Having done that, you can then use the following in your code:
```
Foo x = "whatever";
``` | Is there a workaround for overloading the assignment operator in C#? | [
"",
"c#",
"operator-overloading",
""
] |
Is there any built-in utility or helper to parse `HttpContext.Current.User.Identity.Name`, e.g. `domain\user` to get separately domain name if exists and user?
Or is there any other class to do so?
I understand that it's very easy to call `String.Split("\")` but just interesting | This is better (*easier to use, no opportunity of `NullReferenceExcpetion` and conforms MS coding guidelines about treating empty and null string equally*):
```
public static class Extensions
{
public static string GetDomain(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop) : string.Empty;
}
public static string GetLogin(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
}
}
```
Usage:
```
IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();
```
This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation. | `System.Environment.UserDomainName` gives you the domain name only
Similarly, `System.Environment.UserName` gives you the user name only | Built-in helper to parse User.Identity.Name into Domain\Username | [
"",
"c#",
"asp.net",
".net",
"authentication",
"active-directory",
""
] |
I am looking into building an **authentication** in my ASP.NET application with the following requirements.
* A user has exactly one Role (i.e. Admin, SalesManager, Sales, ....)
* A role has a set of permissions to CRUD access a subset of existing objects. I.e.
"Sales has CREAD, READ, WRITE permission on object type "Products" but not DELETE"
* Somehow I like the permissions to be in a hierarchy with inheritance so that I for i.e. Admin don't need to specify all available objects.
* The system must quickly be able to answer the question "Does user X have permission to do Y to object Z"
* All database managed (MSSQL), implemented in C#/ASP.NET
I would like to get feedback on these requirements? Any ideas how to implement this using ASP.NET framework(as much as possible)? (However, I'm also interested to know how this can be achieved without Memberships) | I think what you need to do here is implement a set of permissions query methods in either your business objects or your controller. Examples: CanRead(), CanEdit(), CanDelete()
When the page renders, it needs to query the business object and determine the users authorized capabilities and enable or disable functionality based on this information. The business object can, in turn, use Roles or additional database queries to determine the active user's permissions.
I can't think of a way to declaratively define these permissions centrally. They need to be distributed into the implementation of the functions. If you want do improve the design, however, you could use dependency injection to insert authorizers into your business objects and thus keep the implementations separate.
There's some code that uses this model in Rocky Lhotka's book. The new version isn't in [Google](http://books.google.com/books?id=AS7zAQaKt-oC&pg=PA303&lpg=PA303&dq=ApplyAuthorizationRules()&source=web&ots=KAM2jFW5DR&sig=CH2iXpBw1K5i5zSnyA8sEJWjKlM&hl=en&sa=X&oi=book_result&resnum=7&ct=result) yet. | I think one of the best implementations that I think will fulfill your requirements is documented [here](http://www.codeproject.com/KB/web-security/objectlevelsecurity.aspx). The only issue is that this hooks into NHibernate, but you can use this as a template to create your own permissions implementation and simply hook into your own event model rather than that of NHibernates Interceptors.
I am working on such a system myself and will blog it once I am happy with it. | ASP.NET: Permission/authentication architecture | [
"",
"c#",
"asp.net",
"security",
"forms-authentication",
""
] |
I'm trying to launch another process from a service (it's a console app that collects some data and writes it to the registry) but for some reason I can't get it to launch properly.
I basics of what I'm am trying to do is as follows:
1. Launch the process
2. Wait for the process to finish
3. Retrieve the return code from the process
I am currently using the following code:
```
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(PATH, ARGS, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
::WaitForSingleObject(processInfo.hProcess, INFINITE);
DWORD exit = 100;
GetExitCodeProcess(processInfo.hProcess, &exit);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
return exit;
}
```
Upon calling CreateProcess(), it succeeds and enters the body of the if statement. The call to WaitForSingleObject returns immediately, which it should not, as the process should take approximately 20-30 seconds to finish. And, finally, calling GetExitCodeProcess() fails and does not set the value "exit".
FYI, this is code I have actually used elsewhere with success, just not in a service.
Could it be that it's being launched from a service and there are permissions issues??
**Edit:** I've now realized that it will actually launch the app (I can see it in TaskMan) but it seems to be stuck. It's there, but isn't doing anything.
Based on Rob Kennedy's [suggestion](https://stackoverflow.com/questions/318265/launching-a-process-from-a-service#318314), I fixed the process handle issue, and it actually does wait for the process to finish. But it never does finish unless I kill it manually. | `WaitForSingleObject` and `GetExitCodeProcess` expect the process handle itself, not a pointer to the process handle. Remove the ampersands.
Also, check the return values and call `GetLastError` when they fail. That will help you diagnose future problems. Never assume an API function will always succeed.
Once you call the functions right, and the new process starts but makes no progress, you can be reasonably certain that *this* code is not the culprit. The problem lies in the new process, so focus your debugging tasks there, not in the service process. | Following the update and edit, this sounds like one of many possible gotchas when launching a process from a service. Is there any possibility - any whatsoever - that your external process is waiting for user interaction? There are three major examples I can think of, one for instance would be a command-line application which might under some circumstances require keyboard input (for example, something like "cmd /c del \*.\*" would require user confirmation). The other examples would apply if the application needed a window, and is displaying it but you can't see it. If that's the case, you might wish to set your service to "interact with desktop" while debugging, and then be able to see either the application window (or an unexpected Windows error message such as being unable to find a DLL or similar).
If this helps you to debug or not, usually the "a-ha!" moment comes from realizing that things such as environment variables, path, current directory, and so on aren't perhaps what you'd expect from within your service. Permissions are not the most common reason for this kind of problem. Could you provide some details about the external application you're trying to launch, perhaps that would help in thinking this out. | Launching a Process from a Service | [
"",
"c++",
"service",
"createprocess",
""
] |
The following SQL separates tables according to their relationship. The problem is with the tables that sort under the 3000 series. Tables that are part of foreign keys and that use foreign keys. Anyone got some clever recursive CTE preferably or a stored procedure to do the necessary sorting?? Programs connectiong to the database are not considered a solution.
Edit: I posted the answer in the "answers" based on the first solution
Free "right answer" to be had for anyone reposting my own "right" answer!
```
WITH
AllTables(TableName) AS
(
SELECT OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id)
FROM dbo.sysobjects so
INNER JOIN sys.all_columns ac ON
so.ID = ac.object_id
WHERE
so.type = 'U'
AND
ac.is_rowguidcol = 1
),
Relationships(ReferenceTableName, ReferenceColumnName, TableName, ColumnName) AS
(
SELECT
OBJECT_SCHEMA_NAME (fkey.referenced_object_id) + '.' +
OBJECT_NAME (fkey.referenced_object_id) AS ReferenceTableName
,COL_NAME(fcol.referenced_object_id,
fcol.referenced_column_id) AS ReferenceColumnName
,OBJECT_SCHEMA_NAME (fkey.parent_object_id) + '.' +
OBJECT_NAME(fkey.parent_object_id) AS TableName
,COL_NAME(fcol.parent_object_id, fcol.parent_column_id) AS ColumnName
FROM sys.foreign_keys AS fkey
INNER JOIN sys.foreign_key_columns AS fcol ON
fkey.OBJECT_ID = fcol.constraint_object_id
),
NotReferencedOrReferencing(TableName) AS
(
SELECT TableName FROM AllTables
EXCEPT
SELECT TableName FROM Relationships
EXCEPT
SELECT ReferenceTableName FROM Relationships
),
OnlyReferenced(Tablename) AS
(
SELECT ReferenceTableName FROM Relationships
EXCEPT
SELECT TableName FROM Relationships
),
-- These need to be sorted based on theire internal relationships
ReferencedAndReferencing(TableName, ReferenceTableName) AS
(
SELECT r1.Tablename, r2.ReferenceTableName FROM Relationships r1
INNER JOIN Relationships r2
ON r1.TableName = r2.ReferenceTableName
),
OnlyReferencing(TableName) AS
(
SELECT Tablename FROM Relationships
EXCEPT
SELECT ReferenceTablename FROM Relationships
)
SELECT TableName, 1000 AS Sorting FROM NotReferencedOrReferencing
UNION
SELECT TableName, 2000 AS Sorting FROM OnlyReferenced
UNION
SELECT TableName, 3000 AS Sorting FROM ReferencedAndReferencing
UNION
SELECT TableName, 4000 AS Sorting FROM OnlyReferencing
ORDER BY Sorting
``` | Thank you for a working solution NXC. You put me on the right track to solve the problem using a recursive CTE.
```
WITH
TablesCTE(TableName, TableID, Ordinal) AS
(
SELECT
OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,
so.id AS TableID,
0 AS Ordinal
FROM dbo.sysobjects so INNER JOIN sys.all_columns ac ON so.ID = ac.object_id
WHERE
so.type = 'U'
AND
ac.is_rowguidcol = 1
UNION ALL
SELECT
OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,
so.id AS TableID,
tt.Ordinal + 1 AS Ordinal
FROM
dbo.sysobjects so
INNER JOIN sys.all_columns ac ON so.ID = ac.object_id
INNER JOIN sys.foreign_keys f
ON (f.parent_object_id = so.id AND f.parent_object_id != f.referenced_object_id)
INNER JOIN TablesCTE tt ON f.referenced_object_id = tt.TableID
WHERE
so.type = 'U'
AND
ac.is_rowguidcol = 1
)
SELECT DISTINCT
t.Ordinal,
t.TableName
FROM TablesCTE t
INNER JOIN
(
SELECT
TableName as TableName,
Max (Ordinal) as Ordinal
FROM TablesCTE
GROUP BY TableName
) tt ON (t.TableName = tt.TableName AND t.Ordinal = tt.Ordinal)
ORDER BY t.Ordinal, t.TableName
```
For thoose wondering what this is useable for: I will use it to safely empty a database without violating any foreign key relations. (By truncating in descending order)
I will also be able to safely fill the tables with data from another database by filling the tables in ascending order. | My rendition with moderate tweaks: This one is SQL-2005+ and works on databases without the "rowguidcol":
```
WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS
(
SELECT
OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,
OBJECT_NAME(so.object_id) AS TableName,
so.object_id AS TableID,
0 AS Ordinal
FROM
sys.objects AS so
WHERE
so.type = 'U'
AND so.is_ms_Shipped = 0
UNION ALL
SELECT
OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,
OBJECT_NAME(so.object_id) AS TableName,
so.object_id AS TableID,
tt.Ordinal + 1 AS Ordinal
FROM
sys.objects AS so
INNER JOIN sys.foreign_keys AS f
ON f.parent_object_id = so.object_id
AND f.parent_object_id != f.referenced_object_id
INNER JOIN TablesCTE AS tt
ON f.referenced_object_id = tt.TableID
WHERE
so.type = 'U'
AND so.is_ms_Shipped = 0
)
SELECT DISTINCT
t.Ordinal,
t.SchemaName,
t.TableName,
t.TableID
FROM
TablesCTE AS t
INNER JOIN
(
SELECT
itt.SchemaName as SchemaName,
itt.TableName as TableName,
itt.TableID as TableID,
Max(itt.Ordinal) as Ordinal
FROM
TablesCTE AS itt
GROUP BY
itt.SchemaName,
itt.TableName,
itt.TableID
) AS tt
ON t.TableID = tt.TableID
AND t.Ordinal = tt.Ordinal
ORDER BY
t.Ordinal,
t.TableName
``` | SQLServer: How to sort table names ordered by their foreign key dependency | [
"",
"sql",
"sql-server",
"database",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.