Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
This is one of the headers I found in WxWidgets and I like it.
I wonder if there is a way to insert in all my source files a header like this and maintain it automatically updated?
It includes two properties of SVN which I am aware of.
```
/////////////////////////////////////////////////////////////////////////////
// Name: <filename>.cpp
// Purpose:
// Author: <AuthorName>
// Modified by:
// Created: $Date$
// RCS-ID: $Id$
// Copyright: (c) <Year> <AuthorName>
// Licence: <licensetype>
/////////////////////////////////////////////////////////////////////////////
``` | It depends in part on which VCS you use. For my own work, I used SCCS up until 1999, but switched to RCS to avoid problems with Y2K (the SCCS date format uses 2 digits for the year, which I find unacceptable). As a result, I have a strong view on how to make reasonably sane use of those systems. Somewhere in SO I have already discussed what goes in my file headers, but it is simpler to find an illustration than that other answer...
```
/*
@(#)File: $RCSfile: stderr.c,v $
@(#)Version: $Revision: 9.14 $
@(#)Last changed: $Date: 2009/07/17 19:00:58 $
@(#)Purpose: Error reporting routines
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1988-91,1996-99,2001,2003,2005-09
@(#)Product: :PRODUCT:
*/
```
This is one of my oldest source files - migrated from SCCS to RCS. The VCS (that is, RCS) automatically maintains the values of the $RCSfile$, $Revision$, and $Date$ values. I have a shell script that drives a Perl script to maintain the Copyright dates; I need to remember to use it the first time I edit the file in any given year. I have not bothered, yet, to make a filter script that just hacks the copyright line (which is moderately unusual for me - I make lots of scripts). That file is in its "undistributed" format; when I distribute it with a product, the ':PRODUCT:' meta-keyword is expanded to name the relevant product (by my release building software). Clearly, neither my name nor the purpose of the file needs much maintenance. (As an aside, I still prefer the SCCS way of managing keywords - the SCCS equivalents of $RCSfile$ etc.)
Where the version control system does not intrinsically support the keywords, it is much harder to decide how to handle such information. The first rule is "don't fight against your VCS". War story - we tried fighting the VCS and it didn't work. Once upon a long time ago (a decade and a half ago), the company switched from SCCS to Atria Clearcase (now IBM Rational ClearCase). ClearCase does not support the embedding of version information into source files. It does support checkin triggers. We wrote and deployed a trigger to ensure that the ClearCase version numbers were embedded in the files like the SCCS version numbers had been before. The checkin trigger worked fine; we could look at the file, inside or outside the view, and see which version it belonged to. But the changes in the version numbers broke the merging code - all merges became manual merges, even if the only conflict was in the version number. This was because we were fighting the VCS and it wasn't willing to let us win. So, we ended up abandoning the checkin trigger.
I am still trying to work out how to handle version stamping source files with a modern DVCS such as git. It looks like I'm going to have to rework my entire release system - probably as a hybrid that covers both SCCS and RCS (as now, though the SCCS part hasn't been used for most of a decade) as well as git.
One theory, used by many people, is that you should avoid building metadata into source files. I remain to be wholly convinced that this is good - I think it is helpful to see the origin of a source file even when it is divorced from its original context (has been renamed, removed from its original package, modified, and included in some new product). I may yet have to live with this viewpoint when using a DVCS.
My theory, used by me but not necessarily by anyone else, is that metadata should be in files because they are not always used in their original context and the metadata can survive and help identify its origins, even decades later. So, when I'm building a source code release, I use my release software to automatically edit in the product information, using the :PRODUCT: etc notations to mark what should be edited. You can see this at work if you download any of the packages I've contributed to the [IIUG](http://www.iiug.org/software) (International Informix Users Group) web site. I'd recommend SQLCMD as probably the biggest and most recent package - though it has been available there since the mid-90s and version 23 or so (currently on version 86.00).
One of the biggest problems I face with git is that almost all my programs use the code in stderr.c and stderr.h. However, it is not yet clear to me how I go about incorporating the same code in each of the many products that use it, without going in for multiple maintenance of it. This is far from being the only pair of source files which I use unchanged in many different products. But I don't want to build the entire library with each product - the library would be bigger than many of the products, and any given product only uses a few of the files from the library. ...Ah well, one day, enlightenment will come...
I disagree with the comments that the name of the file is not metadata worth keeping in the file. I think it is worth keeping - because the name can change when the contents don't, and it is easier to see where it came from if the metadata is there. Of course, the malicious can tamper with (or remove) the metadata - but they often don't. | One option would be to put a pre-commit hook in your Subversion server that checks that the header exists. There's nothing you can really do to make sure it's kept up to date though, beyond self and team discipline; you could check some of them automatically (e.g. Created, Modified by, etc), but you could use Subversion properties for those in the first place, and the rest are judgment calls. How could you automatically update the file's purpose?
Generally speaking though, I'm not very fond of this sort of thing. You already know the file's name (duh), author, modifier, creation date, etc: just ask Subversion. Putting all this at the top of the file wastes space at best, and can be wrong at worst. The file's purpose tends to be useful, but you have to be sure to keep it updated, which is more a question of coding style than anything. | Auto updated header comments in C++ | [
"",
"c++",
"header",
"comments",
""
] |
Is there a way of accessing the width of a DOM element? In particular, I'm looking to get the width of a table cell (td) who's width can be of varying lengths based on the length of the text in that cell.
ideally, the solution I'm looking for will use the jQuery library, but others will work as well.
Also, I must stress that the solution must work in IE6 (unfortunately :-P ) in addition to ie7, ie8, and firefox. Thanks in advance!! | `$(selector).width()` should work fine, but make sure for IE6 and below that the page is rendered in Standards mode and not Quirks-Mode (so it follows W3C box model).
Here is some information on how to toggle Standard/Strict Mode:
> [CSS - Quirks mode and strict mode](http://www.quirksmode.org/css/quirksmode.html) | ```
$('#td_id').width();
```
Of course you'll have to craft the selector to work with the cell in question, but otherwise it's that easy! | Get the width of a DOM element? | [
"",
"javascript",
"jquery",
"dom",
""
] |
I have nested groupboxes, which logically represent nested data structures in my application. Let's say i have a structure like this:
```
Dev1
- CDev1
- CDev2
- ICDev1
- ICDev2
```
I have checkboxes to enable/disable each of these Devs. I want to bind the CheckState of the child checkboxes to the parent checkbox's CheckState. I want the mechanism to work like this: When i check CDev2, ICDev1 & ICDev2 get automatically checked. But when I uncheck ICDev1, CDev2 stays in its own state. Basically, i want these events to be propagated to children but not to parent, like one way binding.
I am using .Net 2.0 SP2. I don't know if this is possible or not, therefore i would be glad if you show me some pointers about this. If it's not possible, i am going to implement event handlers for all checkboxes. | Try this:
```
childCheckBox.DataBindings.Add("Checked", parentCheckBox, "Checked");
```
You might also want to take a look at the `TreeView` control, it has the option to display `CheckBox` next to each item. | This is theoretically possible using two-way binding in WPF (here's a [tutorial on data binding in WPF](http://msdn.microsoft.com/en-us/library/aa480224.aspx)). I don't think you can do it automatically using WinForms. If you're using WinForms, you'll have to catch and handle events to manually modify state changes of that sort. | Binding a property to another property | [
"",
"c#",
"binding",
".net-2.0",
""
] |
I'd like to be able to declare an array as a function argument in C++, as shown in the example code below (which doesn't compile). Is there any way to do this (other than declaring the array separately beforehand)?
```
#include <stdio.h>
static void PrintArray(int arrayLen, const int * array)
{
for (int i=0; i<arrayLen; i++) printf("%i -> %i\n", i, array[i]);
}
int main(int, char **)
{
PrintArray(5, {5,6,7,8,9} ); // doesn't compile
return 0;
}
``` | If you're using older C++ variants (pre-C++0x), then this is not allowed. The "anonymous array" you refer to is actually an *initializer list*. Now that C++11 is out, this can be done with the built-in `initializer_list` type. You theoretically can also use it as a C-style initializer list by using `extern C`, *if your compiler parses them as C99 or later*.
For example:
```
int main()
{
const int* p;
p = (const int[]){1, 2, 3};
}
``` | It's allowed with a typecast in C++11 and in `extern "C"` with C99:
```
void PrintArray(size_t len, const int *array)
{
for(size_t i = 0; i < len; i++)
printf("%d\n", array[i]);
}
int main(int argc, char **argv)
{
PrintArray(5, (const int[]){1, 2, 3, 4, 5});
return 0;
}
``` | Is there any way to pass an anonymous array as an argument in C++? | [
"",
"c++",
"arrays",
"arguments",
""
] |
Within a namespace I have a utility class that is only functional to a main class I'm exposing. How can I hide it away? | Make your class **internal** and work with different assemblies or make it a **private nested** class of your main class.
```
public class A
{
private class B { ... }
...
}
``` | If it is only going to be used internally - within this "main class" - then it would seem most appropiate to nest it.
In other words, your structure would look like:
```
public class MainClass
{
// ...
private class NestedUtilityClass
{
// ...
}
}
```
This way, it's only accessible from *within `MainClass`*. You could change the modified of the nested class to be `protected` if you need it to be available in derived classes, of course. | Protecting class in a namespace | [
"",
"c#",
""
] |
I'm designing a UI, and I found myself itching my head : how can I align a TextBox text and a label text, which are side by side.
In design mode, it's easy, you move one with your mouse, a purple line appears and voila ! the alignment is good, but mine are code generated, so how can i align their contents ?
Thank you !
**Edit** : Layout is something I can't use (I don't make the rules, my boss do..) | I like to use the `FlowLayoutPanel` (instead of the `TableLayoutPanel`) for this purpose because you don't need to fiddle with columns. **Remember** to remove both the Top and the Bottom anchors on every control to make them vertically centered, and set FlowLayoutControl.AutoSize = true and AutoSizeMode = GrowAndShrink.
**Edit**: regarding your restriction that "Layout is something I can't use": so you want instead to access the purple text baseline snapline position programmatically, at runtime? This is possible, but it's unlikely to be faster than layouts because only the *designer* for the control knows where it is, so you will have to create designers for all controls you need this for.
[This question](https://stackoverflow.com/questions/93541/baseline-snaplines-in-custom-winforms-controls) has some code that can be used as a starting point, but as I said, it's probably not the right approach either given the performance constraints. | Take a look at the TableLayoutPanel. Still not so easy to get the baseline match but by vertically centering the label and setting the Rows to AutoSize you will get something that is ordered and flexible. | Align TextBox and Label text | [
"",
"c#",
".net",
"layout",
"alignment",
""
] |
Example:
```
>>> convert('CamelCase')
'camel_case'
``` | ## Camel case to snake case
```
import re
name = 'CamelCaseName'
name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
print(name) # camel_case_name
```
If you do this many times and the above is slow, compile the regex beforehand:
```
pattern = re.compile(r'(?<!^)(?=[A-Z])')
name = pattern.sub('_', name).lower()
```
To handle more advanced cases specially (this is not reversible anymore):
```
def camel_to_snake(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
print(camel_to_snake('camel2_camel2_case')) # camel2_camel2_case
print(camel_to_snake('getHTTPResponseCode')) # get_http_response_code
print(camel_to_snake('HTTPResponseCodeXYZ')) # http_response_code_xyz
```
To add also cases with two underscores or more:
```
def to_snake_case(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
return name.lower()
```
## Snake case to pascal case
```
name = 'snake_case_name'
name = ''.join(word.title() for word in name.split('_'))
print(name) # SnakeCaseName
``` | There's an [inflection library](https://pypi.python.org/pypi/inflection) in the package index that can handle these things for you. In this case, you'd be looking for [`inflection.underscore()`](http://inflection.readthedocs.org/en/latest/#inflection.underscore):
```
>>> inflection.underscore('CamelCase')
'camel_case'
``` | Elegant Python function to convert CamelCase to snake_case? | [
"",
"python",
"camelcasing",
""
] |
I have a small Java desktop app that uses Swing. There is a data entry dialog with some input fields of different types (JTextField, JComboBox, JSpinner, JFormattedTextField). When I activate the JFormattedTextFields either by tabbing through the form or by clicking it with the mouse, I would like it to select all the text that it currently contains. That way, users could just start typing and overwrite the default values.
How can I do that? I did use a FocusListener/FocusAdapter that calls selectAll() on the JFormattedTextField, but it doesn't select anything, although the FocusAdapter's focusGained() method is called (see code sample below).
```
private javax.swing.JFormattedTextField pricePerLiter;
// ...
pricePerLiter.setFormatterFactory(
new JFormattedTextField.AbstractFormatterFactory() {
private NumberFormatter formatter = null;
public JFormattedTextField.AbstractFormatter
getFormatter(JFormattedTextField jft) {
if (formatter == null) {
formatter = new NumberFormatter(new DecimalFormat("#0.000"));
formatter.setValueClass(Double.class);
}
return formatter;
}
});
// ...
pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
pricePerLiter.selectAll();
}
});
```
Any ideas? The funny thing is that selecting all of its text apparently is the default behavior for both JTextField and JSpinner, at least when tabbing through the form. | Wrap your call with SwingUtilities.invokeLater so it will happen after all pending AWT events have been processed :
```
pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
pricePerLiter.selectAll();
}
});
}
});
``` | In addition to the above, if you want this for all text fields you can just do:
```
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
{
public void propertyChange(final PropertyChangeEvent e)
{
if (e.getNewValue() instanceof JTextField)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JTextField textField = (JTextField)e.getNewValue();
textField.selectAll();
}
});
}
}
});
``` | How to select all text in a JFormattedTextField when it gets focus? | [
"",
"java",
"user-interface",
"swing",
""
] |
Is there a way to convert an `enum` to a list that contains all the enum's options? | This will return an `IEnumerable<SomeEnum>` of all the values of an Enum.
```
Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
```
If you want that to be a `List<SomeEnum>`, just add `.ToList()` after `.Cast<SomeEnum>()`.
To use the Cast function on an Array you need to have the `System.Linq` in your using section. | Much easier way:
```
Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.Select(v => v.ToString())
.ToList();
``` | How do I convert an enum to a list in C#? | [
"",
"c#",
".net",
"enums",
""
] |
Given the following classes (lets pretend they are populated), how would you find the minimum value of any `val` for an instance of `test1`?
```
public class test1
{
public int val;
public List<test2> Tests;
}
public class test2
{
public int val;
public List<test3> Tests;
}
public class test3
{
public int val;
public List<test4> Tests;
}
public class test4
{
public int val;
}
``` | You could write a method in the top-level class to flatten the structure out into an IEnumerable.
```
public IEnumerable<int> FlattenVal()
{
yield return this.val;
foreach (var t2 in this.Tests)
{
yield return t2.val;
foreach (var t3 in t2.Tests)
{
yield return t3.val;
foreach (var t4 in t3.Tests)
{
yield return t4.val;
}
}
}
}
```
then you could call it like this:
```
var t = new Test1();
Console.WriteLine(t.FlattenVal().Min());
```
If you cant add the method directly to the class (non-partial, code generated, or in a library), then you could use an extension method:
```
public static IEnumerable<int> FlattenVal(this Test1 t1)
{
yield return t1.val;
foreach (var t2 in t1.Tests)
{
yield return t2.val;
foreach (var t3 in t2.Tests)
{
yield return t3.val;
foreach (var t4 in t3.Tests)
{
yield return t4.val;
}
}
}
}
``` | Non-recursive (and non-tested) solution:
```
int minVal(test1 t1) {
int min = t1.val;
foreach (test2 t2 in t1.Tests) {
min = Math.Min(min, t2.val);
foreach (test3 t3 in t2.Tests) {
min = Math.Min(min, t3.val);
foreach (test4 t4 in t3.Tests) {
min = Math.Min(min, t4.val);
}
}
}
return min;
}
``` | Find Minimum value in class hierarchy | [
"",
"c#",
""
] |
I'm learning *C++*, and I want to know from those who are very good developers now: What is the best IDE, *Visual C++ 2008 Express* or *Eclipse Ganymede* with *CDT*? Remember that I'm using *Microsoft Windows Vista Ultimate*. Thanks!
The book that I'm reading is from Deitel: [C++ How to Program, 5/e](http://www.deitel.com/books/cpphtp5/), because I don't know if the code of the book supports *Microsoft Visual C++ 2008 Express*. | I'm using both regularly now.
Visual studio is easier and more user friendly. I have issues with it though. They force you to do a number of things for reasons the benefit Microsoft and not you. It's free so you can't complain that much. Support is non existent but there's google for help.
Eclipse Gallileo does some difficult things startlingly well, but does some simple stuff startlingly badly. Such as when you compile if there's an error you get no visual indication. You have to open the problems window to see the errors. DOH! Eclipse is nearly as good as visual studio overall and is one of the best when using linux. The new version of the debugger has some very nice new features as well. Support is poor to non existent but there's google for help.
I tried codeblocks. The support was not very good to rude. I found it difficult to do anything serious with. | If you're working on Windows, MSVC++ 2008 Express is probably the one to go with, since it's the platform's native compiler. If you don't have any experience with Eclipse already, definitely go with MSVC. I've found Eclipse to be very counter-intuitive, but that's me, you may love it. | Visual C++ 2008 Express Or Eclipse Ganymede With CDT | [
"",
"c++",
"eclipse",
"visual-c++",
"eclipse-cdt",
""
] |
For example I have the following tables resulting from:
```
CREATE TABLE A (Id int, BId int, Number int)
CREATE TABLE B (Id int, Number decimal(10,2))
GO
INSERT INTO A VALUES(1, 3, 10)
INSERT INTO B VALUES(3, 50)
INSERT INTO A VALUES(2, 5, 20)
INSERT INTO B VALUES(5, 671.35)
GO
```
And I run the following query multiple times:
```
SELECT * FROM A INNER JOIN B ON A.BId = B.Id
```
I should get something like:
```
ID BId Number ID Number
1 3 10 3 50.00
2 5 20 5 671.35
```
But is it possible for A.Number and column B.Number be in different position (also ID in that respect) so I'll get something like:
```
ID Number ID BId Number
3 50.00 1 3 10
5 671.35 2 5 20
```
We are currently experiencing some weird problem that might be resulting from something like this. We have an ASP.NET application, executing a custom reflection based code generated data mapper that is connecting to SQL Server 2008 cluster.
We found sometimes that we get an error like so:
**Object of type 'System.Decimal' cannot be converted to type 'System.Int32'**
Trying to figure out if this is a behaviour in SQL Server or it's something in the reflection based data mapper engine.
As you can see the field names are the same in the two tables. Thinking perhaps when we tried to do DataReader.GetValue(DataReader.GetOrdinal("Number")), it will return B.Number which is a decimal instead of A.Number which is an int.
To complicate the matter further, this only happen intermittently (but consistently after it happened once on a particular IIS web server in a web farm only).
Say Web Server A is doing okay up until 2:00pm and suddenly, we got this error and we'll keep getting that error on Web Server A until we reset IIS on that server and then it will be okay again.
Something to do w/ connection pooling and how SQL query plan cache perhaps? | The second scenario is possible only if you interchange table orders.
Something like SELECT \* FROM B INNER JOIN A ON A.BId = B.Id.
Otherwise its not possible. | SQL is a relational algebra - the standard does not specify what order columns will be returned in if you don't explicitly state the order yourself.
I tend to avoid `"select *"` as much as possible since it can clog up the network with unnecessary traffic and makes it harder to catch things like column renames and ordering until it's too late.
Just select the columns you actually need.
For your specific case, I would also just return the shared ID once since it has to be equal due to your join (I tend to prefer the "old" style as the DBMS should be smart enough to optimize this to an inner join anyway):
```
select
a.Id as Id,
a.BId as BId,
a.Number as Number,
b.Number as BNumber
from
a, b
where
a.BId = b.Id
``` | Is it possible for the data to be returned in different column order between execution when you run SELECT * FROM multiple table joins multiple times? | [
"",
"sql",
"sql-server-2008",
"reflection",
"ado.net",
""
] |
I would like to have a link on my site that when you click it a site segment that hovers above the content appears and displays some information until it is closed in some way, and I would like to be able to insert anything I want to in there- text, images, CSS formatting, etc.
What language should I use for this? Do you know any sites that do this? Also a link to relevant libraries would be appreciated. | javascript is used for such client side tasks such as this. The library jquery will be imensensly helpful. Basically what happens is when you hover your mouse over an image (or whatever you like) a div gets its display property switched and is positioned at the appropriate coordinates. Since this is a div, you can insert into it anything you would have in a webpage, images, CSS, flash, or whatever you like. | Check out [Prototype Window Xilinus](http://prototype-window.xilinus.com/samples.html). They have exactly you're looking for. | How to create a hovering pop up | [
"",
"javascript",
"html",
"popup",
"hover",
""
] |
I would like to get the number of availableProcessors from with my Ant build script (i.e. value that is returned from Runtime.getRuntime().availableProcessors(). Is there an existing property that contains this value or do I have to write a custom ant task? | [write your custom ant task](http://ant.apache.org/manual/develop.html), is simple as write a class | [This post by Ilia Chemodanov](http://www.iliachemodanov.ru/en/blog-en/15-tools/ant/48-get-number-of-processors-in-ant-en) explains two solutions nicely.
If you don't want to compile and import a Java class you can **do it in pure ant:** (though it is pretty hacky)
```
<target name="get-cores">
<property environment="env"/>
<!-- support for Windows -->
<condition property="cores.count" value="${env.NUMBER_OF_PROCESSORS}">
<os family="windows" />
</condition>
<!-- support for Linux and Solaris (package SUNWgnu-coreutils is required) -->
<exec executable="nproc" outputproperty="cores.count" os="Linux,SunOS,Solaris">
<arg value="--all"/>
</exec>
<!-- support for Mac OS X -->
<exec executable="sysctl" outputproperty="cores.count" os="Mac OS X">
<arg value="-n"/>
<arg value="hw.ncpu"/>
</exec>
<echo message="Number of cores: ${cores.count}"/>
</target>
``` | How can I get the number of availableProcessors in Ant | [
"",
"java",
"ant",
""
] |
I have some simple javascript that as far as i can tell should work but doesn't.
The code is below
```
var presenter = new Practicum.Web.TEI.StudentPlacement2009.CreateLetter_class(); //this is a class generated by Ajax.Net
function GetLetters() {
var GetLettersParams = new Object();
GetLettersParams.TemplateType = $('#LetterTypes').val();
var letters = ajaxCall(presenter.GetLetters, GetLettersParams);
createOptions('Templates', letters, 'Id', 'Name', true);
}
function ajaxCall(ajaxMethod, parameters) {
var response = ajaxMethod.call(parameters); //fails here with the message in
if (response.error != null) {
alert('An error has occured\r\n' + response.error.Message);
return;
}
return response.value;
}
```
this is part of the class Ajax.Net produces.
```
Practicum.Web.TEI.StudentPlacement2009.CreateLetter_class = function() {};
Object.extend(Practicum.Web.TEI.StudentPlacement2009.CreateLetter_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
GetLetterTypes: function() {
return this.invoke("GetLetterTypes", {}, this.GetLetterTypes.getArguments().slice(0));
},
GetDegrees: function() {
return this.invoke("GetDegrees", {}, this.GetDegrees.getArguments().slice(0));
},
GetLetters: function(getLettersParams) {
return this.invoke("GetLetters", {"getLettersParams":getLettersParams}, this.GetLetters.getArguments().slice(1));
} ...
```
Any help would be much appriciated;
Colin G | The first parameter that needs to be passed to [`Function.call()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) is the object on which the function is called. Then follow the function parameters as separate values:
```
func.call(someobj, param1, param2, ...);
```
To call a function with an array of arguments you should use [`apply()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply). `apply()` also takes the object for which the method should be called as first parameter:
```
func.apply(someobj, params);
```
So in your case it would look something like this:
```
function ajaxCall(ajaxMethod, obj, parameters) {
var response = ajaxMethod.call(obj, parameters);
// ...
}
var letters = ajaxCall(presenter.GetLetters, presenter, GetLettersParams);
``` | You need to pass an object to the first argument of the call method e.g.:
```
ajaxMethod.call(presenter, parameters);
```
See <http://www.webreference.com/js/column26/call.html> | Call a javascript function from outside its object | [
"",
"javascript",
"ajax",
"ajax.net",
""
] |
I have a windows forms application containing a datagridview control. The datagridview is populated by the contents of an xml file. At the moment, all of the columns are displayed as datagridviewtextboxcolumns. I want to select one that is populated by a particular xml tag and display it's content in a datagridviewcomboboxcolumn along with 2 other options.
EXAMPLE:
```
<SMS>
<Number>+447931663542</Number>
<DateTime>2009-07-12T17:00:02</DateTime>
<Message>YES</Message>
<FollowedUpBy>Unassigned</FollowedUpBy>
<Outcome>Resolved</Outcome>
</SMS>
```
The OUTCOME tag is the column that I would like to be displayed as a comboboxcolumn in the datagridview. If for example the tag is empty and contains no data, then I want to display nothing, but have the comboboxcolumn populated with 3 possible options to choose from (Unresolved, Resolved, Pending). If however the tag contains data, I want that particular item to be displayed in the comboboxcolumn, and have the other two options available to be selected.
Help in achieving this would be appreciated greatly!
Regards,
EDIT:
Currently I use this code:
```
colOutcome = new DataGridViewComboBoxColumn();
colOutcome.HeaderText = "Outcome";
colOutcome.Width = 90;
colOutcome.Items.AddRange("Resolved", "Unresolved", "Pending");
this.dataGridView1.Columns.Insert(1, colOutcome);
this.dataGridView1.Columns[1].Name = "OutcomeColumn";
```
This code above populates the combobox. THE PROBLEM IS: When The xml document populates the datagridview, the outcome column just appears as a textbox column, containing the data inbetween the outcome tags in the xml file. My point is, how can i get the datagridview to realise when it reads the outcome column that it needs to be changed into a combobox column and then display the data that way, along with the other potentially selectable options in the combobox?! Currently the datagridview gets populated with all columns as textboxcolumns containing the data, as well as a seperate combobox column which is not what I want. I need the application to merge the outcome column and its data with the code above.
Any ideas? | **Updated Answer**
You could pass in the XML document to a function that will loop through each node and determine whether it should be a ComboBox one or not i.e. if the name is "Outcome".
```
private void CreateColumns(XmlDocument doc)
{
foreach (...) // loop through each node in xml document
{
if (node.Name == "Outcome")
{
var items = new List<string>() { "Resolved", "Unresolved", "Pending" };
this.dataGridView1.Columns.Add(CreateComboBoxColumn(node.Name, items));
}
else
{
this.dataGridView1.Columns.Add(String.Format("col{0}", node.Name), node.Name);
}
}
}
```
Then your code for creating the Outcome column would be:
```
private DataGridViewComboBoxColumn CreateComboBoxColumn(string colHeaderText, List<string> items)
{
var colOutcome = new DataGridViewComboBoxColumn();
colOutcome.HeaderText = colHeaderText;
colOutcome.Width = 90;
colOutcome.Items.AddRange(items.ToArray());
colOutcome.Name = String.Format("col{0}", colHeaderText);
return colOutcome;
}
```
You would then just call CreateColumns on the form load event and pass in your XML. You should only need to create the columns once.
My advice would be to have a similar function that will find all the SMS elements and add a new row populating it with the information in each node.
```
public void MyForm_Load(object sender, EventArgs e)
{
var doc = new XmlDocument(filename);
CreateColumns(doc);
CreateRows(doc);
}
```
Hope that helps. | I'm not sitting in front of VS so this might not compile but should give you direction.
You need to either pre-populate the ResolvedColumn with the 3-4 possible values at design-time or assign it to another datasource at runtime. If you chose the design-time approach, simply open the DataGridView "Edit Columns" dialog, find the ResolvedColumn, go to Items, and add your values ("", "Unresolved", "Pending", "Resolved"). The empty value might help the ComboBox to render if there is the possiblity of rendering the grid with SMS records that have no Outcome.
To bind the possible options at runtime do something like this:
```
private List<string> _outcomeDataSource;
private void Form1_Load(object sender, EventArgs e)
{
_outcomeDataSource = new List<string>;
_outcomeDataSource.Add("");
_outcomeDataSource.Add("Unresolved");
_outcomeDataSource.Add("Pending");
_outcomeDataSource.Add("Resolved");
ResolvedColumn.DataSource = _outcomeDataSource;
ResolvedColumn.PropertyName = "Outcome";
}
``` | C# Datagridview - Convert TextColumn to ComboBoxColumn | [
"",
"c#",
"xml",
"winforms",
"datagridview",
""
] |
I am trying to embed a flash video into a custom setup of the tinyMCE editor. It is seperate from the main WordPress one, but it is still within the wordpress admin area.
The output code from a simple youtube embed block is as follows:
```
<p><img mce_src=\"../wp-content/themes/porcelain/tinymce/jscripts/tiny_mce/plugins/media/img/trans.gif\" src=\"../wp-content/themes/porcelain/tinymce/jscripts/tiny_mce/plugins/media/img/trans.gif\" width=\"560\" height=\"340\" style=\"\" class=\"mceItemFlash\" title=\""allowFullScreen":"true","allowscriptaccess":"always","src":"http://www.youtube.com/v/26Ywp6vUQMY&hl=en&fs=1&","allowfullscreen":"true"\"></p>
```
As you can see, it's escaping the quotes when I don't want it to...
Any help is massively appreciated, and I know this is a school boy error. I just need setting straight.
Thanks. | This often happens when you have code that escapes data before using it in SQL (as it should do) on a server that has php's [`magic_quotes`](http://php.net/magic_quotes) feature enabled. This feature causes php to automatically escape get and post data when it loads. If you then escape it again, things go wrong - it gets double escaped, so escaped data goes into the db.
PHP has now deprecated this feature, they realised it was a nuiscance, caused more pain than it saved - they were trying to build in security, but ultimately the developer needs to be aware of and work around security issues, rather than having them taken care of silently. Myself, I ended up regularly including code in stuff to detect if this was enabled and reverse it early in the execution if it was. | If you are transfering your data through $\_POST it is escaped if [magic\_quotes](http://php.net/manual/en/security.magicquotes.php) is enabled (it's deprecated now and automatically removed from PHP 5.4 and above). Just use [stripslashes()](http://php.net/manual/fr/function.stripslashes.php) if it's escaped, fixed my problems with HTML being escaped in wordpress using tinymce, at least. | tinyMCE & wordpress giving odd characters... tried combination of solutions | [
"",
"php",
"wordpress",
"tinymce",
""
] |
When mixing PHP and HTML, what is the proper indentation style to use? Do I indent so that the outputted HTML has correct indentation, or so that the PHP/HTML mix looks properly formatted (and is thus easier to read)?
For example, say I have a `foreach` loop outputting table rows. Which one below is correct?
**PHP/HTML mix looks correct:**
```
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
```
**Outputted HTML looks correct:**
```
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
```
I've found that when I run into this situation (quite frequently), I don't have a standard style to use. I know that there may not be a "correct" answer, but I'd love to hear thoughts from other developers. | The PHP and the HTML should each be indented so that they are correct with respect to themselves in source form, irrespective of each other and of outputted form:
```
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
``` | I often pondered this question too, but then I realized, who cares what the HTML output looks like? Your users shouldn't be looking at your HTML anyway. It's for *YOU* to read, and maybe a couple other developers. Keep the *source* code as clean as possible and forget about what the output looks like.
If you need to debug the output, use Chrome Developer Tools, Firebug, or even F12 Tools. | How to properly indent PHP/HTML mixed code? | [
"",
"php",
"html",
"indentation",
""
] |
I am trying to reduce fragmentation in all of the indexes for a database running on SQL Server 2005.
Currently I am trying to use ALTER INDEX in conjunction with sp\_MSforeachtable, to apply it to all of the indexes for all of the tables:
```
sp_MSforeachtable "ALTER INDEX ALL ON ? REBUILD;"
```
But for some reason this doesn’t always seem to work?
If I try it for a single index, or all of the indexes for a single table then the fragmentation is cleaned up, it just seems to be when I apply it to the whole database that I get problems.
Previously I might have used DBCC DBREINDEX but BOL states it will be removed in the next version of SQL Server, so I don’t want to use it.
Can anyone give me any advice on the best way to tackle cleaning up all of the indexes in a database?
Thanks | If you want to fully automate your SQL Server Index maintenance then I seriously recommend that you check out Michelle Ufford's stored procedure for this.
[Index Defrag Script V4.1](http://sqlfool.com/2011/06/index-defrag-script-v4-1/)
It is what I consider to be the best index maintenance script I have ever read.
One of the best features about this script are that you can customize the threshold values that you use in order to determine whether or not to REBUILD or REORGANIZE a given index strucutre.
It also provides the option to limit the number of CPU cores that are utilized by the procedure. An excellent option if you intend to run the script on a busy live production database.
Warning: As with all internet available code, be sure you test it thoroughly before using in a production environment. You will also most likely want to incorporate your own customisation and features too. | Check out the article and accompanying sample script to handle this task at SQL Fool (Michelle Ufford's website):
<http://sqlfool.com/2009/06/index-defrag-script-v30/>
This is quite a nice solution to handle this once and for all!
The best practice recommendation is to reorganize your index if you have 5-30% of fragmentation, and only rebuild it if it has more than 30% fragmentation. You can easily use these thresholds or specify your own using this script.
Marc | Best Approach for Reindexing | [
"",
"sql",
"sql-server",
"database",
"sql-server-2005",
""
] |
How can we prompt for a computer restart after install from within a C# custom action?
We are using VS 2005's setup project for our setup, and we need to programmatically decide to prompt for a restart (so it will not happen on every install, just on some).
UPDATE: We're looking for something that is already built into the MSI custom action system first. If that doesn't exist, we can resort to restarting the PC ourselves somehow, but would like to avoid that.
UPDATE: We see where you can set REBOOT=Force when edited the Msi in Orca, can you modify these tables from a C# custom action at runtime? We could set this to restart every time, but that might make our setup annoying (it will only need to restart on rare occasions).
UPDATE: We tried setting:
```
savedState["REBOOT"] = "Force";
```
From within the Install() method of our custom action, but no luck. It doesn't seem like the IDictionary, savedState really does anything.
Also tried:
```
Context.Parameters["REBOOT"] = "Force";
```
But I think this collection is just the command line arguments passed to the custom action.
UPDATE: Is there a way to edit our MSI with Orca to make this trick work? Maybe schedule a reboot on a condition of some file existing? We have not found how to set MSI properties from a C# custom action.
UPDATE: We tried hooking into AppDomain.ProcessExit and AppDomain.DomainUnload and starting a new thread and calling Process.GetCurrentProcess().WaitForExit() and none of those events will fire from within a C# custom action... | As it seems, the only way for us to solve this is to either:
A) Modify the MSI with orca to make the setup restart for every install
B) Redo the setup project with WiX or Install Shield
Thanks for the help guys. | You need to add or call the MSI custom action ScheduleReboot <http://msdn.microsoft.com/en-us/library/aa371527(VS.85).aspx> in your InstallExecuteSequence, . You can do this by using the MSI function MsiDoAction, <http://msdn.microsoft.com/en-us/library/aa370090(VS.85).aspx> inside a custom action. Please note that the custom action that schedules this must be an immediate custom action, not a deferred custom action. This means you will probably need to schedule it after InstallFinalize. You could also add it to the InstallExecuteSequence with a condition on a public property that your custom action sets. | Force Reboot from Custom Action in Msi in C# | [
"",
"c#",
"visual-studio",
"windows-installer",
"custom-action",
""
] |
How do I convert a string to an integer in JavaScript? | The simplest way would be to use the native `Number` function:
```
var x = Number("1000")
```
If that doesn't work for you, then there are the **parseInt**, **unary plus**, **parseFloat with floor**, and **Math.round** methods.
### parseInt()
```
var x = parseInt("1000", 10); // You want to use radix 10
// So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
```
### Unary plus
If your string is already in the form of an integer:
```
var x = +"1000";
```
### floor()
If your string is or might be a float and you want an integer:
```
var x = Math.floor("1000.01"); // floor() automatically converts string to number
```
Or, if you're going to be using Math.floor several times:
```
var floor = Math.floor;
var x = floor("1000.01");
```
### parseFloat()
If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.
```
var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
```
### round()
Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:
```
var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)
``` | Try parseInt function:
```
var number = parseInt("10");
```
But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.
```
parseInt(string, radix)
```
Example:
```
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
```
Note that `parseInt` ignores bad data after parsing anything valid.
This guid will parse as 51:
```
var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true
``` | How to convert a string to an integer in JavaScript | [
"",
"javascript",
"string",
"integer",
"data-conversion",
""
] |
The following listener will create an event entry when the Trace.WriteLine is called. If the source does not exist he will create it in the default log channel which is 'Application' . I want to specify another default Log channel but after searching for 45 minutes i don't seem to find the solution. Any ideas?
```
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="Source">
</add>
</listeners>
</trace>
</system.diagnostics>
</configuration>
``` | Not sure that you can via the config.
Though the EventLogTraceListener does accept a different eventlog as a parameter in the constructor. Unfortunately, the class is sealed so you can't simply derive from it and pass a different value for the constructor.
Though you could follow this approach and construct your own class(seems fairly simple). And then reference that type in your config.
<http://weblogs.asp.net/psteele/archive/2006/02/23/438936.aspx> | You could repoint the listener in the first line of code.
```
Trace.Listeners["MyListener"].Attributes["EventLog"] = ConfigurationManager.AppSettings["MyCustomEventLogName"];
```
The value can be stored in the `<appSettings>` section of the config file so it's still configuration based:
```
<appSettings>
<add key="MyCustomEventLogName" value="CustomEventLogName" />
</appSettings>
``` | How to direct the EventLogTraceListener to create in a specific Log | [
"",
"c#",
".net",
"config",
"event-log",
"listeners",
""
] |
First off, I know this is a base JS issue, not jQuery. I am at that learning point where I cannot seem to get my head completely wrapped around some scope issues. So I need some explanation.
I've been reading every article/tutorial I can find, but just need some answers. I setup this base code to experiment with (as the actual code is far too big to post here).
In the following experiment, when the selector1-change button is clicked the 'cmd' variable is displayed correctly, but the reference to this.options is 'undefined', because it is a different instance of MySelector(), unless I am way off.
So how does one go about calling an instance of an object like this.
Example:
You can use jQueryUI's dialog by creating it, and then later you can pass commands to it like $('#mydiv').dialog('close'); and that will access the instance attached to that element. How is that accomplished?
**JQUERY\_MYSELECTOR.JS**
```
(function($){
$.fn.MySelector = function(incoming) {
if (typeof(incoming) != 'object') {
return runCommand(incoming);
}
var options = $.extend({},{
id: false,
backgroundColor: false
},incoming);
function runCommand(cmd) {
alert('blah:'+this.options.backgroundColor+"\n"+'cmd:'+cmd);
}
}
})(jQuery);
```
**SCRIPT**
```
<script type="text/javascript" src="jquery_myselector.js"></script>
<script type="text/javascript">
$j(document).ready(function() {
$j('#selector1).MySelector({ backgroundColor: '#000000' });
$j('#selector1-change').click(function() {
$j('#selector1').MySelector('mooocow');
});
});
</script>
```
**STYLE**
```
<input type="button" value="selector1" id="selector1" />
<br/>
<input type="button" value="selector1-change" id="selector1-change" />
```
***UPDATED***
Forgot to use the plugin on selector1 (duh) | You're calling runCommand before you assign a value to options - options has the value `undefined` inside the body of runCommand. Don't ask me how JS is able to see the body of runCommand before you declare it, but it can.
Also, at the first level of MySelector, `this` is bound to the results of running `$j('#selector1-change')`, which is an array. You will need to iterate that array.
Try something like this:
```
(function ($) {
function runCommand(e, cmd) {
alert('blah:' + e.options.backgroundColor + "\n" + 'cmd:' + cmd);
}
$.fn.MySelector = function (incoming) {
this.each(function () {
if (typeof (incoming) != 'object') {
return runCommand(this, incoming);
} else {
this.options = $.extend(this.options || {
id: false,
backgroundColor: false
}, incoming);
}
});
}
})(jQuery);
``` | You could try something like this:
```
(function($){
$.myPlugin = {
foo: function () {...},
bar: function () {...},
foobar: function () {...}
};
$.fn.MySelector = function (operation) {
if (typeof operation === 'string') {
switch(operation) {
'open':
$.myPlugin.foo();
break;
'destroy':
$.myPlugin.bar();
break;
default:
$.myPlugin.foobar();
break;
}
}
}
}(jQuery));
``` | jQuery Plugin Options | [
"",
"javascript",
"jquery",
"scope",
""
] |
I have a jar file I produced from compiled class files using an ant file with `<javac target="1.5" ... />` and I would like to verify that it actually produces 1.5 code. Is there a way to do this?
My version of MATLAB one one of the computers I'm using, uses a JRE 1.5; so it will not run code unless it is JRE 1.5 compatible. It's worked fine with most JAR files I've produced, but I have one that's acting up, with an odd error:
```
>> s = javaObject('com.example.test.hdf5.Test1');
??? Error using ==> javaObject
No constructor with appropriate signature exists
in Java class com.example.test.hdf5.Test1
```
even though here's my class, and it has a regular old no-arg constructor:
```
package com.example.test.hdf5;
import ncsa.hdf.hdf5lib.H5;
import ncsa.hdf.hdf5lib.HDF5Constants;
import ncsa.hdf.hdf5lib.exceptions.HDF5LibraryException;
import ncsa.hdf.object.FileFormat;
import ncsa.hdf.object.h5.H5File;
public class Test1 {
public Test1 () {}
public static void main(String args[])
{
Test1 test = new Test1();
if (args.length < 2)
{
}
else if ("h5file".equals(args[0]))
{
test.testH5File(args[1]);
}
else if ("h5f".equals(args[0]))
{
test.testH5F(args[1]);
}
}
public void testH5File(String filename) {
H5File file;
try
{
file = (H5File) new H5File().createFile(
filename, FileFormat.FILE_CREATE_OPEN);
file.close();
System.out.println("Success!");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testH5F(String filename) {
try {
int id = H5.H5Fopen(filename,
HDF5Constants.H5F_ACC_RDONLY, HDF5Constants.H5P_DEFAULT);
H5.H5Fclose(id);
System.out.println("Success!");
}
catch (HDF5LibraryException e) {
throw new RuntimeException(e);
}
catch (NullPointerException e) {
throw new RuntimeException(e);
}
}
}
```
Another file produced in the same package + jar file works fine:
```
package com.example.test.hdf5;
public class Test3 {
public Test3() {}
private int x=0;
public int foo() { return ++this.x; }
}
```
and I'm wondering if there's something that's screwing up the compiler's 1.5-ness by importing a library that may not be 1.5-compatible.
---
**update**: both my Test1 and Test3 classes are 1.5 (major=0, minor=49 as per `javap -v`). I added a Test2.java which is the exact same as Test1 but with the body of the methods commented out, so it has the same signatures. I get the following with `javap -s`:
```
C:\proj\java\test-hdf5\dist>javap -s -classpath test-hdf5.jar com.example.test.hdf5.Test1
Compiled from "Test1.java"
public class com.example.test.hdf5.Test1 extends java.lang.Object{
public com.example.test.hdf5.Test1();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
public void testH5File(java.lang.String);
Signature: (Ljava/lang/String;)V
public void testH5F(java.lang.String);
Signature: (Ljava/lang/String;)V
}
C:\proj\java\test-hdf5\dist>javap -s -classpath test-hdf5.jar com.example.test.hdf5.Test2
Compiled from "Test2.java"
public class com.example.test.hdf5.Test2 extends java.lang.Object{
public com.example.test.hdf5.Test2();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
public void testH5File(java.lang.String);
Signature: (Ljava/lang/String;)V
public void testH5F(java.lang.String);
Signature: (Ljava/lang/String;)V
}
C:\proj\java\test-hdf5\dist>javap -s -classpath test-hdf5.jar com.example.test.hdf5.Test3
Compiled from "Test3.java"
public class com.example.test.hdf5.Test3 extends java.lang.Object{
public com.example.test.hdf5.Test3();
Signature: ()V
public int foo();
Signature: ()I
}
```
I guess there's just something really weird going on in the HDF5 library JHDF5.jar that causes MATLAB to reject my Test1 class.
**update 2** >:( >:( >:( The JHDF5.jar file has version 50 (JRE1.6), so that's probably what's causing me to lose. Phooey to Matlab for not producing a meaningful error message, and Phooey to HDF5 for compiling with JRE1.6 instead of 1.5 or earlier; I'm very doubtful they're using any of the 1.6 features. I'll file a bug report. | To determine the Java bytecode version of a class file, use `javap -v <classname>`. This will output something like
```
minor version: 0
major version: 49
```
Major version 49 is Java platform version 1.5 (48 is 1.4, 50 is 1.6) | Try `methodsview('com.example.test.hdf5.Test1')` to see exactly
what Matlab thinks your constructor expects. | verifying that the compiler produces Java 1.5 code | [
"",
"java",
"compiler-construction",
"matlab",
""
] |
Let's say I'm parsing a file, which uses `;` as the comment character. I don't want to parse comments. So if I a line looks like this:
```
example.com. 600 IN MX 8 s1b9.example.net ; hello!
```
Is there an easier/more-elegant way to strip chars out other than this:
```
rtr = ''
for line in file:
trig = False
for char in line:
if not trig and char != ';':
rtr += char
else:
trig = True
if rtr[max(rtr)] != '\n':
rtr += '\n'
``` | I'd recommend saying
```
line.split(";")[0]
```
which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line. | just do a split on the line by comment then get the first element
eg
```
line.split(";")[0]
``` | In Python 2.4, how can I strip out characters after ';'? | [
"",
"python",
"string",
"python-2.4",
""
] |
I have a windows forms app in C#. Platform is vS 2005.
Following is the piece of code:
```
namespace HostApp
{
public partial class Form1 : Form
{
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Add("Apples");
comboBox2.Items.Add("Oranges");
comboBox2.Items.Add("Grapefruits");
}
}
}
```
I run the app but the fruit names do not show up in the drop down of comboBox2. I am sure I am missing some line of code to "populate" the drop down with the entered values.
Any help would be much appreciated.
Thanks,
Viren | You add the items in the handler for the `SelectedIndexChanged` event. You need to move the code to `InitializeComponent` or another appropriate place. | Please check the following things:
1. You have added AutoPostBack="true" in the combo-box so that the selectedChange event is fired and post back happens.
2. Make sure you have nothung in ur Page load which refreshed the combo box. You can use IsPostBack to acheive loading of the values. | combobox in C# not getting populated | [
"",
"c#",
"data-binding",
"combobox",
""
] |
I have this code:
```
public byte[] SerializeToBlob()
{
using (var buffer = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(buffer, this);
buffer.Position = 0;
return buffer.ToArray();
}
}
public static ActionData DeserializeFromBlob(byte[] state)
{
using (var buffer = new MemoryStream(state))
{
var formatter = new BinaryFormatter();
var result = formatter.Deserialize(buffer);
return (ActionData) result;
}
}
```
And am calling it as follows:
```
byte[] actionDataBlob = ad.SerializeToBlob();
var ad1 = ActionData.DeserializeFromBlob(actionDataBlob);
```
However, I get an InvalidCastException when it tries to cast the deserialized object to its type:
> [A]ActionData cannot be cast to
> [B]ActionData. Type A originates from
> 'XXXX.XXXX.Auditing, Version=1.0.76.0,
> Culture=neutral, PublicKeyToken=null'
> in the context 'Default' at location
> 'C:\Users\Craig\AppData\Local\Temp\Temporary
> ASP.NET
> Files\root\5d978e5b\ffc57fe1\assembly\dl3\2b1e5f8f\102c846e\_9506ca01\XXXX.XXXX.Auditing.DLL'.
> Type B originates from
> 'XXXX.XXXX.Auditing, Version=1.0.76.0,
> Culture=neutral, PublicKeyToken=null'
> in the context 'LoadNeither' at
> location 'F:\Visual Studio
> Projects\XXXXXXXXX\source\XXXX.XXXX.SilverlightClient.Web\bin\XXXX.XXXX.Auditing.dll'.
(XXXX.XXXX is there to obscure the client's name)
What gives?
I've now asked a related question here:
[How should I serialize some simple auditing data for storing in a SQL table?](https://stackoverflow.com/questions/1141873/how-should-i-serialize-some-simple-auditing-data-for-storing-in-a-sql-table) | You have loaded the same assembly twice, in different [loader contexts](http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx). E.g. you happened to load the XXX.Auditing with `Assembly.LoadFrom()` first, and then some other (or your) assembly loaded it normally. In fact, the binary deserializer could be the one who loaded the assembly a second time, though I wouldn't know why (no experience with ASP.NET). | It sounds to me like you have the same class in different assemblies (or web applications). BinaryFormatter includes the type metadata in the serialization, which means that **only the exact same assembly** will do. 2 solutions:
* put this type in a dll, and reference that **single** dll in both places
* use a contract-based serializer
Personally I would choose the second for a huge number of reasons not just limited to this one. Likely choices:
* XmlSerializer (xml; serializes public fields and properties; "tree" only)
* DataContractSerializer (xml; serializes **marked** fields and properties (public or private); "tree" or "graph")
* protobuf-net (binary; serializes **marked** fields and properties (public or private); "tree" only)
Which is best depends on the scenario. | InvalidCastException when serializing and deserializing | [
"",
"c#",
"serialization",
""
] |
I have a class like this:
```
class MyClass<T> {
public string value1 { get; set; }
public T objT { get; set; }
}
```
and a list of this class. I would like to use .net 3.5 lambda or linq to get a list of MyClass by distinct value1. I guess this is possible and much simpler than the way in .net 2.0 to cache a list like this:
```
List<MyClass<T>> list;
...
List<MyClass<T>> listDistinct = new List<MyClass<T>>();
foreach (MyClass<T> instance in list)
{
// some code to check if listDistinct does contain obj with intance.Value1
// then listDistinct.Add(instance);
}
```
What is the lambda or LINQ way to do it? | Both **Marc**'s and **dahlbyk**'s answers seem to work very well. I have a much simpler solution though. Instead of using `Distinct`, you can use `GroupBy`. It goes like this:
```
var listDistinct
= list.GroupBy(
i => i.value1,
(key, group) => group.First()
).ToArray();
```
Notice that I've passed two functions to the `GroupBy()`. The first is a key selector. The second gets only one item from each group. From your question, I assumed `First()` was the right one. You can write a different one, if you want to. You can try `Last()` to see what I mean.
I ran a test with the following input:
```
var list = new [] {
new { value1 = "ABC", objT = 0 },
new { value1 = "ABC", objT = 1 },
new { value1 = "123", objT = 2 },
new { value1 = "123", objT = 3 },
new { value1 = "FOO", objT = 4 },
new { value1 = "BAR", objT = 5 },
new { value1 = "BAR", objT = 6 },
new { value1 = "BAR", objT = 7 },
new { value1 = "UGH", objT = 8 },
};
```
The result was:
```
//{ value1 = ABC, objT = 0 }
//{ value1 = 123, objT = 2 }
//{ value1 = FOO, objT = 4 }
//{ value1 = BAR, objT = 5 }
//{ value1 = UGH, objT = 8 }
```
I haven't tested it for performance. I believe that this solution is probably a little bit slower than one that uses `Distinct`. Despite this disadvantage, there are two great advantages: simplicity and flexibility. Usually, it's better to favor simplicity over optimization, but it really depends on the problem you're trying to solve. | Hmm... I'd probably write a custom `IEqualityComparer<T>` so that I can use:
```
var listDistinct = list.Distinct(comparer).ToList();
```
and write the comparer via LINQ....
Possibly a bit overkill, but reusable, at least:
Usage first:
```
static class Program {
static void Main() {
var data = new[] {
new { Foo = 1,Bar = "a"}, new { Foo = 2,Bar = "b"}, new {Foo = 1, Bar = "c"}
};
foreach (var item in data.DistinctBy(x => x.Foo))
Console.WriteLine(item.Bar);
}
}
}
```
With utility methods:
```
public static class ProjectionComparer
{
public static IEnumerable<TSource> DistinctBy<TSource,TValue>(
this IEnumerable<TSource> source,
Func<TSource, TValue> selector)
{
var comparer = ProjectionComparer<TSource>.CompareBy<TValue>(
selector, EqualityComparer<TValue>.Default);
return new HashSet<TSource>(source, comparer);
}
}
public static class ProjectionComparer<TSource>
{
public static IEqualityComparer<TSource> CompareBy<TValue>(
Func<TSource, TValue> selector)
{
return CompareBy<TValue>(selector, EqualityComparer<TValue>.Default);
}
public static IEqualityComparer<TSource> CompareBy<TValue>(
Func<TSource, TValue> selector,
IEqualityComparer<TValue> comparer)
{
return new ComparerImpl<TValue>(selector, comparer);
}
sealed class ComparerImpl<TValue> : IEqualityComparer<TSource>
{
private readonly Func<TSource, TValue> selector;
private readonly IEqualityComparer<TValue> comparer;
public ComparerImpl(
Func<TSource, TValue> selector,
IEqualityComparer<TValue> comparer)
{
if (selector == null) throw new ArgumentNullException("selector");
if (comparer == null) throw new ArgumentNullException("comparer");
this.selector = selector;
this.comparer = comparer;
}
bool IEqualityComparer<TSource>.Equals(TSource x, TSource y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return comparer.Equals(selector(x), selector(y));
}
int IEqualityComparer<TSource>.GetHashCode(TSource obj)
{
return obj == null ? 0 : comparer.GetHashCode(selector(obj));
}
}
}
``` | How to get distinct instance from a list by Lambda or LINQ | [
"",
"c#",
"linq",
".net-3.5",
"lambda",
""
] |
The background is that I've got a celery distributed job server configured with a Django view that returns the status of a running job in JSON. The job server is located at celeryserver.mydomain.com and the page I'm executing the jQuery from is www.mydomain.com so I shouldn't need to consider JSONP for this should I, as the requests aren't being made to different domains?
Watching my server logs I see that jQuery is executing the `getJSON` call every 3 seconds as it should (with the Javascript setInterval). It does seem to use an OPTION request, but I've confirmed using `curl` that the JSON is still returned for these request types.
The issue is that the `console.log()` Firebug call in the jQuery below doesn't ever seem to run! The one before the getJSON call does. Not having a callback work is a problem for me because I was hoping to poll for a celery job status in this manner and do various things based on the status of the job.
```
<script type="text/javascript">
var job_id = 'a8f25420-1faf-4084-bf45-fe3f82200ccb';
// wait for the DOM to be loaded then start polling for conversion status
$(document).ready(function() {
var getConvertStatus = function(){
console.log('getting some status');
$.getJSON("https://celeryserver.mydomain.com/done/" + job_id,
function(data){
console.log('callback works');
});
}
setInterval(getConvertStatus, 3000);
});
</script>
```
I've used `curl` to make sure of what I'm receiving from the server:
```
$ curl -D - -k -X GET https://celeryserver.mydomain.com/done/a8f25420-1faf-4084-bf45-fe3f82200ccb
HTTP/1.1 200 OK
Server: nginx/0.6.35
Date: Mon, 27 Jul 2009 06:08:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
{"task": {"executed": true, "id": "a8f25420-1faf-4084-bf45-fe3f82200ccb"}}
```
That JSON looks fine to me and JSONlint.com validates it for me right now... I also simulated the jQuery query with `-X OPTION` and got exactly the same data back from the server as with a GET (content-type of application/json etc.)
I've been staring at this for ages now, any help greatly appreciated. I'm a pretty new jQuery user but this seems like it should be pretty problem-free so I have no idea what I'm doing wrong! | I think you have a cross-subdomain issue, `sub.domain.tld` and `domain.ltd` are not the same.
I recommend you to install [Firebug](http://getfirebug.com/) and check if your code is throwing an *Permission denied* Exception when the request starts, if it's the case, go for JSONP... | As several people stated, sub-domains count as domains and I had a cross-domain issue :)
I solved it by creating a little piece of Django Middleware that changes the response from my views if they're returning JSON and the request had a callback attached.
```
class JSONPMiddleware:
def process_response(self, request, response):
ctype = response.get('content-type', None)
cback = request.GET.get('callback', None)
if ctype == 'application/json' and cback:
jsonp = '{callback}({json})'.format(callback=cback, json=response.content)
return HttpResponse(content=jsonp, mimetype='application/javascript')
return response
```
All is now working as planned. Thanks! | jQuery getJSON callback does not work - even with valid JSON - and seems to be using "OPTION" request not "GET" | [
"",
"jquery",
"python",
"django",
"json",
""
] |
We have a client for whom we build a lot of template based sites. Ideally we would use something like kohana (<http://www.kohanaphp.com/>) to handle the templating and make doing site wide changes a breeze.
Unfortunately our client cannot (and will not) host any server side code (and before you ask, this will not change and hosting the files ourselves is not an option), so any files deployed to them must be HTML, Javascript, CSS, images and Flash only.
Is there a good way to develop in a framework environment like kohana to make the site manageable, but be able to deploy or export a HTML only version of the site (there is no dynamic aspect to the site such as searching that requires server side languages, and no database use)?
I guess it would be similar to spidering the site, but I'd like something a bit more reliable because some page assets are loaded dynamically with javascript.
Thanks | I use [Template Toolkit](http://search.cpan.org/dist/Template-Toolkit/) (Perl) and have a simple script that generates static files from the templates. This is great for the situation you are in (common navigation etc etc).
It comes with a `ttree` command that'll process a directory tree and put the results in another.
Here's the tt.rc file I use:
```
# ignore these files (regular expressions)
ignore = \.svn
ignore = ^#
ignore = ~$
ignore = .DS_Store
ignore = \.tt$
# if these template files change, reprocess everything
depend *=tpl/wrapper,tpl/defaults,style/default.html
# just copy these files, don't process as templates
copy = \.(gif|png|pdf|jpg)$
# verbose output
verbose
# recurse into subdirectories
recurse
# setup some defaults from tpl/defaults
pre_process = tpl/defaults
# process this file instead of the real file (see below how this is used)
process = tpl/wrapper
# process files from src/, output to html/
# extra templates in lib/ (tpl/wrapper for example).
src = src
dest = html
lib = lib
```
A couple of special files, `tpl/defaults` is
```
[%- page = {
title = template.title,
style = template.style or 'default.html'
};
base = INCLUDE tpl/base_uri;
# don't include any whitespace from here...
RETURN;
-%]
```
And `tpl/wrapper` is
```
[%- content = PROCESS $template;
IF !template.name.search('.html') OR page.style == 'none';
content;
ELSE;
default_style_template = "style/" _ page.style;
PROCESS $default_style_template;
END;
%]
```
This will process the real template; put the results in the `content` variable and then process the `style` template (set with `page.style` in `tpl/defaults`; defaults to `defaults.html`).
the `lib/style/default.html` style file just needs to have
```
[% content %]
```
somewhere to include the real template; before and after that you can have the standard footer and headers.
You can read more about Template Toolkit at [tt2.org](http://tt2.org/).
Another option would be to use `wget` (or similar) in recursive mode to "mirror" pages generated by PHP on the development server; but I wouldn't recommend that. | Give [WaveMaker Studio](https://www.wavemaker.com) a try. It will solve your problem partially.
WaveMaker Studio has a kind of templating feature and it comes in community open source version.
HTH | Best way to use a server side language for development, but deploy to static HTML | [
"",
"php",
"html",
"templates",
"kohana",
""
] |
EDIT: I am also after advice if there is a better way to go about this??
I have a webpage that displays a timesheet for the user to fill out.
The timesheet is for a month so it has as many rows in the month
and also 5 columns of data, Normal hours, extended hours, shift hours
holidays hours and total.
I have a dropdown list that allows the user to select the month
and year textbox.
When they select a month the code then disbles the bottom
rows if they are not required due to not havving say 31 days as
an example. It also then sets the background color of each
row depending on if it is a weekend( in a different color) or not.
Problem is when the month is selected it is taking 3-4 secs to
run the code and is annoying for the user as they dont know
what is happening.
Is there any way of improving this that you can see? The code
is shown below.
```
$('[id$=lstMonth]').change(function() {
MonthChange();
});
});
function MonthChange() {
var month = parseInt($('[id$=lstMonth]').val())-1;
var year = $('[id$=txtYear]').val();
var daysInMonth = GetDaysInMonth(month, year);
var day, dte, bgcolor;
for(day=28; day<=31; day+=1) {
if(day > daysInMonth)
DisableRow(day);
else
EnableRow(day);
}
for(day=1; day<=daysInMonth; day+=1) {
dte = GetDate(day, month, year);
bgcolor = GetInputFieldColor(dte, false);
SetBackgroundColor(day, bgcolor);
}
}
function SetBackgroundColor(day, bgcolor) {
var selector = '[id$=txtNormal' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
selector = '[id$=txtExtended' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
selector = '[id$=txtShift' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
selector = '[id$=txtHoliday' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
selector = '[id$=txtTotal' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
}
function DisableRow(day) {
var selector = '[id$=txtNormal' + day + ']';
$(selector).css("background-color", "red");
}
function EnableRow(day) {
var selector = '[id$=txtNormal' + day + ']';
$(selector).css("background-color", "blue");
}
``` | You are using all over your code, attribute selectors without specifying the element type.
This is not well performing, since **all** your DOM elements are inspected, for example:
You are also using [endsWith](http://docs.jquery.com/Selectors/attributeEndsWith#attributevalue) [id$=xxx] this is really needed for your case??
I would consider rewriting your SetBackgroundColor function as this also for readability:
```
function SetBackgroundColor(day, bgcolor) {
var types = ['Normal', 'Extended', 'Shift', 'Holiday'];
$.each(types, function(index, type){
var selector = 'input[id$=txt' + type + day + ']'; // change input to your
// element type
//'#txt' + type + day; or if you don't need the endsWith selector
$(selector).css("background-color", bgcolor)
.parent()
.css("background-color", bgcolor);
// 1 selector call, and using chaining
});
}
``` | ```
function SetBackgroundColor(day, bgcolor) {
var selector = '[id$=txtNormal' + day + ']';
$(selector).css("background-color", bgcolor);
$(selector).parent().css("background-color", bgcolor);
}
```
=>
```
function SetBackgroundColor(day, bgcolor) {
var selector = '#txtNormal' + day;
var obj = $(selector);
obj.css("background-color", bgcolor);
obj.parent().css("background-color", bgcolor);
}
```
There are many [tips](http://www.artzstudio.com/2009/04/jquery-performance-rules/) how to improve performance for jQuery. | Improving performance of jquery/javascript webpage logic | [
"",
"javascript",
"jquery",
"performance",
""
] |
I've got a requirement of determining whether the entered sentence is positive or negative.... First I thought it is something to do with Social Network analysis and later I realised that it is Sentiment analysis. My first question is what is the difference between these two? I think SNA itself uses SA... plz correct me if i am wrong...
Regarding this I got a very good discussion by Alexander @ [NLP: Qualitatively "positive" vs "negative" sentence](https://stackoverflow.com/questions/122595/nlp-qualitatively-positive-vs-negative-sentence)...
I want to get into this field with the power of open source and preferably with Java (but I am open to others too). Can anyone pls guide me on how to get started and move ahead
Thanks in advance
Siva | This is sentiment analysis.
Social Network Analysis doesn't really have anything to do with Sentiment Analysis - social network analysis deals with relationships between people or things - common problems deal with figuring out "clustering" or cliques within a social network, discovering group cohesion, prestige within groups, discovering "ringleaders", etc.
Sentiment analysis is much closer to natural language processing - taking some textual, audio or video content and attempting to classify it in some way - subjective/objective, agreement/disagreement, etc.
As for tools/APIs that support this - I googled and found this blog post [listing several sentiment analysis and natural language processing tools](http://lordpimpington.com/codespeaks/drupal-5.1/?q=node/5). | RapidMiner is a powerful text mining and sentiment analysis tools. Rapid-I offers RapidMiner training courses on text mining and sentiment analysis:
[Sentiment Analysis, Opinion Mining, and Automated Market Research](http://rapid-i.com/content/view/125/150/).
Best regards,
Frank | getting into sentiment analysis | [
"",
"java",
"nlp",
"sa",
""
] |
I'm trying to add a Foreign Key to a table, but database, Sql Server 2005, does not like it.
It says that columns do not match an existing primary key or unique constraint.
How can I find the columns in question so I can delete/change them and add the foreign key? | Do a left join to the parent table on the key in question, then examine the values in the child table where the value in the left-joined parent table are null.
For example, if this was your schema...
```
table1:
myKey int primary key,
...other columns...
table2:
otherKey int primary key,
myKeyFromTable1 int
...other columns...
```
You'd do this:
```
select distinct
t2.myKeyFromTable1
from table2 t2
left join table1 t1 on t1.myKey = t2.myKeyFromTable1
where t1.myKey is null
```
That would give you the distinct values in `table2` that wouldn't have a corresponding parent in `table1`. | ```
SELECT
ForeignKey
FROM
FK_TABLE f
LEFT JOIN
PK_TABLE p ON f.ForeignKey = p.PrimaryKey
WHERE
p.PrimaryKey = NULL
```
That should do it.
ForeignKey = the column you want to make into a foreign key
PK\_TABLE = the table you want the foreign key to reference
PrimaryKey = the column ForeignKey will be a foreign key to. | Finding columns that do not match existing primary key | [
"",
"sql",
"sql-server",
"visual-studio-2008",
"sql-server-2005",
""
] |
Martin Fowler's Refactoring discusses creating Null Objects to avoid lots of
```
if (myObject == null)
```
tests.
What is the right way to do this? My attempt violates the "virtual member call in constructor" rule.
Here's my attempt at it:
```
public class Animal
{
public virtual string Name { get; set; }
public virtual string Species { get; set; }
public virtual bool IsNull
{
get { return false; }
}
}
public sealed class NullAnimal : Animal
{
public override string Name
{
get{ return "NULL"; }
set { }
}
public override string Species
{
get { return "NULL"; }
set { }
}
public virtual bool IsNull
{
get { return true; }
}
}
``` | I tend to agree with [Wyatt Barnett's answer](https://stackoverflow.com/questions/1178399/how-do-i-create-a-null-object-in-c/1178428#1178428) in that you should show restraint when creating these kinds of "null" objects. That said, there are some nice reasons for doing so. On occasion.
I also tend to agree with [Supertux's answer](https://stackoverflow.com/questions/1178399/how-do-i-create-a-null-object-in-c/1178451#1178451) in that the whole point of a null object is to not need to check whether or not it is null, so you should lose the IsNull property. If you really feel you need the IsNull property, then read Wyatt's response again and reconsider.
And thank you [CraigTP for the nice links](https://stackoverflow.com/questions/1178399/how-do-i-create-a-null-object-in-c/1178450#1178450) for more info. Good stuff.
Now I will assume that in your real code you actually have a constructor that is attempting to set the values of Name or Species (whatever your real code equivalent might be called). Otherwise, why would you get the "virtual member call in constructor" warning/error? I've run into a couple of similar problems when using the newfangled MyProperty { get; set; } shortcut myself (particularly when used in structs, and don't get me started about serialization versioning). Your solution is to not use the shortcut, but instead do it the old-fashioned way.
```
public class Animal {
protected Animal() { }
public Animal(string name, string species) {
_Name = name;
_Species = species;
}
public virtual string Name {
get { return _Name; }
set { _Name = value; }
}
private string _Name;
public virtual string Species {
get { return _Species; }
set { _Species = value; }
}
private string _Species;
}
public sealed class NullAnimal : Animal {
public override string Name {
get { return String.Empty; }
set { }
}
public override string Species {
get { return String.Empty; }
set { }
}
}
```
This solves the problem of setting your virtual properties in the constructor. Instead, you are setting your private field values (something you don't have the ability to reference if you use the shortcut). For extra credit, compile both methods, and use the Reflector to look at the resulting assemblies.
The more I use the { get; set; } shortcut, the more I dislike it. | Go look up the amount of pain that interesting concepts, such as DbNull, have caused and think about if this is actually a good idea.
Protip: if you are constantly checking for null references, you probably should rethink the API a bit to help preclude null objects closer to the top of the stack.
Protip II: having something throw an exception when there is an unexpected null is actually fine and dandy. Things should go boom if you have nulls where there shouldn't be null. | How do I create a Null Object in C# | [
"",
"c#",
"design-patterns",
"refactoring",
""
] |
I am trying to read some Java code from a tutorial, I don't understand the line:
```
public Weatherman(Integer... zips) {
```
* I don't understand what the ... represents if it was just (Integer zips) I would understand that there is a variable of class Integer called zips. But the ... are confusing me. | Those are "varargs," syntactic sugar that allows you to invoke the constructor in the following ways:
```
new Weatherman()
new Weatherman(98115);
new Weatherman(98115, 98072);
new Weatherman(new Integer[0]);
```
Under the covers the arguments are passed to the constructor as an array, but you do not need to construct an array to invoke it. | That’s a “vararg”. It can handle any number of `Integer` arguments, i.e.
```
new Weatherman(1);
```
is just as valid as
```
new Weatherman();
```
or
```
new Weatherman(1, 7, 12);
```
Within the method you access the parameters as an `Integer` array. | What does "public Weatherman(Integer... zips) {" mean in java | [
"",
"java",
"constructor",
""
] |
I get lists in Outlook, Word or Excel of hundreds of strings like so:
etc.
Currently I run a stored procedure on each of these, in one-by-one fashion.
How could I programmatically add an apostrophe before and after a string and add a comma inbetween, like so: ('','','','','','','')?
I want to change my stored procedure to use IN (' ',' ',' ') and run all of them at once? | ```
DECLARE @STRING varchar(max)
SELECT @STRING = '7864750A 7888801BZ 5189748C 48982572E 6936001F 7096235FG 3218833H'
SELECT '(''' + REPLACE(@STRING,' ',''',''') + ''')'
```
gives this result:
```
('7864750A','7888801BZ','5189748C','48982572E','6936001F','7096235FG','3218833H')
``` | You could write a table-valued UDF that takes the strings as input and returns the items in separate rows of a table. Something like this (not the most efficient thing in the world...):
```
CREATE FUNCTION [dbo].[SplitMyValues]
(
@Input VARCHAR(MAX)
)
RETURNS @Results TABLE
(
Data VARCHAR(MAX)
)
AS
BEGIN
DECLARE @Where INT
DECLARE @Length INT
DECLARE @Next INT
SET @Where = 0
SET @Length = LEN(@Input)
WHILE (@Where < @Length)
BEGIN
SET @Next = CHARINDEX(' ', @Input, @Where)
IF (@Next > 0)
BEGIN
INSERT INTO @Results VALUES (SUBSTRING(@Input, @Where, @Next - @Where))
SET @Where = @Next + 1
END
ELSE
BEGIN
INSERT INTO @Results VALUES (SUBSTRING(@Input, @Where, LEN(@Input)))
SET @Where = @Length
END
END
RETURN
END
```
To see the output, you can just run this:
```
SELECT *
FROM
dbo.SplitMyValues('7864750A 7888801BZ 5189748C 3218833H')
```
Then you can just do a join or a subquery in the `WHERE` clause of an `UPDATE` or `SELECT`, like:
```
SELECT *
FROM
SomeTable S
INNER JOIN dbo.SplitMyValues('7864750A 7888801BZ 5189748C 3218833H') X
ON X.Data = S.WhateverColumn
``` | How do I programmatically add an apostrophe before and after a string and add a comma inbetween? | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
Coming from an Classic ASP background I'm pretty cautious about placing objects into Session.
Would it be a bad idea for me to store an object of type Dictionary into Session within .NET? | Well, you won't have some of the issues that you would have with ASP. .net is not STA COM, so the thread affinity problems that you had with ASP are not going to hurt you (unless you try to store an STA COM object in the session, or in your dictionary).
Do be careful about concurrent access, though. If it is possible that multiple threads could access the dictionary (do to asynchronous page code, or maybe AJAX calls), then you will need to apply appropriate locking to the dictionary. | Well, it depends on what you want to achieve, for simple things like persisting state between page postbacks, I recommend you to use the [ViewState](http://msdn.microsoft.com/en-us/library/ms972976.aspx). | Storing Dictionary<String, String> in Session (.NET) | [
"",
"c#",
".net",
"session",
""
] |
with Java5 we can write:
```
Foo[] foos = ...
for (Foo foo : foos)
```
or just using an Iterable in the for loop. This is very handy.
However you can't write a generic method for iterable like this:
```
public void bar(Iterable<Foo> foos) { .. }
```
and calling it with an array since it is not an Iterable:
```
Foo[] foos = { .. };
bar(foos); // compile time error
```
I'm wondering about the reasons behind this design decision. | Arrays can implement interfaces (`Cloneable` and `java.io.Serializable`). So why not `Iterable`? I guess `Iterable` forces adding an `iterator` method, and arrays don't implement methods. `char[]` doesn't even override `toString`. Anyway, arrays of references should be considered less than ideal - use `List`s. As dfa comments, `Arrays.asList` will do the conversion for you, explicitly.
(Having said that, you can call `clone` on arrays.) | The array is an Object, but its items might not be. The array might hold a primitive type like int, which Iterable can't cope with. At least that's what I reckon. | Why is an array not assignable to Iterable? | [
"",
"java",
"language-design",
""
] |
I'm trying to make a video out of a folder full of jpeg files. I tried Google, and everybody is stuck with this. I have downloaded the WM SDK and the Encoder, but since the moment I don't know their object model I cant do much.
Does somebody here have some code WORKING about how to create a WMV or an AVI or a MPEG video file out of a folder full of jpegs? (In C#)
**I can see on the answers that apparently there is no way to do it from C#, just using a third party. I will check your suggestions.** | Take a look at [Corinna John's AVIFile wrapper](http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx). I used it in the [AVI output plugin for Cropper](http://cropperplugins.codeplex.com/SourceControl/changeset/view/3303#47968). | [VirtualDub](http://www.virtualdub.org/ "VirtualDub") is capable of making a video out of several image files. [Here's](http://www.virtualdub.org/blog/pivot/entry.php?id=34) a quite overview of how to do it.
FFMPEG, as CptSkippy mentioned, also has this feature. | Create Video out of image files? | [
"",
"c#",
"windows-mobile",
"video",
"sdk",
"jpeg",
""
] |
How can I determine the maximum filename length on a linux box?
Preferred in PHP programming language. | You want [`pathconf` or `fpathconf`](http://www.opengroup.org/onlinepubs/009695399/functions/pathconf.html), which are not exposed (yet) in PHP. (When they are, they'll probably be `posix_pathconf`.)
You may also shell out to [`getconf`](http://www.opengroup.org/onlinepubs/009695399/utilities/getconf.html), a command-line utility interface to the same functionality. Try this on your system:
`$ getconf NAME_MAX /tmp`
`$ getconf PATH_MAX /tmp` | there's no need to programatically determine it. it's 255 bytes.
edit: you can have longer filenames on a very few file systems (reiser, i believe), but if you stick to 255 your app will be usable on any linux installation. | Programmatically determine maximum filename length | [
"",
"php",
"linux",
"path",
"filenames",
"name-length",
""
] |
In c#, when I want to remove some items from a list, i do it in the following way,
```
List<Item> itemsToBeRemoved = new List<Item>();
foreach(Item item in myList)
{
if (IsMatching(item)) itemsToBeRemoved.Add(item);
}
foreach(Item item in itemsToBeRemoved)
{
myList.Remove(item);
}
```
Is there any better way to do it? | Well, you could call the method that does exactly what you want.
```
myList.RemoveAll(IsMatching);
```
Generally it is "better" to use the method that does exactly what you want rather than re-inventing it yourself. | ```
myList.RemoveAll(x=> IsMatching(x));
``` | Better way to remove matched items from a list | [
"",
"c#",
"list",
""
] |
I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program.
However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file.
When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)
```
def init_hardware(self):
""" Inits the instrument """
self.write_log("Initialising the automatic tuner")
version_string = create_string_buffer(80)
self.error_string = create_string_buffer(80)
self.name = "Maury MT982EU"
self.write_log("Tuner DLL path: %s", find_library('MLibTuners'))
self.maury = WinDLL('MlibTuners')
self.maury.get_tuner_driver_version(version_string)
if (version_string.value == ""):
self.write_log("IMPORTANT: Error obtaining the driver version")
else:
self.write_log("Version number of the DLL: %s" % version_string.value)
self.ThreeTypeLong = c_long * 3
```
Now that works swell, everything is perfect and I get perfect log-entries.
But when I try to run a method further into the program called:
```
def add_tuner_and_controller(self, name, serial_number, tuner_number=0):
""" Adds the tuner to the driver object, controller is inside the tuner """
self.write_log("Adding tuner %d and the built-in controller" % tuner_number)
TempType = self.ThreeTypeLong()
self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0),
c_long(0), c_short(serial_number), self.error_string)
self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0),
c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()),
pointer(c_double()), self.error_string)
```
The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init\_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?
---
**EDIT:**
*Documentation info*:
[Legend: The stars indicate pointers and the brackets indicate arrays]
**The add\_tuner function adds or updates one tuner in the tuner driver object.**
```
short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ])
```
**Output**: `no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return->Error flag`
**The add\_controller function adds or updates one controller in the tuner driver object**
```
short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ])
```
**Output**: `error_string, function-return->Error flag` | I found out that the only way to call the functions in the exported DLL was to use the DLL through a parameter in each method. (the program exports the dll and in each method called it will send it as a parameter).
It looks pretty ugly but that's the only way I found to be working for me. I even tried exporting the DLL as an class attribute. The system I'm working with is pretty hefty so I guess there is some boboo-code somewhere that makes it fail. Thanks for all the feedback and tips!
/Mazdak | I'm not sure about your exact problem, but here's a couple general tips:
For those functions that you are calling outside of the constructor, I would strongly recommend setting their [`argtypes`](http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes) in the constructor as well. Once you've declared the `argtypes`, you shouldn't need to cast all the arguments as `c_short`, `c_double`, etc. Moreover, if you do accidentally pass an incorrect argument to a C function, Python will raise a runtime error instead of crashing within the DLL.
Another minor detail, but you should be using `x = 0;` [`byref(x)`](http://docs.python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference) or maybe [`POINTER`](http://docs.python.org/library/ctypes.html#pointers)`(c_double)()` instead of pointer(c\_double()) in the tuner and controller.
I've been writing some ctypes classes in Python 2.6 recently as well, and I haven't seen any issues like what you're describing. Since there apparently aren't any Python bug reports on that either, I strongly believe that there's just a minute detail that we are both overlooking in your method that is having a problem. | Problem running functions from a DLL file using ctypes in Object-oriented Python | [
"",
"python",
"dll",
"oop",
"automation",
"ctypes",
""
] |
I wrote this extension for stringbuilder in VB.NET:
```
Imports System.Runtime.CompilerServices
Public Module sbExtension
<Extension()> _
Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
ByVal format As String, _
ByVal arg0 As Object)
oStr.AppendFormat("{0}{1}", String.Format(format, arg0), ControlChars.NewLine)
End Sub
<Extension()> _
Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
ByVal format As String, ByVal arg0 As Object, _
ByVal arg1 As Object)
oStr.AppendFormat("{0}{1}", String.Format(format, arg0, arg1), ControlChars.NewLine)
End Sub
<Extension()> _
Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
ByVal format As String, _
ByVal arg0 As Object, _
ByVal arg1 As Object, _
ByVal arg2 As Object)
oStr.AppendFormat("{0}{1}", String.Format(format, arg0, arg1, arg2), ControlChars.NewLine)
End Sub
<Extension()> _
Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _
ByVal format As String, _
ByVal ParamArray args() As Object)
oStr.AppendFormat("{0}{1}", String.Format(format, args), ControlChars.NewLine)
End Sub
End Module
```
I tried porting it to C# (I am slowly learning/teaching myself C#), but I have been unsuccessful thus far:
```
using System.Runtime.CompilerServices;
namespace myExtensions
{
public static class sbExtension
{
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0, string arg1)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0, arg1), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string arg0, string arg1, string arg2)
{
oStr.AppendFormat("{0}{1}", string.Format(format, arg0, arg1, arg2), Environment.NewLine);
}
[Extension()]
public static void AppendFormattedLine(this System.Text.StringBuilder oStr, string format, string[] args)
{
oStr.AppendFormat("{0}{1}", string.Format(format, args), Environment.NewLine);
}
}
}
```
When I have this file in my App\_Code folder, I get the following error message:
> **Compiler Error Message:** CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.
I am unsure of what it means by this, because if I replace '[Extension()]' with 'this', the only thing that is related to an extension is 'ExtensionAttribute', but that does not work either.
Does anyone know what I am missing?
Thanks! | C#'s "this" keyword, which you are using correctly, is a replacement for the [Extension()] attribute. Remove those and you should be good to go.
To clarify, by "replacement" I really mean "syntactic sugar" - when the compiler sees the "this" modifier, it generates the same ExtensionAttribute you have to add by hand in VB. | No one actually shows an example syntax.
```
public static void ApplyNewServer(this ReportDocument report, string serverName, string username, string password)
{
}
``` | How do you create an extension in C#? | [
"",
"c#",
"extension-methods",
""
] |
Has anyone used `SQLAlchemy` in addition to `Django`'s ORM?
I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins).
Is it possible?
Note: I'm aware about `django-sqlalchemy` but the project doesn't seem to be production ready. | What I would do,
1. Define the schema in Django orm, let it write the db via syncdb. You get the admin interface.
2. In view1 you need a complex join
```
def view1(request):
import sqlalchemy
data = sqlalchemy.complex_join_magic(...)
...
payload = {'data': data, ...}
return render_to_response('template', payload, ...)
``` | I don't think it's good practice to use both. You should either:
1. Use Django's ORM and use custom SQL where Django's built-in SQL generation doesn't meet your needs, or
2. Use SQLAlchemy (which gives you finer control at the price of added complexity).
Of course, if you need Django's admin, then the first of these approaches is recommended. | SQLAlchemy and django, is it production ready? | [
"",
"python",
"database",
"django",
"sqlalchemy",
""
] |
I have a registration form which I need to validate before submit. The form has the following fields:name,email, and password. I need the name to have a value, the email to have the correct format, and the password to be at least 6 characters.
What is the best way to do all this validation and hightlight incorrect fields live before submit?
Thanks,
Brad | If you're using jQuery, you may want to look into a jQuery validation plugin. [This one](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) seems to be popular, and looks pretty nice. If you're not using jQuery, you probably should be. ;) | Hope this isn't *too* off topic, but I've have to say that tackling this problem solely in JavaScript is never going to completely solve the problem, in the main due to the fact that it's trvial to stomp all over whatever logic you try and impose using browser developer tools, etc. (You also can't presume that everyone has JavaScript enabled, etc.)
As such, whilst you can carry out some nice real-time validation, etc. using JavaScript (with jQuery for nice visual effects, etc.) you'll need to carry out the *real* validation in whatever server side environment you're using.
In terms of the JavaScript 'validation' itself, simply attach functions that update the appropriate parts of the DOM with success/failure messages to the onchange, etc. events of the relevant inputs. See <http://www.w3schools.com/jS/js_form_validation.asp> for the basics. | Register Form Validation | [
"",
"javascript",
"forms",
"registration",
""
] |
I have a View that has a single `TextBox` and a couple `Button`s below it. When the window loads I want that `TextBox` to have focus.
If I was not using MVVM I would just call `TextBox.Focus()` in the Loaded event. However my ViewModel does not know about my view so how can I accomplish this without putting code into the codebehind of my view?
EDIT:
After reading the answers I decided to put this code in the view xaml
```
<DockPanel FocusManager.FocusedElement="{Binding ElementName=MessageTextBox}">
<TextBox Name="MessageTextBox" Text="{Binding Message}"/>
</DockPanel>
```
If this were anything other than initial page focus I would probably recommend Jon Galloway's answer since it can be controlled from the ViewModel. | If it makes you feel better (it makes me feel better) you can do this in XAML using an attached property:
<https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.focusmanager.focusedelement?view=netframework-4.7.2>
Anything you can do in code behind you can do in XAML if you know the tricks. Fortunately, you didn't have to implement this trick - MS did it for you. | In this case I think that it is fine to put the code into the view. Setting focus to a control affects the behaviour of the user interface rather than logic of the application and therefore is the responsibility of the view. | WPF MVVM Focus Field on Load | [
"",
"c#",
"wpf",
"mvvm",
"textbox",
"focus",
""
] |
I'm having trouble finding an elegant way to allow for date/time input in an html form. I am thinking of having drop down menus for year, month, day, hour, minute, second, millisecond that are populated with valid entries only. I *could* do this by hard coding values for each drop down menu, but I'm thinking there must be a more elegant way to do this, perhaps with some already existing javascript library that I have not found yet. Any tips for getting this done?
edit: Second, and if possible, millisecond precision is needed for what I'm working on.
edit#2: After reading some of the comments, I have come to the realization that it is probably a bad idea to have drop down menus for the large range of values required by hours/minutes/seconds and especially milliseconds. I think will go with having the DatePicker prototype date chooser, along with a simple textfield for time input. | This can be done quite elegantly with a Jquery plug-in called [Datepicker](http://docs.jquery.com/UI/Datepicker) | There are many calendars which can do this, with both date and time :
* [Calendar Date Select](http://code.google.com/p/calendardateselect/)
* and others | Date/Time input for an HTML Form | [
"",
"javascript",
"html",
"datetime",
"forms",
"input",
""
] |
I'm assigned to a large project that is going to be done in Java and viewed by a few programmers on the team. I want the code to be readable and understandable, and so I want the naming convention to suit everyone that reads it.
I'm wondering if I have to use the Java naming convention in order for other people to view it and understand it naturally. I always use a type of my own naming convention that doesn't differ much from the Java naming convention, but it inherits from the C/C++ naming convention.
The biggest difference is the variable, class and method naming. I use names like `intLargestNumber, chGet, strName` for variables. `funType, funErase, funAdd, getThis, setThis` for methods and `Screen, clsPlay, cls_User` for classes. Where Java naming convention would use something like `myNumber` for a variable, `lowSplit()` for a method and `Image` for a class.
Should I use the Java naming convention or use my own naming convention and provide a lexicon or a log for my code? | Using the standard for the language will make it simpler to bring new people on board. Also, using an externally defined convention can help mute the level of religious warfare that these sorts of style issues often provoke. | Use the Java naming convention. It's almost always a mistake to try to apply conventions from one language to another. The fact is that most people won't spend time reading up on the conventions used for a project. Therefore it's always easier to use the established norms of the language. | Should I use the Java naming convention? | [
"",
"java",
"naming-conventions",
""
] |
I know, I know - it probably doesn't (and shouldn't) matter - I've read [this comment](https://stackoverflow.com/questions/319421/what-is-the-best-programming-language-for-web-development-and-why/319464#319464). But as a newbie just learning Python, I'm quite intrigued. The source seems to reference Javascript a few times - would the whole site be in this? Any idea about the rest of the technology stack behind the site?
Looking at the technology behind some of my fave sites is proving to be quite an interesting way to learn about the pros and cons of various languages/frameworks.
EDIT: Don't mean to sound like an exam, but give reasons for your answer :-) eg. why would/wouldn't you recommend following in their footsteps? | According to [this interview with Craig from 2008](http://broadcast.oreilly.com/2008/12/craig-newmark-interview-a-brie.html), it's mostly written in Perl.
**EDIT:** You also asked about the remainder of the technology stack used there, which in the interview linked above is referred to as "pretty conventional LAMP architecture, a whole bunch of Linux systems, Apache, MySQL, and Perl specifically mod\_perl." As regards your specific mention of Javascript, Craigslist doesn't appear to be an especially Javascript-intensive site, but a quick "view source" confirmed that they do use [jQuery](http://jquery.com/). | From <http://www.craigslist.org/about/thanks>:
> * linux - essential to craigslist
> * apache - open source web server par excellence
> * mySQL - a fantastic open source SQL database
> * **perl - virtually all craigslist software is written in perl**
> * GNU - emacs, gcc, bash, and the very concept of free software
> * openBSD - virtually crashproof
> * [...]
(the list goes on) | Which language is Craigslist written in? | [
"",
"javascript",
"programming-languages",
"craigslist",
""
] |
What is the best way of supporting optional data passed to a C# function?
I have web service function in .Net which defines 5 arguments:
```
[WebMethod]
public string UploadFile( string wsURL
, byte[] incomingArray
, string FileName
, string RecordTypeName
, MetaData[] metaDataArray)
```
The code of this function is not too long (but not trivial either) and there is only one place in the the function where I perform this test if there is any MetaData[] to be processed:
```
if (metaDataArray.Length > 0)
{
Update update = BuildMetaData(metaDataArray);
treq2.Items = new Operation[] { sru, cin, update, fetch};
}
else
{
treq2.Items = new Operation[] { sru, cin, fetch};
}
```
I needed a quick and dirty version of the above which only takes 4 arguments (i.e. no "Metadata" array as a final argument) so I cloned the whole function and removed the IF-ELSE block refering to metadata. Ugly I know.
```
[WebMethod]
public string UploadFileBasic( string wsURL
, byte[] incomingArray
, string FileName
, string RecordTypeName)
```
Now I want to do things better and I am looking for advice on the best way to support this. I do not want to burden the client program with creating an empty array as a 5th parameter...I want to have my web service functions to be smart enough to handle this optional data. Thanks. | Change your check in the method that takes 5 arguments to (note, that you should be checking if the value is null anyway).
```
if (metaDataArray != null && metaDataArray.Length > 0)
{
Update update = BuildMetaData(metaDataArray);
treq2.Items = new Operation[] { sru, cin, update, fetch };
}
else
{
treq2.Items = new Operation[] { sru, cin, fetch};
}
```
Then, simply have your 4 argument version call the 5 argument version internally with the metaDataArray argument null.
```
[WebMethod]
public string UploadFileBasic( string wsURL,
byte[] incomingArray,
string FileName,
string RecordTypeName)
{
return UploadFile( wsUrl, incomingArray, fileName, RecordTypeName, null );
}
``` | ```
private static readonly MetaData[] EmptyMetaData = new MetaData[0];
[WebMethod]
public string UploadFile(string wsURL
, byte[] incomingArray
, string fileName
, string recordTypeName)
{
return UploadFile(wsURL, incomingArray, fileName, recordTypeName, EmptyMetaData)
}
``` | Best way of making an argument optional for a C# webmethod | [
"",
"c#",
"visual-studio",
"arrays",
"arguments",
"overloading",
""
] |
I have a Java Swing UI that isn't updating/repainting as I thought it should. The app sends an XMPP message and receives a response on a different thread. That response is processed and the UI is updated to reflect information contained in the message.
When the response is received, I update a JPanel component using
```
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() { /* execute logic to update panel */ }
});
```
It's been quite sometime since I've developed in Java, but based on my research online invokeLater queues the runnable up for execution on the GUI thread. However, my GUI doesn't update until I do something else in the app that causes a repaint - such as resizing the window. What am I missing? After the logic for updating the panel, I've tried various combinations of invalidate() and repaint(), but the result is still the same - the GUI does not update until I, say, resize the window.
EDIT: When I say updating the panel, I am, specifically, doing a removeAll() and then adding a handful of JLabels. | After adding/removing components from a panel you should use:
```
panel.revalidate(); // this works 99% of the time
panel.repaint(); // sometimes needed.
```
Other stuff like validate(), invalidate() etc., is left over from AWT days I believe and revalidate() does a better job and was added specifically for Swing. | If you mean by "update the panel" that you are adding or removing components, then you better use invalidate() or revalidate() so that the layout manager catches the changes.
See [here](https://stackoverflow.com/questions/1097366/java-swing-revalidate-vs-repaint) for a similar problem. | Swing UI not updating after using invokeLater | [
"",
"java",
"user-interface",
"swing",
""
] |
I've been trying and failing to use the java full screen mode on the primary display of an OSX system. Whatever I've tried I can't seem to get rid of the 'apple' menu bar from the top of the display. I really need to paint over the entire screen. Can anyone tell me how to get rid of the menu?
I've attached an example class which exhibits the problem - on my system the menu is still visible where I would expect to see a completely blank screen.
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class FullScreenFrame extends JFrame implements KeyListener {
public FullScreenFrame () {
addKeyListener(this);
setUndecorated(true);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
}
else {
System.err.println("Full screen not supported");
}
setVisible(true);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
setVisible(false);
dispose();
}
public static void main (String [] args) {
new FullScreenFrame();
}
}
``` | I think your problem is here:
```
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
```
`finally` blocks are always executed, so what happens here is that you window becomes full screen for a brief instant (if that) and then relinquishes the screen immediately.
Also, `setVisible(true)` is not necessary when you have previously called `setFullScreenWindow(this)`, according to the [Javadocs](http://java.sun.com/javase/6/docs/api/java/awt/GraphicsDevice.html#setFullScreenWindow(java.awt.Window)).
So I would change the constructor to this:
```
public FullScreenFrame() {
addKeyListener(this);
GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
setUndecorated(true);
gd.setFullScreenWindow(this);
} else {
System.err.println("Full screen not supported");
setSize(100, 100); // just something to let you see the window
setVisible(true);
}
}
``` | On OS X (10.7 and higher), it is better to use the native fullscreen mode available. You should use:
```
com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window,true);
com.apple.eawt.Application.getApplication().requestToggleFullScreen(window);
```
where `window` is the window (`JFrame`, etc) that you want to take fullscreen | How can I do full screen in Java on OSX | [
"",
"java",
"macos",
"awt",
"fullscreen",
""
] |
What generics collection class can I use that provides both mapping and array-like functionality. For example, I want to map a String to a Double and I want to reference the value using the key as the index.
```
collection[key] = collection[key] + double
```
Does the Google collections library provide such functionality?
Thanks. | Java won't let you use the bracket syntax with collections, but you could do something like:
```
HashMap<String, Double> collection = new HashMap<String, Double>();
String key = "some key";
...
if( collection.containsKey(key) )
{
// increment the value
collection.put( key, collection.get( key ) + 1.0 );
}
else
{
// initialize the value
collection.put( key, 0.0 );
}
``` | HashMap should serve your purposes:
<https://docs.oracle.com/javase/1.5.0/docs/api/java/util/HashMap.html> | Java - Collection Selection | [
"",
"java",
"collections",
""
] |
I have a method inside of a MooTools class that I want to access after uploading a file with AJAX (iFrame). The Javascript that the iFrame page runs when it loads should call the method of the Class, but I am unable to access it using anything like:
Class name: Main
var class was initialized in: myMain
parent.window.myMain.myMethod
parent.window.Main.myMethod
Is this even possible? If it is how do I do this? | The syntax I prefer:
```
var MyClass = new Class({
/* list regular non-static methods her as usual */
});
MyClass.staticMethod = function()
{
/* body of static function */
};
```
The advantages you have are:
* You can call the static method via `MyClass.staticMethod()` inside and outside of your class
* It is not possible to accidentally access the this-pointer in the static method as it is not available
To access the static method in an inner frame use can `window.parent.MyClass.staticMethod();` | This works for me (iframes too).
In main window.
```
var T=new MyClass();
```
In Iframe (which loads after T was initialized!)
```
window.parent.T.anyMethodOfMyClass()
``` | Accessing a MooTools Class Method from outside the class | [
"",
"javascript",
"mootools",
""
] |
I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.
I found how to access the output of the command in Python with the answer to this question:
[How can I perform a ping or traceroute in python, accessing the output as it is produced?](https://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p)
Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use `return` so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.
Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?
Basically, I'm trying to do something like this:
<http://network-tools.com/default.asp?prog=trace&host=www.bbc.co.uk> | `pexpect` will let you get the output as it comes, with no buffering.
To update info promptly on the user's browser, you need javascript on that browser sending appropriate AJAX requests to your server (dojo or jquery will make that easier, though they're not strictly required) and updating the page as new responses come -- without client-side cooperation (and JS + AJAX is the simplest way to get that cooperation), there's no sensible way to do it on the server side alone.
So the general approach is: send AJAX query from browser, have server respond as soon as it has one more line, JS on the browser updates contents then immediately sends another query, repeat until server responds with an "I'm all done" marker (e.g. an "empty" response may work for that purpose). | You may want to look at this [faq](http://wiki.pylonshq.com/display/pylonsfaq/Streaming+Content+to+the+Browser) entry. Then with JS, you always clear the screen before writing new stuff. | How can I display updating output of a slow script using Pylons? | [
"",
"python",
"pylons",
""
] |
hey, this i have a loop that adds gathered strings and ints into an object, and then adds that object into a list. I need it to check if there is already an object with a property == to the one i'm about to assign, and then depending on which the property is, I either want to change one of its properties, or still add a new object. I'll be sorting this later. Here's where I'm stuck. I have marked the line (currently commented out) which when activated, causes the command line to freeze. The weird thing is that i use the IDENTICAL code earlier with no trouble.
As you can see, I have some other code currently commented out, as this bit needs to work before I can continue, but I left it in to allow you to get more of an idea of what i am doing.
**solved. i actually had to move it another two loops upwards. THANKS!**
```
//IF THIS IS THE FIRST ONE, ADD IT!
var refSize = Referrals.Count();
if (refSize == 0)
{
var NewReferral = new Referral(referringURL.Trim(), referringWords.Trim(), 3);
Referrals.Add(NewReferral);
}
else
{
for (int i=0;i<refSize;i++)
{
// RESET BOOLS
URLPresent = false;
KeywordPresent = false;
// IF THE URL IS ALREADY PRESENT
//if (Referrals[i].URL == referringURL)
//{
//URLPresent = true;
// CHECK IF THE KEYWORD IS ALREADY PRESENT
//for (int ii=0;ii<Referrals[i].Keywords.Count;ii++)
//{
// if (Referrals[i].Keywords[ii] == referringWords)
// {
// ADD TO OCCURRENCES
// Referrals[i].Occurrences++;
// KeywordPresent = true;
// }
//}
// ADD KEYWORD TO LIST
// ###
// ###
//}
// IF THE KEYWORD ISN'T THERE && THE URL ISNT THERE, ADD A NEW REFERRAL OBJECT
if (URLPresent == false && KeywordPresent == false)
{
var NewReferral = new Referral(referringURL.Trim(), referringWords.Trim(), 3);
//Referrals.Add(NewReferral); //HERE IS MY PROBLEM! UNCOMMENTING THIS LINE CAUSES A FAIL.
//URLPresent = true;
//KeywordPresent = true;
}
// IF THE URL IS THERE, BUT THE KEYWORD ISNT, ADD AN ELEMENT TO THE REFERRAL.KEYWORDS LIST
//else if (URLPresent == true && KeywordPresent == false)
//{
//Referrals[i].Keywords.Add(referringWords);
//URLPresent = true;
//KeywordPresent = true;
//}
}
}
``` | The specific problem is that you're chasing your own tail. Every time you add a new element to the list, Refferals.Count goes up (your loop will never end if you keep adding elements). You should either pull the count out into a variable and use that into your loop or use something like Referrals.Contains ...
```
var refSize = Refferals.Count();
for (int i=0;i < refSize; i++)
{
// same
}
``` | The problem is that after you add it to the list, the loop runs through the newly added item and adds it again (probably due to a mistake you made somewhere), which repeats forever.
You can step through your code in the debugger and see.
As an aside, you shouldn't be calling the `Count()` method in the loop. Instead, use the `Count` property (without parentheses) | c# loop fails when adding object to list! | [
"",
"c#",
"list",
"object",
"loops",
""
] |
I'd like a SaveFileDialog with the following behavior:
* The first time you open it, it goes to "My Documents".
* Afterwards, it goes to the last selected folder.
What's the best way to accomplish this?
If I don't set the InitialDirectory, it goes to the exe's directory - which is not what I want. It rememebers the last selected directory though - even between executions.
If I set the InitialDirectory, it does not remember the last selected directory. Of course, I could save the last selected directory in the registry :( but I am looking for a better solution.
```
SaveFileDialog dialog = new SaveFileDialog();
//??? dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialog.ShowDialog();
```
Any advice? | You need to set the [`RestoreDirectory`](http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.restoredirectory.aspx) to `true` as well as the [`InitialDirectory`](http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.initialdirectory.aspx) property. | I have no idea why this works, but I was finally able to get it working for me.
I found that if I gave the full path, it would not work, but if I put that full path inside of **Path.GetFullPath()**, then it would work. Looking at the before and after values show them being the same, but it would consistently not work without it, and work with it.
```
//does not work
OpenFileDialog dlgOpen = new OpenFileDialog();
string initPath = Path.GetTempPath() + @"\FQUL";
dlgOpen.InitialDirectory = initPath;
dlgOpen.RestoreDirectory = true;
//works
OpenFileDialog dlgOpen = new OpenFileDialog();
string initPath = Path.GetTempPath() + @"\FQUL";
dlgOpen.InitialDirectory = Path.GetFullPath(initPath);
dlgOpen.RestoreDirectory = true;
``` | Setting the initial directory of an SaveFileDialog? | [
"",
"c#",
".net",
"wpf",
"winapi",
""
] |
I have to sync large files across some machines. The files can be up to 6GB in size. The sync will be done manually every few weeks. I cant take the filename into consideration because they can change anytime.
My plan is to create checksums on the destination PC and on the source PC and then copy all files with a checksum, which are not already in the destination, to the destination.
My first attempt was something like this:
```
using System.IO;
using System.Security.Cryptography;
private static string GetChecksum(string file)
{
using (FileStream stream = File.OpenRead(file))
{
SHA256Managed sha = new SHA256Managed();
byte[] checksum = sha.ComputeHash(stream);
return BitConverter.ToString(checksum).Replace("-", String.Empty);
}
}
```
The Problem was the runtime:
- with SHA256 with a 1,6 GB File -> 20 minutes
- with MD5 with a 1,6 GB File -> 6.15 minutes
Is there a better - faster - way to get the checksum (maybe with a better hash function)? | The problem here is that `SHA256Managed` reads 4096 bytes at a time (inherit from `FileStream` and override `Read(byte[], int, int)` to see how much it reads from the filestream), which is too small a buffer for disk IO.
To speed things up (2 minutes for hashing 2 Gb file on my machine with SHA256, 1 minute for MD5) wrap `FileStream` in `BufferedStream` and set reasonably-sized buffer size (I tried with ~1 Mb buffer):
```
// Not sure if BufferedStream should be wrapped in using block
using(var stream = new BufferedStream(File.OpenRead(filePath), 1200000))
{
// The rest remains the same
}
``` | Don't checksum the entire file, create checksums every 100mb or so, so each file has a collection of checksums.
Then when comparing checksums, you can stop comparing after the first different checksum, getting out early, and saving you from processing the entire file.
It'll still take the full time for identical files. | What is the fastest way to create a checksum for large files in C# | [
"",
"c#",
".net",
"large-files",
"checksum",
""
] |
How to compile open source framework in Visual Studio C++, that has "makefile" only and no solution file? | Unfortunately there is no silver bullet for this kind of change. Make and Visual Studio C++ style build are very different beasts. While they can do very similar operations, they can also have wildly different structures which makes providing a simple guide very difficult.
IMHO, the best way to achieve this is to start a new C++ project. Add in all of the existing files and go through the make file step by step attempting to convert every action to the equivalent C++ action. | If all you need is a self-built binary that you can link to with VC (i.e. no integration into existing VS solution) then have a look at [MSys](http://www.mingw.org/wiki/MSYS). It allows you to use GNU make together with VC. So you can use the GNU build system delivered with the OS project, while compiling with VC. | How to compile open source framework in Visual Studio C++, that has "makefile" only and no solution file? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-c++",
"makefile",
""
] |
I have a shared library (namely libXXX.so) with a cpp/h file associated.
They contains a number of function pointers ( to point to .so function entrypoint) and a class to wrap this functions as methods of the said class.
ie: .h file:
```
typedef void* handle;
/* wrapper functions */
handle okUsbFrontPanel_Construct();
void okUsbFrontPanel_Destruct(handle hnd);
/* wrapper class */
class okCUsbFrontPanel
{
public:
handle h;
public:
okCUsbFrontPanel();
~okCUsbFrontPanel();
};
```
.cpp file
```
/* class methods */
okCUsbFrontPanel::okCUsbFrontPanel()
{ h=okUsbFrontPanel_Construct(); }
okCUsbFrontPanel::~okCUsbFrontPanel()
{ okUsbFrontPanel_Destruct(h); }
/* function pointers */
typedef handle (*OKUSBFRONTPANEL_CONSTRUCT_FN) (void);
typedef void (*OKUSBFRONTPANEL_DESTRUCT_FN) (handle);
OKUSBFRONTPANEL_CONSTRUCT_FN _okUsbFrontPanel_Construct = NULL;
OKUSBFRONTPANEL_DESTRUCT_FN _okUsbFrontPanel_Destruct = NULL;
/* load lib function */
Bool LoadLib(char *libname){
void *hLib = dlopen(libname, RTLD_NOW);
if(hLib){
_okUsbFrontPanel_Construct = ( OKUSBFRONTPANEL_CONSTRUCT_FN ) dlsym(hLib, "okUsbFrontPanel_Construct");
_okUsbFrontPanel_Destruct = ( OKUSBFRONTPANEL_DESTRUCT_FN ) dlsym( hLib, "okUsbFrontPanel_Destruct" );
}
}
/* construct function */
handle okUsbFrontPanel_Construct(){
if (_okUsbFrontPanel_Construct){
handle h = (*_okUsbFrontPanel_Construct)(); //calls function pointer
return h;
}
return(NULL);
}
void okUsbFrontPanel_Destruct(handle hnd)
{
if (_okUsbFrontPanel_Destruct)
(*_okUsbFrontPanel_Destruct)(hnd);
}
```
Then I have another shared library (made by myself) which calls:
```
LoadLib("libXXX.so");
okCusbFrontPanel *device = new okCusbFrontPanel();
```
resulting in a Segmentation fault.
The segmentation fault seems to happen at
```
handle h = (*_okUsbFrontPanel_Construct)();
```
but with a strange behaviour: once I reach
```
(*_okUsbFrontPanel_Construct)();
```
I get a recursion to okUsbFrontPanel\_Construct().
Does anyone have any idea?
EDIT: here is a backtrace obtained by a run with gdb.
```
#0 0x007590b0 in _IO_new_do_write () from /lib/tls/libc.so.6
#1 0x00759bb8 in _IO_new_file_overflow () from /lib/tls/libc.so.6
#2 0x0075a83d in _IO_new_file_xsputn () from /lib/tls/libc.so.6
#3 0x00736db7 in vfprintf () from /lib/tls/libc.so.6
#4 0x0073ecd0 in printf () from /lib/tls/libc.so.6
#5 0x02cb68ca in okCUsbFrontPanel (this=0x9d0ae28) at okFrontPanelDLL.cpp:167
#6 0x03cac343 in okUsbFrontPanel_Construct () from /opt/atlas/tdaq/tdaq-02-00-00/installed/i686-slc4-gcc34-dbg/lib/libokFrontPanel.so
#7 0x02cb8f36 in okUsbFrontPanel_Construct () at okFrontPanelDLL.cpp:1107
#8 0x02cb68db in okCUsbFrontPanel (this=0x9d0ade8) at okFrontPanelDLL.cpp:169
#9 0x03cac343 in okUsbFrontPanel_Construct () from /opt/atlas/tdaq/tdaq-02-00-00/installed/i686-slc4-gcc34-dbg/lib/libokFrontPanel.so
#10 0x02cb8f36 in okUsbFrontPanel_Construct () at okFrontPanelDLL.cpp:1107
#11 0x02cb68db in okCUsbFrontPanel (this=0x9d0ada8) at okFrontPanelDLL.cpp:169
#12 0x03cac343 in okUsbFrontPanel_Construct () from /opt/atlas/tdaq/tdaq-02-00-00/installed/i686-slc4-gcc34-dbg/lib/libokFrontPanel.so
#13 0x02cb8f36 in okUsbFrontPanel_Construct () at okFrontPanelDLL.cpp:1107
```
and so on...
IMHO I get a seg fault becouse of a sort of stack overflow. There are too many recursive call and something goes wrong..
By the way I'm on a Scientific Linux 4 distro (based on RH4).
EDIT2:
an objdump of libokFrontPanel.so for function okUsbFrontPanel\_Construct outputs:
```
00009316 <okUsbFrontPanel_Construct>:
9316: 55 push ebp
9317: 89 e5 mov ebp,esp
9319: 56 push esi
931a: 53 push ebx
931b: 83 ec 30 sub esp,0x30
931e: e8 44 f4 ff ff call 8767 <__i686.get_pc_thunk.bx>
9323: 81 c3 dd bd 00 00 add ebx,0xbddd
9329: c7 04 24 38 00 00 00 mov DWORD PTR [esp],0x38
9330: e8 93 ec ff ff call 7fc8 <_Znwj@plt>
9335: 89 45 e4 mov DWORD PTR [ebp-28],eax
9338: 8b 45 e4 mov eax,DWORD PTR [ebp-28]
933b: 89 04 24 mov DWORD PTR [esp],eax
933e: e8 65 ed ff ff call 80a8 <_ZN16okCUsbFrontPanelC1Ev@plt>
9343: 8b 45 e4 mov eax,DWORD PTR [ebp-28]
9346: 89 45 f4 mov DWORD PTR [ebp-12],eax
9349: 8b 45 f4 mov eax,DWORD PTR [ebp-12]
934c: 89 45 e0 mov DWORD PTR [ebp-32],eax
934f: eb 1f jmp 9370 <okUsbFrontPanel_Construct+0x5a>
9351: 89 45 dc mov DWORD PTR [ebp-36],eax
9354: 8b 75 dc mov esi,DWORD PTR [ebp-36]
9357: 8b 45 e4 mov eax,DWORD PTR [ebp-28]
935a: 89 04 24 mov DWORD PTR [esp],eax
935d: e8 d6 f2 ff ff call 8638 <_ZdlPv@plt>
9362: 89 75 dc mov DWORD PTR [ebp-36],esi
9365: 8b 45 dc mov eax,DWORD PTR [ebp-36]
9368: 89 04 24 mov DWORD PTR [esp],eax
936b: e8 a8 f0 ff ff call 8418 <_Unwind_Resume@plt>
9370: 8b 45 e0 mov eax,DWORD PTR [ebp-32]
9373: 83 c4 30 add esp,0x30
9376: 5b pop ebx
9377: 5e pop esi
9378: 5d pop ebp
9379: c3 ret
```
at 933e there is indeed a call to <\_ZN16okCUsbFrontPanelC1Ev@plt>.Is this call that gets confused with the one inside my .cpp? | Now that you've posted `GDB` output, it's clear exactly what your problem is.
You are defining the same symbols in `libokFrontPanel.so` and in the `libLoadLibrary.so` (for lack of a better name -- it is *so* much easier to explain things when they are named properly), and *that* is causing the infinite recursion.
By default on UNIX (unlike on Windows) all global symbols from all shared libraries (and the main executable) go into single "loader symbol name space".
Among other things, this means that if you define `malloc` in the main executable, *that* `malloc` will be called by all shared libraries, including `libc` (even though `libc` has its own `malloc` definition).
So, here is what's happening: in `libLoadLibrary.so` you defined `okCUsbFrontPanel` constructor. I assert that there is also a definition of that exact symbol in `libokFrontPanel.so`. *All* calls to this constructor (by default) go to the first definition (the one that the dynamic loader first observed), even though the creators of `libokFrontPanel.so` did not intend for this to happen. The loop is (in the same order `GDB` printed them -- innermost frame on top):
```
#1 okCUsbFrontPanel () at okFrontPanelDLL.cpp:169
#3 okUsbFrontPanel_Construct () from libokFrontPanel.so
#2 okUsbFrontPanel_Construct () at okFrontPanelDLL.cpp:1107
#1 okCUsbFrontPanel () at okFrontPanelDLL.cpp:169
```
The call to constructor from `#3` was intended to go to symbol #4 -- `okCUsbFrontPanel` constructor *inside* `libokFrontPanel.so`. Instead it went to previously seen definition inside `libLoadLibrary.so`: you "preempted" symbol #4, and thus formed an infinite recursion loop.
Moral: do not define the same symbols in multiple libraries, unless you understand the rules by which the runtime loader decides which symbol references are bound to which definitions.
EDIT: To answer 'EDIT2' of the question:
Yes, the call to `_ZN16okCUsbFrontPanelC1Ev` from `okUsbFrontPanel_Construct` is going to the definition of that method inside your `okFrontPanelDLL.cpp`.
It might be illuminating to examine `objdump -d okFrontPanelDLL.o` | Contrary to what Norman Ramsey says, a tool of choice for diagnosing segfaults is `GDB`, not `valgrind`.
The latter is only useful for *certain* kinds of segfaults (mostly these related to heap corruption; which doesn't appear to be the case here).
My crystal ball says that your `dlopen()` fails (you should print `dlerror()` if/when that happens!), and that your `_okUsbFrontPanel_Construct` remains `NULL`. In `GDB` you will immediately be able to tell whether that guess is correct.
My guess contradicts your statement that you "get a recursion to okUsbFrontPanel\_Construct()". But just how can you know that you get such recursion, if you didn't look with `GDB`? | Segmentation fault using shared library | [
"",
"c++",
"memory-management",
"shared-libraries",
"segmentation-fault",
""
] |
I have created an open source project that runs from Visual Studio. But it relies on some external libraries to work as well. These libraries are also open source. The question I'm wondering is if I should
1. Point users to these libraries and have them download the source code and then add them to the project
2. Point users to the dll and have them reference it directly
3. Include the dll directly into the project
4. Include the source code of these libraries directly into the project
Which is the best way or standard way of doing this? | There are guidelines that are not open source specific, but I think they apply.
I always include binaries of all external libraries (except for standard ones like System.dll) in source control. This way, people that check out source code can immediately build the project. Moreover, I can easily switch to older version of project and immediately have dependencies in versions that were used to build that revision - this is particulary useful when debuging older release of software. | Most projects I've seen include a ThirdParty folder (or something similar) with the dll files in the project, and the project references those. This ensures everyone has the same version and theres no need to change the references.
If its in version control it also makes it easier to debug if you need to switch back to an earlier version. | How should I include external libraries in an open source project? | [
"",
"c#",
"open-source",
""
] |
I'm trying to solve the below problem.
I feel like it is possible, but I can't seem to get it.
Here's the scenario:
```
Table 1 (Assets)
1 Asset-A
2 Asset-B
3 Asset-C
4 Asset-D
Table 2 (Attributes)
1 Asset-A Red
2 Asset-A Hard
3 Asset-B Red
4 Asset-B Hard
5 Asset-B Heavy
6 Asset-C Blue
7 Asset-C Hard
```
If I am looking for something having the same attributes as Asset-A, then it should identify Asset-B since Asset-B has all the same attributes as Asset-A (it should discard heavy, since Asset-A didn't specify anything different or the similar). Also, if I wanted the attributes for only Asset-A AND Asset-B that were common, how would I get that?
Seems simple, but I can't nail it...
The actual table I am using, is almost precisely Table2, simply an association of an AssetId, and an AttributeId so:
PK: Id
int: AssetId
int: AttributeId
I only included the idea of the asset table to simplify the question. | This solution works as prescribed, thanks for the input.
```
WITH Atts AS
(
SELECT
DISTINCT
at1.[Attribute]
FROM
Attribute at1
WHERE
at1.[Asset] = 'Asset-A'
)
SELECT
DISTINCT
Asset,
(
SELECT
COUNT(ta2.[Attribute])
FROM
Attribute ta2
INNER JOIN
Atts b
ON
b.[Attribute] = ta2.[attribute]
WHERE
ta2.[Asset] = ta.Asset
)
AS [Count]
FROM
Atts a
INNER JOIN
Attribute ta
ON
a.[Attribute] = ta.[Attribute]
``` | ```
SELECT ato.id, ato.value
FROM (
SELECT id
FROM assets a
WHERE NOT EXISTS
(
SELECT NULL
FROM attributes ata
LEFT JOIN
attributes ato
ON ato.id = ata.id
AND ato.value = ata.value
WHERE ata.id = 1
AND ato.id IS NULL
)
) ao
JOIN attributes ato
ON ato.id = ao.id
JOIN attributes ata
ON ata.id = 1
AND ata.value = ato.value
```
, or in `SQL Server 2005` (with sample data to check):
```
WITH assets AS
(
SELECT 1 AS id, 'A' AS name
UNION ALL
SELECT 2 AS id, 'B' AS name
UNION ALL
SELECT 3 AS id, 'C' AS name
UNION ALL
SELECT 4 AS id, 'D' AS name
),
attributes AS
(
SELECT 1 AS id, 'Red' AS value
UNION ALL
SELECT 1 AS id, 'Hard' AS value
UNION ALL
SELECT 2 AS id, 'Red' AS value
UNION ALL
SELECT 2 AS id, 'Hard' AS value
UNION ALL
SELECT 2 AS id, 'Heavy' AS value
UNION ALL
SELECT 3 AS id, 'Blue' AS value
UNION ALL
SELECT 3 AS id, 'Hard' AS value
)
SELECT ato.id, ato.value
FROM (
SELECT id
FROM assets a
WHERE a.id <> 1
AND NOT EXISTS
(
SELECT ata.value
FROM attributes ata
WHERE ata.id = 1
EXCEPT
SELECT ato.value
FROM attributes ato
WHERE ato.id = a.id
)
) ao
JOIN attributes ato
ON ato.id = ao.id
JOIN attributes ata
ON ata.id = 1
AND ata.value = ato.value
``` | SQL Elaborate Joins Query | [
"",
"sql",
"t-sql",
"common-table-expression",
""
] |
I have an sql query that returns a lot of results for which I want to generate an html table to display them. Problem is I don't want to display them all on one page, I want to grab 10 at a time and flip through pages of results.
I want to return 100 results for each query but I can't figure out how to get THE NEXT 100 on the next query. | ```
-- return the first 100 rows
SELECT * FROM table LIMIT 0, 100
-- return the next 100 rows
SELECT * FROM table LIMIT 100, 100
-- and the next
SELECT * FROM table LIMIT 200, 100
```
What you need to do is pass a variable to your script that will create the proper SQL LIMIT statement for each page. | You would define at the bottom a Limit. For the first page:
```
LIMIT 0,100
```
Second Page
```
LIMIT 100,100
```
and so on.
When you go to put the 'Next' link on the page, make a $\_GET parameter that says start=100. Then, use that start parameter as the first value in limit, and add 100 to it to get the second value.
So, in the end it would look like:
```
if(empty($_GET['start']))
{
$start = 0;
}
else
{
$start = $_GET['start'];
}
$SQL = "SELECT * FROM TABLE WHERE 1=1 LIMIT ".$start.",100;";
query($sql);
$link = "<a href=\"?start=".$start+100."\">Next</a>";
```
If you wanted to expand upon that further, you could add a num parameter. That would allow for users to control how many records they see. So:
```
if(empty($_GET['start']))
{
$start = 0;
}
else
{
$start = $_GET['start'];
}
if(empty($_GET['num']))
{
$start = 100;
}
else
{
$start = $_GET['num'];
}
$SQL = "SELECT * FROM TABLE WHERE 1=1 LIMIT ".$start.",".$num.";";
query($sql);
$link = "<a href=\"?start=".$start+100."&num=".$num."\">Next</a>";
```
Of course, you would want to sanatize/validate all those numbers. | Generating an html report from an sql query | [
"",
"sql",
""
] |
I have inherited a database which contains strings such as:
\u5353\u8d8a\u4e9a\u9a6c\u900a: \u7f51\u4e0a\u8d2d\u7269: \u5728\u7ebf\u9500\u552e\u56fe\u4e66\uff0cDVD\uff0cCD\uff0c\u6570\u7801\uff0c\u73a9\u5177\uff0c\u5bb6\u5c45\uff0c\u5316\u5986
The question is, how do I get this to be displayed properly in an HTML page?
I'm using PHP5 to process the strings. | Based on daremon's submission, here is a "unicode\_decode" function which will convert \uXXXX into their UTF counterparts.
```
function unicode_decode($str){
return preg_replace("/\\\u([0-9A-F]{4})/ie", "iconv('utf-16', 'utf-8', hex2str(\"$1\"))", $str);
}
function hex2str($hex) {
$r = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2)
$r .= chr(hexdec($hex[$i] . $hex[$i + 1]));
return $r;
}
``` | 1) I downloaded and installed a unicode font named [CODE2000](http://www.code2000.net/code2000_page.htm)
2) I wrote this:
```
<?php header('Content-Type: text/html;charset=utf-8'); ?>
<head></head>
<body style="font-family: CODE2000">
<?php
// I had to remove some strings like ': ', 'DVD', 'CD' to make it in \uXXXX format
$s = '\u5353\u8d8a\u4e9a\u9a6c\u900a\u7f51\u4e0a\u8d2d\u7269\u5728\u7ebf\u9500\u552e\u56fe\u4e66\uff0c\uff0c\uff0c\u6570\u7801\uff0c\u73a9\u5177\uff0c\u5bb6\u5c45\uff0c\u5316\u5986';
$chars = explode('\\u', $s);
foreach ($chars as $char) {
$c = iconv('utf-16', 'utf-8', hex2str($char));
print $c;
}
function hex2str($hex) {
$r = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2)
$r .= chr(hexdec($hex[$i] . $hex[$i + 1]));
return $r;
}
?>
</body>
</html>
```
3) It produced this [characters http://img267.imageshack.us/img267/9759/49139858.png](http://img267.imageshack.us/img267/9759/49139858.png) which could be correct. E.g. the 1st character (5353) is indeed [this](http://www.fileformat.info/info/unicode/char/5353/index.htm) while the 2nd one (8d8a) is [this](http://www.fileformat.info/info/unicode/char/8d8a/index.htm). Of course I cannot be 100% sure but it seems to fit. Maybe you can take it from here.
That was a good exercise :) | How to get \uXXXX to display correctly, using PHP5 | [
"",
"php",
"unicode",
"encoding",
""
] |
To cut a long story short I have a C# function that performs a task on a given Type that is passed in as an Object instance. All works fine when a class instance is passed in. However, when the object is declared as an interface I'd really like to find the concrete class and perform the action upon that class type.
Here is the ubiquitous bad example (resplendent with incorrect property casing etc):
```
public interface IA
{
int a { get; set; }
}
public class B : IA
{
public int a { get; set; }
public int b { get; set; }
}
public class C : IA
{
public int a { get; set; }
public int c { get; set; }
}
// snip
IA myBObject = new B();
PerformAction(myBObject);
IA myCObject = new C();
PerformAction(myCObject);
// snip
void PerformAction(object myObject)
{
Type objectType = myObject.GetType(); // Here is where I get typeof(IA)
if ( objectType.IsInterface )
{
// I want to determine the actual Concrete Type, i.e. either B or C
// objectType = DetermineConcreteType(objectType);
}
// snip - other actions on objectType
}
```
I'd like the code in PerformAction to use Reflection against it's parameter and see that it's not just an instance of IA but that it's an instance of B and to see the property "b" via GetProperties(). If I use .GetType() I get the Type of IA - not what I want.
How can PerformAction determine the underlying Concrete Type of the instance of IA?
Some might be tempted to suggest using an Abstract class but that is just the limitation of my bad example. The variable will be originally declared as an interface instance. | ```
Type objectType = myObject.GetType();
```
Should still give you the concrete type, according to your example. | I have to agree about the bad design. If you have an interface, it should be because you need to utilize some common functionality without caring what the concrete implementation is. Given your example, it sounds like the PerformAction method should actually be a part of the interface:
```
public interface IA
{
int a { get; set; }
void PerformAction();
}
public class B: IA
{
public int a { get; set; }
public int b { get; set; }
public void PerformAction()
{
// perform action specific to B
}
}
public class C : IA
{
public int a { get; set; }
public int c { get; set; }
public void PerformAction()
{
// perform action specific to C
}
}
void PerformActionOn(IA instance)
{
if (instance == null) throw new ArgumentNullException("instance");
instance.PerformAction();
// Do some other common work...
}
B b = new B();
C c = new C();
PerformActionOn(b);
PerformActionOn(c);
``` | Finding the Concrete Type behind an Interface instance | [
"",
"c#",
"interface",
"types",
"concrete",
""
] |
> **Possible Duplicate:**
> [byte + byte = int… why?](https://stackoverflow.com/questions/941584/byte-byte-int-why)
I have a method like this:
```
void Method(short parameter)
{
short localVariable = 0;
var result = localVariable - parameter;
}
```
Why is the result an `Int32` instead of an `Int16`? | It's not just subtraction, there simply exisits no short (or byte/sbyte) arithmetic.
```
short a = 2, b = 3;
short c = a + b;
```
Will give the error that it cannot convert int (a+b) to short (c).
One more reason to almost never use short.
Additional: in any calculation, short and sbyte will always be 'widened' to int, ushort and byte to uint. This behavior goes back to K&R C (and probaly is even older than that).
The (old) reason for this was, afaik, efficiency and overflow problems when dealing with char. That last reason doesn't hold so strong for C# anymore, where a char is 16 bits and not implicitly convertable to int. But it is very fortunate that C# numerical expressions remain compatible with C and C++ to a very high degree. | All operations with integral numbers smaller than Int32 are widened to 32 bits before calculation by default. The reason why the result is Int32 is simply to leave it as it is after calculation. If you check the MSIL arithmetic opcodes, the only integral numeric type they operate with are Int32 and Int64. It's "by design".
If you desire the result back in Int16 format, it is irrelevant if you perform the cast in code, or the compiler (hypotetically) emits the conversion "under the hood".
Also, the example above can easily be solved with the cast
```
short a = 2, b = 3;
short c = (short) (a + b);
```
The two numbers would expand to 32 bits, get subtracted, then truncated back to 16 bits, which is how MS intended it to be.
The advantage of using short (or byte) is primarily storage in cases where you have massive amounts of data (graphical data, streaming, etc.)
P.S. Oh, and the article is "a" for words whose pronunciation starts with a consonant, and "an" for words whose pronunciated form starts with a vowel. A number, AN int. ;) | Why is the result of a subtraction of an Int16 parameter from an Int16 variable an Int32? | [
"",
"c#",
".net",
"variables",
""
] |
I have a class that has a dozen or so properties that represent various financial fields. I have another class that needs to perform some calculations on each of those fields separately. The code inside those calculation methods are identical except for the field that it does the calculation on.
Is there a way that I can pass a property name as a parameter and just have one method that does all of the performing work instead of the 12 methods for each property?
Also, I'm sure this can be accomplished via reflection, but I've seen in other code where lambdas are used in this same kind of fashion and was wondering if this is a candidate where this can be used.
As requested, here is an example:
```
public class FinancialInfo
{
public virtual DateTime AuditDate { get; set; }
public virtual decimal ReleasedFederalAmount { get; set; }
public virtual decimal ReleasedNonFederalAmount { get; set; }
public virtual decimal ReleasedStateAmount { get; set; }
public virtual decimal ReleasedLocalAmount { get; set; }
public virtual decimal ReleasedPrivateAmount { get; set; }
// more fields like this
}
public class FinancialLedger()
{
public virtual DateTime? BeginDate { get; set; }
public virtual DateTime? EndDate { get; set; }
public virtual IList<FinancialInfo> Financials { get; set; } //not actual implementation, but you get the idea
public decimal GetTotalReleasedFederalAmountByDate()
{
if (BeginDate == null && EndDate == null)
return 0;
decimal total = 0;
foreach (var fi in Financials)
{
if (someCondition)
if (someSubCondition)
total += fi.ReleasedFederalAmount;
else if (someOtherCondition)
if (someOtherSubCondition)
total += fi.ReleasedFederalAmount;
else if (anotherCondigion)
total += fi.ReleasedFederalAmount;
}
return total;
}
public decimal GetTotalReleasedNonFederalAmountByDate()
{
// same logic as above method,
// but it accesses fi.ReleasedNonFederalAmount;
}
// More methods the same as the previous, just accessing different
// members of FinancialInfo
}
```
My goal is to just make one method called GetTotalAmountByDate() and pass in a begin date, and end date and the name of the property (ReleasedFederalAmount or ReleasedLocalAmount, etc.) it needs to access.
I hope this depicts accurately what I'm trying to accomplish. | You don't need reflection if your properties are all numeric and can be homogeneously treated as a single type - let's say a `decimal`.
Something like this should do the trick:
```
protected decimal ComputeFinancialSum( DateTime? beginDate, DateTime? endDate,
Func<FinancialInfo,decimal> propertyToSum )
{
if (beginDate == null && endDate == null)
return 0;
decimal total = 0;
foreach (var fi in Financials)
{
if (someCondition)
if (someSubCondition)
total += propertyToSum(fi);
else if (someOtherCondition)
if (someOtherSubCondition)
total += propertyToSum(fi);
else if (anotherCondigion)
total += propertyToSum(fi);
}
return total;
}
```
You can then provide appropriately named versions for all of your specific cases:
```
public decimal GetTotalReleasedFederalAmountByDate()
{
return ComputeFinancialSum( BeginDate, EndDate,
(x) => x.ReleasedFederalAmount );
}
public decimal GetTotalReleasedNonFederalAmountByDate()
{
return ComputeFinancialSum( BeginDate, EndDate,
(x) => x.ReleasedNonFederalAmount );
}
// other versions ....
``` | What if your properties are not the same type (let say you need to use and int and long property as parameter) ?
Based on this answer you could then improve it by creating a generic method
<https://stackoverflow.com/a/1179210/1461862>
```
protected decimal ComputeFinancialSum<T>( DateTime? beginDate, DateTime? endDate,
Func<FinancialInfo,T> propertyToSum )
{
if (beginDate == null && endDate == null)
return 0;
decimal total = 0;
foreach (var fi in Financials)
{
if (someCondition)
if (someSubCondition)
total += propertyToSum(fi);
else if (someOtherCondition)
if (someOtherSubCondition)
total += propertyToSum(fi);
else if (anotherCondigion)
total += propertyToSum(fi);
}
return total;
}
```
Then you can just pass a function that maps to different fields with different types
```
public decimal GetTotalReleasedFederalAmountByDate()
{
return ComputeFinancialSum<int>( BeginDate, EndDate,
(x) => x.ReleasedFederalAmountInteger );
}
public decimal GetTotalReleasedNonFederalAmountByDate()
{
return ComputeFinancialSum<long>( BeginDate, EndDate,
(x) => x.ReleasedNonFederalAmountLong );
}
```
I have taken then original code from the answer to show a way, but I have actually used this to use a linq expresion like
```
IEnumerable.Where(fieldToUse== null).OrderDescendingBy(fieldToUse)
```
To filter and order a collection based on any property type | How can I pass a property of a class as a parameter of a method? | [
"",
"c#",
"lambda",
""
] |
I need to retrieve values from CakePHP's config file database.php from one of my controllers.
I'm maintaining an ex-employee's code, so I'm not positive how much of this adheres to default structures. I'm hoping this is fairly straightforward, but I can't seem to Google the right info.
File: app/config/database.php
```
class DATABASE_CONFIG
{
var $db1 =
array('driver' => 'mysqli',
'connect' => 'mysql_connect',
'host' => 'localhost',
'login' => 'username',
'password' => 'password',
'database' => 'schema',
'prefix' => '');
}
```
File: app/controllers/my\_controller.php
```
// here is where I need to retrieve
// the database login and password values
```
What syntax can I use here? Is it even possible to retrieve these values, or are they only accessible to the guts of the CakePHP framework? | ```
$fields = get_class_vars('DATABASE_CONFIG')
echo $fields['db1']['login'];
``` | Well, I have to say the above answer is a much quicker and simpler method than what I've been using, but just for argument's sake:
```
App::Import('ConnectionManager');
$ds = ConnectionManager::getDataSource('default');
$dsc = $ds->config;
echo $dsc['host'];
echo $dsc['login'];
echo $dsc['password'];
echo $dsc['database'];
```
I guess if anything this protects your code from a change in the name of the 'DATABASE\_CONFIG' class. | CakePHP: Accessing database.php values | [
"",
"php",
"cakephp",
""
] |
I am programming a simple game in Java but I am trying to do it 'right' with a nice clean design and no hacks.
I have two classes `GamePanel` that receives clicks and keypresses and `Model` which contains all the Entities and is responsible for their updates. The Model needs to know where the user's mouse is but I can't decide on the 'right' way to do it.
Should the `Model` and every `Entity` within keep a reference to the `GamePanel` or just cache the last known mouse position and receive updates from the `GamePanel` regularly. With the first option when the model is created it will need to be given a reference to the `GamePanel` and with the second the last mouse position will be sent as a parameter to the `World.update()` method.
Neither of these solutions seem elegant so I was wondering if there is a 'right' way to do this that I have missed.
Thanks,
Ben. | In my opinion, it would depend on how your classes are interacting. Is a change in the mouse position triggering the entities in the Model class? or Is the Model class independent of the GamePanel and only works on the current values of Mouse position?
If the later and in that case I agree with what jeff has said before me. Pass a handle on the GamePanel to the Model class when creating it and let every entity use the handle to access the mouse position whenever needed. That way the updated mouse position is always used.
If the former I would suggest use Observers to let the Model class know when the mouse position value has changed. Then Model class could use the same design (i.e let the Model class have an handle on the GamePanel class always) and access the current values in the GamePanel.
To sum up my answer to your question, I think it is only logical and conforming to OO concepts to let the GamePanel hold the values of the mouse position and let other classes access that information using a GamePanel instance.
Thanks,
Rohan. | A common solution is to fire events. In this case GamePanel would fire an event informing all interested (subscribed to the event) objects (Entity) in Model of the new mouseposition.
In this way, GamePanel does not need to know explicitly which Entities to inform, and the Entities do not need to keep an instance of GamePanel around.
My advice: read up on event listeners. (Java.util) | OO game design question | [
"",
"java",
"design-patterns",
"oop",
""
] |
**UPDATE:** I found a solution. See my Answer below.
## My Question
How can I optimize this query to minimize my downtime? I need to update over 50 schemas with the number of tickets ranging from 100,000 to 2 million. Is it advisable to attempt to set all fields in tickets\_extra at the same time? I feel that there is a solution here that I'm just not seeing. Ive been banging my head against this problem for over a day.
Also, I initially tried without using a sub SELECT, but the performance was *much* worse than what I currently have.
## Background
I'm trying to optimize my database for a report that needs to be run. The fields I need to aggregate on are very expensive to calculate, so I am denormalizing my [existing schema](https://gist.github.com/82b992328d6d32d00d9c) a bit to accommodate this report. Note that I simplified the tickets table quite a bit by removing a few dozen irrelevant columns.
My report will be aggregating ticket counts by **Manager When Created** and **Manager When Resolved**. This complicated relationship is diagrammed here:
[](https://i.stack.imgur.com/baPE4.png)
(source: [mosso.com](http://cdn.cloudfiles.mosso.com/c163801/eav.png))
To avoid the half dozen nasty joins required to calculate this on-the-fly I've added the following table to my schema:
```
mysql> show create table tickets_extra\G
*************************** 1. row ***************************
Table: tickets_extra
Create Table: CREATE TABLE `tickets_extra` (
`ticket_id` int(11) NOT NULL,
`manager_created` int(11) DEFAULT NULL,
`manager_resolved` int(11) DEFAULT NULL,
PRIMARY KEY (`ticket_id`),
KEY `manager_created` (`manager_created`,`manager_resolved`),
KEY `manager_resolved` (`manager_resolved`,`manager_created`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
```
The problem now is, I haven't been storing this data anywhere. The manager was always calculated dynamically. I have **millions** of tickets across several databases with the same schema that need to have this table populated. I want to do this in as efficient a way as possible, but have been unsuccessful in optimizing the queries I'm using to do so:
```
INSERT INTO tickets_extra (ticket_id, manager_created)
SELECT
t.id,
su.user_id
FROM (
SELECT
t.id,
shift_times.shift_id AS shift_id
FROM tickets t
JOIN shifts ON t.shop_id = shifts.shop_id
JOIN shift_times ON (shifts.id = shift_times.shift_id
AND shift_times.dow = DAYOFWEEK(t.created)
AND TIME(t.created) BETWEEN shift_times.start AND shift_times.end)
) t
LEFT JOIN shifts_users su ON t.shift_id = su.shift_id
LEFT JOIN shift_positions ON su.shift_position_id = shift_positions.id
WHERE shift_positions.level = 1
```
This query takes over an hour to run on a schema that has > 1.7 million tickets. This is unacceptable for the maintenance window I have. Also, it doesn't even handle calculating the manager\_resolved field, as attempting to combine that into the same query pushes the query time into the stratosphere. My current inclination is to keep them separate, and use an UPDATE to populate the manager\_resolved field, but I'm not sure.
Finally, here is the EXPLAIN output of the SELECT portion of that query:
```
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: <derived2>
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 167661
Extra:
*************************** 2. row ***************************
id: 1
select_type: PRIMARY
table: su
type: ref
possible_keys: shift_id_fk_idx,shift_position_id_fk_idx
key: shift_id_fk_idx
key_len: 4
ref: t.shift_id
rows: 5
Extra: Using where
*************************** 3. row ***************************
id: 1
select_type: PRIMARY
table: shift_positions
type: ALL
possible_keys: PRIMARY
key: NULL
key_len: NULL
ref: NULL
rows: 6
Extra: Using where; Using join buffer
*************************** 4. row ***************************
id: 2
select_type: DERIVED
table: t
type: ALL
possible_keys: fk_tickets_shop_id
key: NULL
key_len: NULL
ref: NULL
rows: 173825
Extra:
*************************** 5. row ***************************
id: 2
select_type: DERIVED
table: shifts
type: ref
possible_keys: PRIMARY,shop_id_fk_idx
key: shop_id_fk_idx
key_len: 4
ref: dev_acmc.t.shop_id
rows: 1
Extra:
*************************** 6. row ***************************
id: 2
select_type: DERIVED
table: shift_times
type: ref
possible_keys: shift_id_fk_idx
key: shift_id_fk_idx
key_len: 4
ref: dev_acmc.shifts.id
rows: 4
Extra: Using where
6 rows in set (6.30 sec)
```
Thank you so much for reading! | Well, I found a solution. It took a lot of experimentation, and I think a good bit of blind luck, but here it is:
```
CREATE TABLE magic ENGINE=MEMORY
SELECT
s.shop_id AS shop_id,
s.id AS shift_id,
st.dow AS dow,
st.start AS start,
st.end AS end,
su.user_id AS manager_id
FROM shifts s
JOIN shift_times st ON s.id = st.shift_id
JOIN shifts_users su ON s.id = su.shift_id
JOIN shift_positions sp ON su.shift_position_id = sp.id AND sp.level = 1
ALTER TABLE magic ADD INDEX (shop_id, dow);
CREATE TABLE tickets_extra ENGINE=MyISAM
SELECT
t.id AS ticket_id,
(
SELECT m.manager_id
FROM magic m
WHERE DAYOFWEEK(t.created) = m.dow
AND TIME(t.created) BETWEEN m.start AND m.end
AND m.shop_id = t.shop_id
) AS manager_created,
(
SELECT m.manager_id
FROM magic m
WHERE DAYOFWEEK(t.resolved) = m.dow
AND TIME(t.resolved) BETWEEN m.start AND m.end
AND m.shop_id = t.shop_id
) AS manager_resolved
FROM tickets t;
DROP TABLE magic;
```
## Lengthy Explanation
Now, I'll explain why this works, and my relative though process and steps to get here.
First, I knew the query I was trying was suffering because of the huge derived table, and the subsequent JOINs onto this. I was taking my well-indexed tickets table and joining all the shift\_times data onto it, then letting MySQL chew on that while it attempts to join the shifts and shift\_positions table. This derived behemoth would be up to a 2 million row unindexed mess.
Now, I knew this was happening. The reason I was going down this road though was because the "proper" way to do this, using strictly JOINs was taking an even longer amount of time. This is due to the nasty bit of chaos required to determine who the manager of a given shift is. I have to join down to shift\_times to find out what the correct shift even is, while simultaneously joining down to shift\_positions to figure out the user's level. I don't think the MySQL optimizer handles this very well, and ends up creating a HUGE monstrosity of a temporary table of the joins, then filtering out what doesn't apply.
So, as the derived table seemed to be the "way to go" I stubbornly persisted in this for a while. I tried punting it down into a JOIN clause, no improvement. I tried creating a temporary table with the derived table in it, but again it was too slow as the temp table was unindexed.
I came to realize that I had to handle this calculation of shift, times, positions sanely. I thought, maybe a VIEW would be the way to go. What if I created a VIEW that contained this information: (shop\_id, shift\_id, dow, start, end, manager\_id). Then, I would simply have to join the tickets table by shop\_id and the whole DAYOFWEEK/TIME calculation, and I'd be in business. Of course, I failed to remember that MySQL handles VIEWs rather assily. It doesn't materialize them at all, it simply runs the query you would have used to get the view for you. So by joining tickets onto this, I was essentially running my original query - no improvement.
So, instead of a VIEW I decided to use a TEMPORARY TABLE. This worked well if I only fetched one of the managers (created or resolved) at a time, but it was still pretty slow. Also, I found out that with MySQL you can't refer to the same table twice in the same query (I would have to join my temporary table twice to be able to differentiate between manager\_created and manager\_resolved). This is a big WTF, as I can do it as long as I don't specify "TEMPORARY" - this is where the CREATE TABLE magic ENGINE=MEMORY came into play.
With this pseudo temporary table in hand, I tried my JOIN for just manager\_created again. It performed well, but still rather slow. Yet, when I JOINed again to get manager\_resolved in the same query the query time ticked back up into the stratosphere. Looking at the EXPLAIN showed the full table scan of tickets (rows ~2mln), as expected, and the JOINs onto the magic table at ~2,087 each. Again, I seemed to be running into fail.
I now began to think about how to avoid the JOINs altogether and that's when I found some obscure ancient message board post where someone suggested using subselects (can't find the link in my history). This is what led to the second SELECT query shown above (the tickets\_extra creation one). In the case of selecting just a single manager field, it performed well, but again with both it was crap. I looked at the EXPLAIN and saw this:
```
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: t
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 173825
Extra:
*************************** 2. row ***************************
id: 3
select_type: DEPENDENT SUBQUERY
table: m
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 2037
Extra: Using where
*************************** 3. row ***************************
id: 2
select_type: DEPENDENT SUBQUERY
table: m
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 2037
Extra: Using where
3 rows in set (0.00 sec)
```
Ack, the dreaded DEPENDENT SUBQUERY. It's often suggested to avoid these, as MySQL will usually execute them in an outside-in fashion, executing the inner query for every row of the outer. I ignored this, and wondered: "Well... what if I just indexed this stupid magic table?". Thus, the ADD index (shop\_id, dow) was born.
Check this out:
```
mysql> CREATE TABLE magic ENGINE=MEMORY
<snip>
Query OK, 3220 rows affected (0.40 sec)
mysql> ALTER TABLE magic ADD INDEX (shop_id, dow);
Query OK, 3220 rows affected (0.02 sec)
mysql> CREATE TABLE tickets_extra ENGINE=MyISAM
<snip>
Query OK, 1933769 rows affected (24.18 sec)
mysql> drop table magic;
Query OK, 0 rows affected (0.00 sec)
```
Now **THAT'S** what I'm talkin' about!
## Conclusion
This is definitely the first time I've created a non-TEMPORARY table on the fly, and INDEXed it on the fly, simply to do a single query efficiently. I guess I always assumed that adding an index on the fly is a prohibitively expensive operation. (Adding an index on my tickets table of 2mln rows can take over an hour). Yet, for a mere 3,000 rows this is a cakewalk.
Don't be afraid of DEPENDENT SUBQUERIES, creating TEMPORARY tables that really aren't, indexing on the fly, or aliens. They can all be good things in the right situation.
Thanks for all the help StackOverflow. :-D | You should have used Postgres, lol. A simple query like this should not take more than some tens of seconds provided you have enough RAM to avoid disk thrashing.
Anyway.
=> Is the problem in the SELECT or the INSERT ?
(run the SELECT alone on a test server and time it).
=> Is your query disk bound or CPU bound ?
Launch it on a test server and check vmstat output.
If it is CPU bound, skip this.
If it is disk bound, check the working set size (ie the size of your database).
If the working set is smaller than your RAM, it should not be disk bound.
You can force loading of a table in the OS cache prior to executing a query by launching a dummy select like SELECT sum( some column ) FROM table.
This can be useful if a query selects many rows in random order from a table which is not cached in RAM... you trigger a sequential scan of the table, which loads it in cache, then random access is much faster. With some trickery you can also cache indexes (or just tar your database directory to >/dev/null, lol).
Of course, adding more RAM could help (but you need to check if the query is killing the disk or the CPU first). Or telling MySQL to use more of your RAM in the configuration (key\_buffer, etc).
If you are making millions of random HDD seeks you are in PAIN.
=> OK now the query
FIRST, ANALYZE your tables.
> LEFT JOIN shift\_positions ON su.shift\_position\_id = shift\_positions.id
> WHERE shift\_positions.level = 1
WHY do you LEFT JOIN and then add a WHERE on it ? The LEFT makes no sense. If there is no row in shift\_positions, LEFT JOIN will generate a NULL, and the WHERE will reject it.
Solution : use JOIN instead of LEFT JOIN and move (level=1) in the JOIN ON() condition.
While you're at it, also get rid of the other LEFT JOIN (replace by JOIN) unless you are really interested in all those NULLs ? (I guess you are not).
Now you probably can get rid of the subselect.
Next.
> WHERE TIME(t.created) BETWEEN shift\_times.start AND shift\_times.end)
This is not indexable, cause you have a function TIME() in the condition (use Postgres, lol).
Lets look at it :
> JOIN shift\_times ON (shifts.id = shift\_times.shift\_id
> AND shift\_times.dow = DAYOFWEEK(t.created)
> AND TIME(t.created) BETWEEN shift\_times.start AND shift\_times.end)
Ideally you would like to have a multicolumn index on shift\_times(shift\_id, DAYOFWEEK(t.created),TIME(t.created)) so this JOIN can be indexed.
Solution : add columns 'day','time' to shift\_times, containing DAYOFWEEK(t.created),TIME(t.created), filled with correct values using a trigger firing on INSERT or UPDATE.
Now create multicolumn index on (shift\_id,day,time) | How can I further optimize a derived table query which performs better than the JOINed equivalent? | [
"",
"sql",
"mysql",
"optimization",
"query-optimization",
"derived-table",
""
] |
I have an method that takes in an observable collection (returned from a webservice) of objects and analyzes them according to their attributes.
Here is the code snippet from the method
private double analyze(ObservableCollection mobjColl)
{
```
FieldInfo fi = null;
foreach (MyApp.MyObj oi in mobjColl)
{
if(oi.pressure.Equals("high"){
fi = oi.GetType().GetField("air");
.....
}
}
return someval;
}
```
My problem is that the fieldinfo fi is always null. I can access every field of the object (within foreach) using the objects name however the fieldinfo object is never populated. I even tried using GetFields method but it does not return an array...
P.S : the object fields are public. Using bindingflags in getfield didnt help either. | I don't believe objects returned from web services expose public fields. You might be thinking of properties instead. If you try `GetProperty("air")` you'll probably get something back. | GetField/GetFields without BindingFlags only look for public fields. My guess is "air" is a private field.
Instead try this:
`oi.GetType().GetField("air", BindingFlags.Instance | BindingFlags.NonPublic);` | Cannot access Object fields using fieldinfo | [
"",
"c#",
"reflection",
"observablecollection",
""
] |
**Overview:** I have set up a server and a client, where both attempt discovery of each other using UDP. When the server starts up it sends a multicast message (239.1.1.1) that it is alive. When the client starts up it sends a multicast message (239.1.1.2) that it is alive. Both server and client are subscribed to each other's multicast messages to receive their transmissions. This way, regardless of which application (server or client) starts up first, one or the other will be notified of their existence.
On the client side I do the following:
1. Set up a listening socket to subscribe to and receive server originated multicast messages.
2. Set up a receiving socket to receive server responses to client's multicast
message per #3 below.
3. Send a muticast message (for server to receive and respond to) that client is running.
4. Receive server response to clients multicast message sent in #3.
**Question:** Everything is working fine, except that both receiving sockets end up getting the server's (non-multicast) response to the client. I am not clear if this is expected behavior or not. Can I reduce the two receiving sockets to one? #1 is subscribed to the server's multicast and #2 is simply listening for a direct transmission from the server on the same port (non-multicast message from server). Can I safely remove the second receiving socket?
See source code below (I removed exception handling for simpler code presentation).
**Client code:**
```
// 1. Set up a socket and asynchronously listen for server startup multicasts.
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
listenSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
listenSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("239.1.1.1")));
EndPoint clientEndPoint = new IPEndPoint(0, 0);
listenSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length,
SocketFlags.None, ref clientEndPoint,
new AsyncCallback(OnServerMessageReceived), (object)this);
// 2. Set up socket to receive the server's response to client's multicast.
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
receiveSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
receiveSocket.ReceiveTimeout = 3000; // Timeout after 3 seconds.
// 3. Send a multicast message for server to respond to.
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
EndPoint multicastEndPoint = new IPEndPoint(IPAddress.Parse("239.1.1.2"), 50000);
sendSocket.SendTo(packet, packet.Length, SocketFlags.None, multicastEndPoint);
// 4. Wait for server to respond to the multicast message (timeout = 3 seconds).
byte[] receiveBuff = new byte[2048];
EndPoint serverEndPoint = new IPEndPoint(0, 0);
int bytesRead = receiveSocket.ReceiveFrom(receiveBuff, ref serverEndPoint);
```
**Server code:**
```
// Receive multicast message sent from client (in asynchronous callback method).
EndPoint clientEndPoint = new IPEndPoint(0, 0);
int bytesRead = listenSocket.EndReceiveFrom(asyncResult, ref clientEndPoint);
// Send response back to the client (change port to 50000).
EndPoint destination = new IPEndPoint((clientEndPoint as IPEndPoint).Address,
50000);
Socket responseSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
responseSocket.SendTo(response, response.Length, SocketFlags.None, destination);
``` | The answer to your question is "Yes, this is expected behaviour". You don't need to open a seperate socket to recieve unicast packets on the same port.
**PS**
It seems like overkill to have your servers join a multicast group to listen for new clients - you could just have the servers regularly transmit a beacon to the client multicast address saying "I am here" (say, once every 30 seconds). | ```
receiveSocket.Bind(new IPEndPoint(IPAddress.Any, 50000));
```
Your receive sockets are binding to ANY address, which means they will receive unicast, broadcast and multicast traffic. You can bind to an interface address to just receive unicast traffic, and you can bind just to the multicast group to only receive multicast traffic.
When sending a UDP datagram you can specify the destination address which may be multicast or unicast. You can therefore reduce both the server and client code to one socket each. | Why UDP socket subscribed to a multicast group is picking up a non-multicast message? | [
"",
"c#",
"sockets",
"udp",
"multicast",
""
] |
I'm writing a browser plugin, similiar to Flash and Java in that it starts downloading a file (.jar or .swf) as soon as it gets displayed. Java waits (I believe) until the entire jar files is loaded, but Flash does not. I want the same ability, but with a compressed archive file. I would like to access files in the archive as soon as the bytes necessary for their decompression are downloaded.
For example I'm downloading the archive into a memory buffer, and as soon as the first file is possible to decompress, I want to be able to decompress it (also to a memory buffer).
Are there any formats/libraries that support this?
**EDIT:** If possible, I'd prefer a single file format instead of separate ones for compression and archiving, like gz/bzip2 and tar. | There are 2 issues here
1. How to write the code.
2. What format to use.
On the file format, You can't use the .ZIP format because .ZIP puts the table of contents at the end of the file. That means you'd have to download the entire file before you can know what's in it. Zip has headers you can scan for but those headers are not the official list of what's in the file.
Zip explicitly puts the table of contents at the end because it allows fast adding a files.
Assume you have a zip file with contains files 'a', 'b', and 'c'. You want to update 'c'. It's perfectly valid in zip to read the table of contents, append the new c, write a new table of contents pointing to the new 'c' but the old 'c' is still in the file. If you scan for headers you'll end up seeing the old 'c' since it's still in the file.
This feature of appending was an explicit design goal of zip. It comes from the 1980s when a zip could span multiple floppy discs. If you needed to add a file it would suck to have to read all N discs just to re-write the entire zip file. So instead the format just lets you append updated files to the end which means it only needs the last disc. It just reads the old TOC, appends the new files, writes a new TOC.
Gzipped tar files don't have this problem. Tar files are stored header, file, header file, and the compression is on top of that so it's possible to decompress as the file it's downloaded and use the files as they become available. You can create gzipped tar files easily in windows using winrar (commercial) or 7-zip (free) and on linux, osx and cygwin use the tar command.
On the code to write,
O3D does this and is open source so you can look at the code
<http://o3d.googlecode.com>
The decompression code is in o3d/import/cross/...
It targets the NPAPI using some glue which can be found in o3d/plugin/cross | Check out the [boost::zlib filters](http://www.boost.org/doc/libs/1_39_0/libs/iostreams/doc/classes/zlib.html). They make using [zlib](http://www.zlib.net/) a snap.
Here's the sample from the boost docs that will decompress a file and write it to the console:
```
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>
int main()
{
using namespace std;
ifstream file("hello.z", ios_base::in | ios_base::binary);
filtering_streambuf<input> in;
in.push(zlib_decompressor());
in.push(file);
boost::iostreams::copy(in, cout);
}
``` | Decompression and extraction of files from streaming archive on the fly | [
"",
"c++",
"compression",
"streaming",
"archive",
""
] |
I am trying to create a facebook application, all is working fine except the ajax part that I am using to populate a second box from the item selected in first select box.
I am using jquery (v1.3.2) for accomplishing this. This ajax is working absolutely fine on the host where I have taken space for it, but it is not working in facebook.
Here are my questions regarding to this problem,
* does canvas page url needs to be same as that of my application name. ( in my case it is different)
I am getting this error on the onchange event of parent select box inside facebook.
> Access to restricted URI denied" code: "1012
* what might be wrong...? Please help me solve this problem.
Thanks | You are not allowed to request data from other sites than the domain the script is running on. For example, if you are running the script www.example.com/script.js, then you can only ajax files under the www.exaple.com domain, not www.facebook.com.
There are a few ways to do it:
* [JSONp](http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback) is a way, but it requires that
facebook replies with jsonp data. Not
sure if it does. More info on JSONp [here](http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/).
* [CSSHttpRequest](http://nb.io/hacks/csshttprequest) (or AJACSS) is another way. Seriously doubt facbook uses this method. | There is a limitation when using ajax that the xmlhttp request may not be cross-domain. See <https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript>
A common workaround for this is to make the ajax request to a backend script that will actually make the cross-domain request i.e. cURL. | jquery's ajax not working in facebook apps | [
"",
"php",
"jquery",
"ajax",
"facebook",
"cakephp",
""
] |
Can anyone tell me how can I get the height of horizontal scrollbar in ListView in C#? is it the same as the standard Horizontal scrollbar, if so is there any windows function that return that? basically I'm using ListView with OwnerDraw and want to know exactly how big is my client area which excludes ColumnHeader area and HorizontalScrollbar area.
Thanks | [`SystemInformation.HorizontalScrollBarHeight`](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.horizontalscrollbarheight.aspx) | Control.ClientRectangle excludes scrollbars and borders.
```
listView1.Scrollable = true;
Console.WriteLine(listView1.ClientRectangle);
Console.WriteLine(listView1.Size);
listView1.Scrollable = false;
Console.WriteLine(listView1.ClientRectangle);
Console.WriteLine(listView1.Size);
``` | How to get height of horizontal scrollbar in a ListView | [
"",
"c#",
""
] |
I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key?
```
$(document).keypress(function(e) {
if (e.which == 13) $('.save').click(); // enter (works as expected)
if (e.which == 27) $('.cancel').click(); // esc (does not work)
});
``` | Try with the [keyup event](https://api.jquery.com/keyup/):
```
$(document).on('keyup', function(e) {
if (e.key == "Enter") $('.save').click();
if (e.key == "Escape") $('.cancel').click();
});
``` | Rather than hardcode the keycode values in your function, consider using named constants to better convey your meaning:
```
var KEYCODE_ENTER = 13;
var KEYCODE_ESC = 27;
$(document).keyup(function(e) {
if (e.keyCode == KEYCODE_ENTER) $('.save').click();
if (e.keyCode == KEYCODE_ESC) $('.cancel').click();
});
```
Some browsers (like FireFox, unsure of others) define a global `KeyEvent` object that exposes these types of constants for you. [This SO question](https://stackoverflow.com/questions/1465374/javascript-event-keycode-constants) shows a nice way of defining that object in other browsers as well. | Which keycode for escape key with jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm writing a templated C++ generic container class that can optionally maintain its contents in a well-defined order. Previously it used function pointers to order its contents in a sensible type-specific way, but I am attempting to change it to use templated functor arguments instead.
Since it's often the case that the class's user might want to keep items of the same type sorted in different ways in different containers, the container class takes an optional template argument that lets the user optionally specify his own compare-functor:
```
template <class ItemType, class CompareFunctorType = CompareFunctor<ItemType> > class MyContainer
{
[...]
};
```
If the class user doesn't specify a custom functor type, it uses the following CompareFunctor definition by default:
```
template <typename ItemType> class CompareFunctor
{
public:
bool IsItemLessThan(const ItemType & a, const ItemType & b) const
{
return (a<b); // will compile only for types with < operator
}
};
```
This works great for built-in types and also user-defined types where a less-than operator has been defined. However, I'd like it to also automatically work for types where there is no built-in or explicitly defined less-than operator. For those types, the ordering of the items within the container is not important.
The motivation is that I use this container to hold a lot of different types, and most of the time, I don't care about the order of the types in the container, but in some cases I do... and I don't want to have to go in and add "dummy" less-than operators to all of these different types just so I can use them with this container class... and I don't want to have to explicitly specify a custom "dummy" CompareFunctor argument every time I use the table to store items that don't have a less-than operator.
So, is there a way I can use template specialization (or something) so that the default CompareFunctor (shown above) is used whenever possible, but in cases where that CompareFunctor would cause an error, C++ would automatically fall back to a "dummy" FallbackCompareFunctor like the one below? Or perhaps some other clever way to handle this dilemna?
```
template <typename ItemType> class FallbackCompareFunctor
{
public:
bool IsItemLessThan(const ItemType & a, const ItemType & b) const
{
return ((&a)<(&b)); // will compile for all types (useful for types where the ordering is not important)
}
};
``` | In case anyone is interested, I was able to come up with a way to do what I wanted, using a combination of the techniques described above. My proof-of-concept code (with unit test) is shown below.
```
#include <stdio.h>
// Real functor, should be used by default when ItemType has a < operator
template <typename ItemType> class RealCompareFunctor
{
public:
bool IsLessThan(const ItemType & item1, const ItemType & item2)
{
printf(" --> RealCompareFunctor called!\n");
return item1 < item2;
}
typedef ItemType TheItemType;
};
// Dummy functor, should be used by default when ItemType has no < operator
template <typename ItemType> class DummyCompareFunctor
{
public:
bool IsLessThan(const ItemType & item1, const ItemType & item2)
{
printf(" --> DummyCompareFunctor called!\n");
return (&item1) < (&item2);
}
};
namespace implementation_details
{
// A tag type returned by operator < for the any struct in this namespace when T does not support (operator <)
struct tag {};
// This type soaks up any implicit conversions and makes the following (operator <)
// less preferred than any other such operator found via ADL.
struct any
{
// Conversion constructor for any type.
template <class T> any(T const&);
};
// Fallback (operator <) for types T that don't support (operator <)
tag operator < (any const&, any const&);
// Two overloads to distinguish whether T supports a certain operator expression.
// The first overload returns a reference to a two-element character array and is chosen if
// T does not support the expression, such as < whereas the second overload returns a char
// directly and is chosen if T supports the expression. So using sizeof(check(<expression>))
// returns 2 for the first overload and 1 for the second overload.
typedef char yes;
typedef char (&no)[2];
no check(tag);
template <class T> yes check(T const&);
// Implementation for our has_less_than_operator template metafunction.
template <class T> struct has_less_than_operator_impl
{
static const T & x;
static const bool value = sizeof(check(x < x)) == sizeof(yes);
};
template <class T> struct has_less_than_operator : implementation_details::has_less_than_operator_impl<T> {};
template <bool Condition, typename TrueResult, typename FalseResult>
class if_;
template <typename TrueResult, typename FalseResult>
struct if_<true, TrueResult, FalseResult>
{
typedef TrueResult result;
};
template <typename TrueResult, typename FalseResult>
struct if_<false, TrueResult, FalseResult>
{
typedef FalseResult result;
};
}
template<typename ItemType> struct AutoChooseFunctorStruct
{
typedef struct implementation_details::if_<implementation_details::has_less_than_operator<ItemType>::value, RealCompareFunctor<ItemType>, DummyCompareFunctor<ItemType> >::result Type;
};
/** The default FunctorType to use with this class is chosen based on whether or not ItemType has a less-than operator */
template <class ItemType, class FunctorType = struct AutoChooseFunctorStruct<ItemType>::Type > class Container
{
public:
Container()
{
ItemType itemA;
ItemType itemB;
FunctorType functor;
bool isLess = functor.IsLessThan(itemA, itemB);
//printf(" --> functor says isLess=%i\n", isLess);
}
};
// UNIT TEST CODE BELOW
struct NonComparableStruct {};
struct ComparableStructOne
{
bool operator < (ComparableStructOne const&) const { return true; }
};
struct ComparableStructTwo {};
bool operator < (ComparableStructTwo const&, ComparableStructTwo const&) { return true; }
class NonComparableClass
{
public:
NonComparableClass() {/* empty */}
};
class ComparableClass
{
public:
ComparableClass() {/* empty */}
bool operator < (const ComparableClass & rhs) const {return (this < &rhs);}
};
int main(int argc, char * argv[])
{
printf("\nContainer<int>\n");
Container<int> c1;
printf("\nContainer<ComparableStructOne>\n");
Container<ComparableStructOne> c2;
printf("\nContainer<ComparableStructTwo>\n");
Container<ComparableStructTwo> c3;
printf("\nContainer<NonComparableStruct>\n");
Container<NonComparableStruct> c4;
printf("\nContainer<NonComparableClass>\n");
Container<NonComparableClass> c5;
printf("\nContainer<ComparableClass>\n");
Container<ComparableClass> c6;
return 0;
}
``` | For your default unsorted case, use a Null Comparison functor that just returns false for all cases.
You can then specialise your template to a sorted container using the std::less() functor.
```
template<class T>
struct NullCompare: public binary_function <T, T, bool>
{
bool operator()(const T &l, const T &r) const
{
// edit: previously had "return true;" which is wrong.
return false;
}
};
template <class T, class Compare=NullCompare<T> >
class MyContainer
{
[...]
};
template <class T, class Compare=std::less<T> >
class MySortedContainer : public MyContainer<T, Compare>
{
[...]
};
``` | C++ templated container class: How to best support both ordered and un-ordered item types? | [
"",
"c++",
"templates",
"containers",
"specialization",
""
] |
What are some Oracle gotchas for someone new to the platform, but not new to relational databases (MySQL, MS SQL Server, Postgres, etc.) in general.
Two examples of the kind of things I'm looking for
1. Many relational database products handle creating an auto\_increment key for you. Oracle does not, you must manually create the sequence, then create the trigger
2. When INSERTING data via the SQL Developer interface, you have to manually commit the data
Bonus points for PHP related gotchas, as that's the platform ~~I'll~~ this hypothetical experienced newb will be using. | ### Note: I'm explaining only the gotchas here, i. e. situations when `Oracle` behaves not as other systems do. `Oracle` has numerous benefits over other `RDBMS`'s, but they are not the topic of the post.
* You cannot `SELECT` without `FROM`.
```
SELECT 1
```
will fail, you need to:
```
SELECT 1
FROM dual
```
* Empty string and `NULL` are the same thing.
```
SELECT *
FROM dual
WHERE '' = ''
```
returns nothing.
* There are neither `TOP` nor `LIMIT`. You limit your results in the `WHERE` clause:
```
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
col
)
WHERE rownum < 10
```
exactly this way, using a subquery, since `ROWNUM` is evaluated before `ORDER BY`.
* You cannot nest the correlated subqueries more than one level deep. This one will fail:
```
SELECT (
SELECT *
FROM (
SELECT dummy
FROM dual di
WHERE di.dummy = do.dummy
ORDER BY
dummy
)
WHERE rownum = 1
)
FROM dual do
```
This is a problem.
* `NULL` values are not indexed. This query will not use an index for ordering:
```
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
col
)
WHERE rownum < 10
```
, unless `col` is marked as `NOT NULL`.
Note than it's `NULL` *values* that are not indexed, not *columns*. You can create an index on a nullable column, and non-`NULL` values will get into the index.
However, the index will not be used when the query condition assumes that `NULL` values can possibly satisfy it.
In the example above you want all value to be returned (including `NULL`s). Then index doesn't know of non-`NULL` values, hence, cannot retrieve them.
```
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
col
)
WHERE rownum < 10
```
But this query will use the index:
```
SELECT *
FROM (
SELECT *
FROM mytable
WHERE col IS NOT NULL
ORDER BY
col
)
WHERE rownum < 10
```
, since non-`NULL` values cannot ever satisfy the condition.
* By default, `NULL`s are sorted last, not first (like in `PostgreSQL`, but unlike `MySQL` and `SQL Server`)
This query:
```
SELECT *
FROM (
SELECT 1 AS id
FROM dual
UNION ALL
SELECT NULL AS id
FROM dual
) q
ORDER BY
id
```
will return
```
id
---
1
NULL
```
To sort like in `SQL Server` and `MySQL`, use this:
```
SELECT *
FROM (
SELECT 1 AS id
FROM dual
UNION ALL
SELECT NULL AS id
FROM dual
) q
ORDER BY
id NULLS FIRST
```
Note that it breaks `rownum` order unless the latter is not used out of the subquery (like explained above)
* `"MYTABLE"` and `"mytable"` (double quotes matter) are different objects.
```
SELECT *
FROM mytable -- wihout quotes
```
will select from the former, not the latter. If the former does not exist, the query will fail.
```
CREATE TABLE mytable
```
creates `"MYTABLE"`, not `"mytable"`.
* In `Oracle`, all implicit locks (that result from `DML` operations) are row-level and are never escalated. That is no row not affected by the transaction can be implicitly locked.
Writers never block readers (and vice versa).
To lock the whole table, you should issue an explicit `LOCK TABLE` statement.
Row locks are stored on the datapages.
* In `Oracle`, there are no "`CLUSTERED` indexes", there are "index-organized tables". By default, tables are heap organized (unlike `SQL Server` and `MySQL` with `InnoDB`).
In `Oracle` world, a "clustered storage" means organizing several tables so that the rows which share a common key (from several tables) also share a datapage.
A single datapage hosts multiple rows from multiple tables which makes joins on this key super fast. | SELECT 1 wont work, do select 1 from dual instead.
If you work with hierarchical data, connect by is great. | Oracle Gotchas for An Experienced Newb | [
"",
"php",
"mysql",
"sql-server",
"oracle",
"postgresql",
""
] |
In `C#`, I want to use a regular expression to match any of these words:
```
string keywords = "(shoes|shirt|pants)";
```
I want to find the whole words in the content string. I thought this `regex` would do that:
```
if (Regex.Match(content, keywords + "\\s+",
RegexOptions.Singleline | RegexOptions.IgnoreCase).Success)
{
//matched
}
```
but it returns true for words like `participants`, even though I only want the whole word `pants`.
How do I match only those literal words? | You should add the word delimiter to your regex:
```
\b(shoes|shirt|pants)\b
```
In code:
```
Regex.Match(content, @"\b(shoes|shirt|pants)\b");
``` | Try
```
Regex.Match(content, @"\b" + keywords + @"\b", RegexOptions.Singleline | RegexOptions.IgnoreCase)
```
`\b` matches on word boundaries. See [here](http://www.regular-expressions.info/wordboundaries.html) for more details. | Regex.Match whole words | [
"",
"c#",
".net",
"regex",
""
] |
From what I've read,
```
yield return <value>
```
jumps out of the function the moment the line is executed. However, Scott Guthrie's text indicates that
```
var errors = dinner.GetRuleViolations();
```
successfully pulls out a list of all the rule violations even though GetRuleViolations is a long list of
```
if(String.someFunction(text))
yield return new RuleViolation("Scary message");
if(String.anotherFunction(text))
yield return new RuleViolation("Another scary message");
```
How does this work? | It doesn't return a list. It returns an `IEnumerable<RuleViolation>`. `yield return` returns a value in an [iterator method](http://msdn.microsoft.com/en-us/library/dscyy5s0(VS.80).aspx). An iterator is an easy way to generate a sequence of elements in a method. | See [yield (C# reference)](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx)
> The yield keyword uses what's known as
> lazy evaluation. What this means
> practically is that anything following
> a "yield return" will not be evaluated
> until it is requested from the
> enumerator.
Also have a look at Eric Lippert's blog on Iterator Blocks.
[Part 1](http://blogs.msdn.com/ericlippert/archive/2009/07/09/iterator-blocks-part-one.aspx)
[Part 2 - Why No Ref or Out Parameters](http://blogs.msdn.com/ericlippert/archive/2009/07/13/iterator-blocks-part-two-why-no-ref-or-out-parameters.aspx)
[Part 3 - Why No yield in finally](http://blogs.msdn.com/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx)
[Part 4 - Why No yield in catch](http://blogs.msdn.com/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx)
[Part 5 - Push vs Pull](http://blogs.msdn.com/ericlippert/archive/2009/07/23/iterator-blocks-part-five-push-vs-pull.aspx)
[Part 6 - Why no unsafe code](http://blogs.msdn.com/ericlippert/archive/2009/07/27/iterator-blocks-part-six-why-no-unsafe-code.aspx) | How does the NerdDinner example's Dinner.GetRuleViolations function return a list? | [
"",
"c#",
"asp.net-mvc",
"nerddinner",
"yield-return",
""
] |
I started learning Python through some books and online tutorials. I understand the basic syntax and operations, but I realize that the correct way to understand the language would be to actually do a project on it.
Now when i say a project, I mean something useful, maybe some web app. I started searching for web programming in python and landed on a couple of tutorials referencing a very complex code. most of it was based upon, i think, CGI programming.
now what i would really appreciate is if someone could provide certain guidelines on how a beginner like me can understand the various aspects of programming the web through python. because the things i am seeing are just confusing me. can anyone please help? | If you want to create a powerful web application with Python, Django is the way to go. You can start with the documentation at <http://docs.djangoproject.com/en/dev/> or the [Django Book](http://www.djangobook.com/en/2.0/) (I recommend the latter). It's a bit complicated to grasp as a beginner, but it's totally worth the hassle :)
Good Luck! | +1 for django, though the "django book" is a little simpler to understand (especially if you're just getting start with python): <http://www.djangobook.com/en/2.0/> | python web programming | [
"",
"python",
"web-applications",
""
] |
I'd like to only get the worddpress navigation (header, navigation menu, footer) so I can
add custom pages to the site which can easily integrate in the general template of the side while showing other things in the center instead of blog postings?
Edit: To clarify, I'd either like to know if there's an easy way to include the functions like `header()`, `footer()` (or whatever they're called) of Wordpress in another page, so where those functions are called, it echoes the general layout of Wordpress.
Or, I'd like to know which html files I can include to display the wordpress template's header, footer, and navagiation menu on a page.
What I'm trying to do is build my own pages on a website, outside of wordpress, which will use my own framework and php code, but call the wordpress's template to make the look & feel of the pages integrate with the rest of the site. | Add the following lines of code, then you can use whatever WP function you want:
```
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
```
Example from my own site:
```
<?php
define('WP_USE_THEMES', false);
require('./wordpress/wp-blog-header.php');
get_header();
?>
``` | <http://codex.wordpress.org/wp_list_pages>
What I would do is:
```
<ul>
<?php wp_list_pages('title_li='); ?>
<li>my page links...</li>
</ul>
``` | Getting Wordpress navigation inside another page | [
"",
"php",
"wordpress",
""
] |
What is the maximum length URL?
This is may be handset dependent; on a desktop, it is definitely browser dependent, as discussed in [this question](https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-an-url/417184).
I am interested in specifications or references as much as empirical data.
My particular usecase is passing a very long (about 1600 character) URL to a `MIDlet.platformRequest(String url)`, which is failing. The majority of the URL (some 1575 characters) is query.
Are there any other considerations for passing very long URLs about (e.g. mobile proxies and gateways truncating the URL)? | Short answer: it depends, but probably long enough.
Long answer, following investigation on SonyEricsson J2ME emulator (WTK 2.2.4), a K610i, and Samsung U700V.
---
Empirically testing: from the emulator, the `platformRequest()` passes the URL straight to the desktop browser (Firefox in this case).
```
http://test.example.com/?q=2048xxxxxxxxxxxxxxxxxxxxxxxxxxxx... xxxxxxxxxxxxxxxxxx2048
```
Looking at the logs of a test server, we see we can pass through very long URLs from the emulator to the desktop to the server.
On a device (in this case, a SonyEricsson K610i, user agent: "SonyEricssonK610i/R1CB Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1") can handle at least a URL of at least 3072 characters (upper bound c.3800).
On a second device Samsung U700V, user agent: "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7 MG(Novarra-Vision/7.3)", the lower bound for URL length was 2048, but upper bound was less than 3072. Note that this could be a problem with Novarra transcoder, which has been known to (at least) re-write user-agent strings.
Without the Novarra transcode (switching networks), the U700V has a user agent "SAMSUNG-SGH-U700-Vodafone/BUGK1 SHP/VPP/R5 NetFront/3.4 Qtv5.3 SMM-MMS/1.2.0 profile/MIDP-2.0 configuration/CLDC-1.1", and has a lower bound of 3072 chars.
---
This effectively ends my interest in the answer to this question, as this empirical testing invalidates my theory that an upper bound on URL length is causing my problem.
However, for completeness, I will include a potential cause of my problem:
The URL needed to connect has at least two query parameters. The ampersands separating the queries seem to confuse the emulator.
The emulator silently drops the second parameter.
On the Samsung, without a second parameter, the browser connects, but the long parameter is corrupted or missing.
On the K610i when a second parameter is used, the browser does not start properly. | According to the HTTP spec, you can rely on at least 255 characters, but beyond that it is browser specific. For example, IE limits the path part of the URL to 2048 characters, according to various sources, and Apache apparently complains about URLs > ~4000 characters.
Source: [WWW FAQs: What is the maximum length of a URL?](http://www.boutell.com/newfaq/misc/urllength.html)
I could not find any references to a URL limits for J2ME browsers.
UPDATE: "In the field of mobile browsing, URL limitation can be much lower. Many handsets still don’t support URLs longer than 128, 256 or 512 characters, in particular WAP devices (as opposed to devices carrying a full blown HTTP browser)."
Source: [Maximum URL Length Web Analytics](http://wacb.pedia.ch/archives/51) | What is the maximum length a URL can be to be opened in a J2ME browser? | [
"",
"java",
"url",
"java-me",
""
] |
I am getting a following exception while enumerating through a queue:
> System.InvalidOperationException:
> Collection was modified; enumeration
> operation may not execute
here is the code excerpt:
```
1: private bool extractWriteActions(out List<WriteChannel> channelWrites)
2: {
3: channelWrites = new List<WriteChannel>();
4: foreach (TpotAction action in tpotActionQueue)
5: {
6: if (action is WriteChannel)
7: {
8: channelWrites.Add((WriteChannel)action);
9: lock(tpotActionQueue)
10: {
11: action.Status = RecordStatus.Batched;
12: }
13: }
14: }
15: return (channelWrites.Count > 0);
16: }
```
I think I understand the problem - altering the hashtable at `action.Status = RecordStatus.Batched`, which screws up the MoveNext() on enumerator.
Question is, how do I implement that "pattern" correctly? | You are allowed to change the value in an item in a collection. The error you're getting means that an item was either added or removed i.e.: the collection itself was modified, not an item inside the collection. This is most likely caused by another thread adding or removing items to this collection.
You should lock your queue at the beginning of your method, to prevent other Threads modifying the collection while you are accessing it. Or you could lock the collection before even calling this method.
```
private bool extractWriteActions(out List<WriteChannel> channelWrites)
{
lock(tpotActionQueue)
{
channelWrites = new List<WriteChannel>();
foreach (TpotAction action in tpotActionQueue)
{
if (action is WriteChannel)
{
channelWrites.Add((WriteChannel)action);
action.Status = RecordStatus.Batched;
}
}
}
return (channelWrites.Count > 0);
}
``` | I think I had a similar exception when using a `foreach` loop on a Collection where I tried to remove items from the Collection (or it may have been a List, I can't remember). I ended up getting around it by using a `for` loop. Perhaps try something like the following:
```
for (int i=0; i<tpotActionQueue.Count(); i++)
{
TpotAction action = tpotActionQueue.Dequeue();
if (action is WriteChannel)
{
channelWrites.Add((WriteChannel)action);
lock(tpotActionQueue)
{
action.Status = RecordStatus.Batched;
}
}
}
``` | System.InvalidOperationException: Collection was modified | [
"",
"c#",
"collections",
"thread-safety",
""
] |
I've added a new library to my application (multiple projects-DLLs) - SQLite, to perform some in memory caching. There is just one library/project that is affected by this change - Lib1.
A build goes through fine. All libraries are built successfully and no errors are reported, including a couple of Com Objects.
If I try to register the com objects, I get the The *DLL could not be loaded. Check to make sure all required application runtime files and other dependent DLLs are available in the component DLL's directory or the system path.* message. But all the libs are at the same place. And all are in the path. A copy of this project builds and registers fine (without the few changes made for SqlLite ofcourse). Dependency walker reports no issues
Oddly, if I try to register the DLL of the com object (using regsvr32) it works fine. Also, I have another library, which is dependant on Lib1 (not on SqlLite) which also cannot be loaded.
Any ideas?
Thanks,
A'z | You can use Process Monitor (<http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx>) set to filter process name regsvr32.exe in order to see all file and registry access.
Always use full path to your-com-dll when you issue regsvr32 commands, if you have the same dll somewhere else in path (for example c:\windows\system32) regsvr32 will use the other dll and not the one in your current directory.
Another trick would be to use "rundll32 your-com-dll,DllRegisterServer". In case of missing dlls it will tell which dll is missing instead of just saying that LoadLibrary failed.
**Edit**:
What do you mean by "If I try to register the com objects"? How are you doing this? I'm asking because you say that regsvr32 on the dll which actually implements these com object works fine. | And so, the plot thickens!!!!
I've actually **narrowed down the to the line of code** that causes this linking problem.
In the modified library (LIB1) I've added a new class A1 which inherits from an existing class A.
When I change an existing class B which used to inherit from A to now inherit from A1 - this is when the problem is caused. Class B is in a lib3.
I've verified that just **when I change the inheritance, only then the problem occurs!!!**
I've used file-mon on regsvr32 when loading successfully and when failing. I stuggle to find the difference! Tomorrow morning I'll try Process Monitor and see if it helps.
Still desperate for help,
A'z | C++ Linking and COM Registration issue | [
"",
"c++",
"windows",
"com",
"linker",
""
] |
Does anyone know how to set a C# console application's icon in the code (not using project properties in Visual Studio)? | You can't specify an executable's icon in code - it's part of the binary file itself.
From the command line you'd use `/win32icon:<file>` if that's any help, but you can't specify it within the code of the application. Don't forget that most of the time the application's icon is displayed, your app isn't running at all!
That's assuming you mean the icon for the file itself in explorer. If you mean the icon of the application *while it's running* if you just double-click the file, I believe that will always just be the icon for the console itself. | You can change it in the project properties.
See this Stack Overflow article: [Is it possible to change a console window's icon from .net?](https://stackoverflow.com/questions/1285798/is-it-possible-to-change-a-console-windows-icon-from-net)
To summarize right click on your project (not the solution) in Visual Studio and select properties. At the bottom of the "Application" tab there is a section for "Icon and manifest" where you can change the icon. | C# console application icon | [
"",
"c#",
"console-application",
"imageicon",
""
] |
I have a really long list of itinerary items with integer values. I was thinking about creating a database with each of these items with like fifty columns but that seemed a bit long-winded, and the itinerary may change. Is there a better way to store these name => value pairs in a database? serializing seems a bit crude, I was thinking about just creating an itinerary\_items db with name, value columns and sticking the data in there. What is the best solution? | Why not save them like like properties in a table. that is
```
| id| name | value |
+---+------------+--------------+
| 1 | array_key | array_value |
| 2 | array_key2 | array_value2 |
```
If one wants multiple instances of the array, one could always add an extra key for keeping track of the instances:
```
| id| name | value | instance_key |
+---+------------+--------------+--------------+
| 1 | array_key | array_value | 1 |
| 2 | array_key2 | array_value2 | 1 |
| 3 | array_key | array_value | 2 |
| 4 | array_key2 | array_value2 | 2 |
```
Problem with the approach of using this kinds of solutions is that the data tend to be more less human-readable and there be alot of extra joins if you have several properties on an object. | How many records do you have? Hundreds? Thousands?
If your record count is below 500 then I don't think you should pick up a database at all. You could store that in a XML file. These are the times of [NoSQL](http://www.computerworld.com/s/article/9135086/No_to_SQL_Anti_database_movement_gains_steam_) :).
Not that I support the movement, but a database seems like overambition for your requirement. | Storing a large array in a database | [
"",
"php",
"database",
"cakephp",
""
] |
I am trying to parse XML with Python but not getting very far. I think it's due to wrong XML tree this API returns.
So this is what is returned by the GET request:
```
<codigo>3</codigo><valor></valor><operador>Dummy</operador>
```
The GET request goes here:
```
http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&cliente=XX
```
This is the Python code I am using without any luck:
```
import urllib
from xml.dom import minidom
url = urllib.urlopen('http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&cliente=XX')
xml = minidom.parse(url)
code = doc.getElementsByTagName('codigo')
print code[0].data
```
And this is the response I get:
```
xml.parsers.expat.ExpatError: junk after document element: line 1, column 18
```
What I need to do is retrieve the value inside the `<codigo>` element and place it in a variable (same for the others). | The main problem here is that the XML code being returned by that service doesn't include a root node, which is invalid. I fixed this by simply wrapping the output in a `<root>` node.
```
import urllib
from xml.etree import ElementTree
url = 'http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&cliente=XX'
xmldata = '<root>' + urllib.urlopen(url).read() + '</root>'
tree = ElementTree.fromstring(xmldata)
codigo = tree.find('codigo').text
print codigo
```
You can use whatever parser you wish, but here I used ElementTree to get the value. | An XML document consists of *one* top level document element, and then multiple subelements. Your XML fragment contains multiple top level elements, which is not permitted by the XML standard.
Try returning something like:
```
<result><codigo>3</codigo><valor></valor><operador>Dummy</operador></result>
```
I have wrapped the entire response in a `<result>` tag. | xml.parsers.expat.ExpatError on parsing XML | [
"",
"python",
"xml",
""
] |
I have a class like the following:
```
class User:
def __init__(self):
self.data = []
self.other_data = []
def doSomething(self, source):
// if source = 'other_data' how to access self.other_data
```
I want to pass a string for the source variable in `doSomething` and access the class member of the same name.
I have tried `getattr` which only works on functions (from what I can tell) as well as having `User` extend `dict` and using `self.__getitem__`, but that doesn't work either. What is the best way to do this? | `x = getattr(self, source)` will work just perfectly if `source` names ANY attribute of self, including the `other_data` in your example. | A picture's worth a thousand words:
```
>>> class c:
pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
``` | Python: access class property from string | [
"",
"python",
"syntax",
""
] |
Is there anyway to find out the ssid of the wifi access point you are connected to within the browser using javascript?
If there isn't my guess would you'd have to write a plugin for it. I bet ActiveX allows this. | No there isn't and for a good reason :)
*Update:* I should have elaborated, JavaScript is run inside a browser sandbox that was designed to protect both security and privacy. ESSID of AP you're connected to is of course not a secret, but it's also not an information that should be revealed without ones consent. | Using Javascript? No.
I would be extremely surprised to find that there's a non-OS/Browser-specific hack to do this. | Is there anyway to find out the ssid of the wifi access point within the browser using javascript? | [
"",
"javascript",
"wifi",
"ssid",
""
] |
I'm using a DLL with the following function in C# Visual Studio 2008:
```
[DllImport("slpapi62", EntryPoint = "_SlpGetPrinterName@12")]
public static extern int SlpGetPrinterName(int nIndex, string strPrinterName, int nMaxChars);
```
Calling this function, `strPrinterName` is suppose to return a string.
```
string name = "";
SlpGetPrinterName(0, name, 128);
```
How can i get this parameter to pass by reference? | Pass a `StringBuilder` object instead of a string:
```
[DllImport("slpapi62", EntryPoint = "_SlpGetPrinterName@12")]
public static extern int SlpGetPrinterName(int nIndex, StringBuilder strPrinterName, int nMaxChars);
```
Calling it:
```
StringBuilder name = new StringBuilder(128);
int value = SlpGetPrinterName(0, name, name.Capacity);
``` | Use a `StringBuilder` object for the string parameter. | How do I pass a parameter by reference to managed code in C#? | [
"",
"c#",
"visual-studio-2008",
""
] |
I have several block a elements that I want to be side-by-side to create a menu. The width of each is set to auto to accommodate the text inside. Each a element is displayed as a table cell and can work with either absolute or relative positioning.
Thanks for any help.
Mike | display:inline-block | If you float block elements, they'll be placed in a horizontal row (with dynamic widths unless you specify a fixed one.)
```
ul#navigation li {
float: left;
}
```
Have a look at the HTML for the navigation on this page, for example (Questions, Tags, Users, ...) | How can I line block elements up in a row? | [
"",
"javascript",
"html",
"css",
""
] |
I'm defining a database for a customer/ order system where there are two highly distinct types of customers. Because they are so different having a single customer table would be very ugly (it'd be full of null columns as they are pointless for one type).
Their orders though are in the same format. Is it possible to have a `CustomerId` column in my Order table which has a foreign key to both the Customer Types? I have set it up in SQL server and it's given me no problems *creating* the relationships, but I'm yet to try inserting any data.
Also, I'm planning on using nHibernate as the ORM, could there be any problems introduced by doing the relationships like this? | No, you can't have a single field as a foreign key to two different tables. How would you tell where to look for the key?
You would at least need a field that tells what kind of user it is, or two separate foreign keys.
You could also put the information that is common for all users in one table and have separate tables for the information that is specific for the user types, so that you have a single table with user id as primary key. | A foreign key can only reference a single primary key, so no. However, you could use a bridge table:
```
CustomerA <---- CustomerA_Orders ----> Order
CustomerB <---- CustomerB_Orders ----> Order
```
So Order doesn't even *have* a foreign key; whether this is desirable, though... | Multiple foreign keys to a single column | [
"",
"sql",
"sql-server",
"nhibernate",
"database-design",
""
] |
When using a framework method, the description you get when you highlight over it will list the exception(s) possibly raised.
Does it matter if you write the catch handlers in this order? E.g. SqlConnection.Open() can throw:
System.InvalidOperationException
System.Data.SqlClient.SqlException
It is listed in that order. Should my catch handlers follow this order? If so, why?
Also, some methods such as SqlDataAdapter.Fill() return an int but no error is reported by Visual Studio if I don't have a variable to store the return value. Why?
Thanks | You should place your catch handlers not in the order they are listed in the documentation, but in the order of priority for your particular circumstances.
In saying that, if you are accessing a SQL Server database and get a SQL exception then it is unlikely your application will be able to continue, so the `SqlException` should probably be high priority.
**Update**: I omitted the part about the order of Exception inheritance (from most derived to base), as I incorrectly assumed this was a given. Other posters mentioned this explicitly. | The order is irrelevant unless one of the exceptions named in a catch handler inherits from another exception named in another handler, in which case the more-derived catch should come first (or it will never be called).
The runtime will go through the catch blocks in the order they are listed, executing **only** the first one that matches, so if you have the following, only the first catch block will be executed, even if an ArgumentException is thrown:
```
try
{
throw new ArgumentException("foo");
}
catch (Exception ex)
{
}
catch (ArgumentException aex)
{
// Will never be executed.
}
``` | Order of catch clauses | [
"",
"c#",
"exception",
""
] |
I'm starting in C++ development, but i like to use Gedit for writing the files, but like for Ruby on Rails and many other languages, are some tools and configurations for Gedit that makes develop more easy and comfortable, and another question, what is the best for C++, SVN, CVS, Git and others...? Thanks, and sorry about my english! | For editing you can choose:
* just an editor - vi(m), emacs, etc. Here I prefer vim. But if you're not
familiar with it you may be shocked at the begging. These give posibility also run make from within the editor itself.
* IDE - KDevelop, Eclipse (+ CDT - plugin for C++), Code::Blocks. I didn't used by these,
but heard from colleagues that KDevelop is ok, while Eclipse is too have ans slow.
As for source control the choice is between SVN (this is right successor of CVS) and git.
If you develop alone or it's not big team of developers SVN should be fine. It uses central repository to store the data.
git in contrast is distributed source control tool. I found it pretty complicated to used to.
So if you don't need "distributed" feature of git, choose SVN. | The two most important plugins for Gedit are "External Tools" (allows you to run make or whatever other command you want with a keystroke) and "Snippets" (avoids retyping boilerplate code).
Also, have a look at <http://live.gnome.org/Gedit/Plugins>, you will probably find something useful.
As for version control - I would recommend git, it is faster and has more features. SVN can work OK too. Do not use CVS unless someone points a gun at your head. | Setup Gedit For C++ Development | [
"",
"c++",
"linux",
"svn",
"gedit",
""
] |
Does anyone have an elegant sql statement to delete duplicate records from a table, but only if there are more than x number of duplicates? So it allows up to 2 or 3 duplicates, but that's it?
Currently I have a select statement that does the following:
```
delete table
from table t
left outer join (
select max(id) as rowid, dupcol1, dupcol2
from table
group by dupcol1, dupcol2
) as keeprows on t.id=keeprows.rowid
where keeprows.rowid is null
```
This works great. But now what I'd like to do is only delete those rows if they have more than say 2 duplicates.
Thanks | ```
with cte as (
select row_number() over (partition by dupcol1, dupcol2 order by ID) as rn
from table)
delete from cte
where rn > 2; -- or >3 etc
```
The query is manufacturing a 'row number' for each record, grouped by the (dupcol1, dupcol2) and ordered by ID. In effect this row number counts 'duplicates' that have the same dupcol1 and dupcol2 and assigns then the number 1, 2, 3.. N, order by ID. If you want to keep just 2 'duplicates', then you need to delete those that were assigned the numbers `3,4,.. N` and that is the part taken care of by the `DELLETE.. WHERE rn > 2;`
Using this method you can change the `ORDER BY` to suit your preferred order (eg.`ORDER BY ID DESC`), so that the `LATEST` has `rn=1`, then the next to latest is rn=2 and so on. The rest stays the same, the `DELETE` will remove only the oldest ones as they have the highest row numbers.
Unlike [this closely related question](https://stackoverflow.com/questions/1175061/delete-records-which-are-considered-duplicates-based-on-same-value-on-a-column-an/1175205#1175205), as the condition becomes more complex, using CTEs and row\_number() becomes simpler. Performance may be problematic still if no proper access index exists. | `HAVING` is your friend
`select id, count(*) cnt from table group by id having cnt>2` | SQL Query - Delete duplicates if more than 3 dups? | [
"",
"sql",
"sql-server",
"duplicates",
""
] |
I am working on a project in eclipse that when I launch using the jetty plugin gives me a
```
java.lang.AbstractMethodError:
au.com.mycopmpany.impl.MyClassDAOImpl.findById(Ljava/lang/Integer;)Ljava/lang/Object;.
```
This file compiles fine in Eclipse and the code is implementing the method that the error talks about. From my reading this error indicates that "at runtime" the JVM finds a class that doesn't have this method implemented.
But I can assure you that the `MyClassDAOImpl` most definitely does have the `findById` method implemented with the correct signature.
This seems like a bug in the Eclipse compiler; I can fix the issue by running `maven package` from a command prompt and then running the application within Eclipse works fine.
It seems that the Eclipse compiler has some sort of bug in relation to this class. I did read something online about a bug with generics in the Eclipse compiler (which this class does use Generics) but this base class / interface is re-implemented over and over in our code base and it is this class that always has problems.
Does anyone know a workaround, or better yet, a fix for this problem?
I can replicate this exception every time, so if an Eclipse compiler developer reads this and this is a known issue, please feel free to contact me for assistance in tracking down the issue.
**Update:**
The class with the issue is one of many that implement `GenericDAO` where the Generic interface is defined as:
```
public interface GenericDAO<T, TList>
```
The method in question that is failing is:
```
public T findById(Integer integer) throws APIException;
``` | Try rebuilding your code.
I'm guessing that you've got a DAO interface, and the signatures of the interface and the impl differ slightly enough that the compiler doesn't see the interface as fully implemented by the concrete impl class. Maybe Eclipse is out of synch.
If that doesn't work, see if Eclipse lets you navigate from the interface method to the concrete implementation. If it can't, that's a clue reinforcing what the compiler is telling you.
Check your CLASSPATH. Maybe the impl that you think is being loaded by the JVM isn't.
Check the bug list if you think it's a problem with the compiler.
If you don't see a bug in list, assume that you're the problem. Lots of people use it; a bug that serious would have been discovered and fixed long ago.
Clean out the Jetty deployment - the WAR and all temp files. Rebuild and redeploy. Maybe Jetty is holding onto an older version of the .class file, which would explain why it works on the command line and not when you deploy to the web.
Assume that you're the problem first, last, and always.
UPDATE: Is there a way to switch the JDK that Eclipse uses? Can you point to a Sun JDK?
This is another reason why I detest Eclipse. Your story, if true, would make me even happier to be an IntelliJ user.
Question: Are you implementing [IBM's generic DAO](http://www.ibm.com/developerworks/java/library/j-genericdao.html)? | Try disabling internal-weaving: (`eclipselink.weaving.internal=false` in persistence.xml) | java.lang.AbstractMethodError running a webapp in Eclipse with jetty. | [
"",
"java",
"eclipse",
"jetty",
""
] |
Why did Java's designers consider it useful/necessary? | Using method-local classes can increase the readability of your code by keeping related parts together. As a contrived example, suppose you have a method that needs to create a thread to do something in the background:
```
class Test {
void f() {
// Method local inner class
class InnerClass {
private String myThreadName;
// InnerClass constructor
public InnerClass(String myThreadName) {
this.myThreadName = myThreadName;
}
// InnerClass method
public void run() {
Thread thread = new Thread(
// Anonymous inner class inside method local inner class
new Runnable() {
public void run() {
doSomethingBackgroundish();
}
}
);
thread.setName(myThreadName);
thread.start();
}
}
InnerClass anInnerClass = new InnerClass(aThreadName);
anInnerClass.run();
}
}
```
Without method-local classes, you would have to either:
* create a new named class inside `Test` to do the background processing, or
* create a new named class in a *separate source file* to do the background processing.
Both these options can reduce the readability of the code by moving the related processing somewhere else in your source tree (maybe in the same source file, maybe in another source file entirely). Using a method-local class keeps the processing logic right where it is used.
This is certainly not applicable for all situations, but it can be very useful in a number of common situations. Such code is commonly used for GUI action listeners, which are very small classes that usually just relay action method calls from one place to another. | Since most people probably have never seen a method-local inner class, here is an example:
```
public class TestMethodLocalInnerClass
{
public static void main(String[] args)
{
class Greeter implements Runnable
{
private final String _greeted;
public Greeter(String greeted)
{
super();
_greeted = greeted;
}
public void run()
{
System.out.printf("Hello %s!\n", _greeted);
}
}
new Greeter("world").run();
new Greeter("dog").run();
}
}
```
This could theoretically be useful as an additional level of encapsulation below an inner class when an anonymous class can't be used because you need more than one instance. Maybe if you need say different comparators in different methods and need to instantiate them more than once. This seems to be very very rare (I never wrote such a class before), and it is not a big deal to use normal inner classes instead.
So in my view it would not be worth to include it in a newly designed language. | What's the use of a method-local inner class? | [
"",
"java",
""
] |
I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the `readline` module which offers functions like: `read_history_file`, `write_history_file`, and `set_startup_hook`. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:
(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:
```
def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
```
(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:
```
def ex():
import readline
readline.write_history_file('.python_history')
exit()
```
It's very annoying to have to exit using parentheses, though: `ex()`. Is there some python sugar that would allow `ex` (without the parens) to run the `ex` function?
Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.
Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:
```
def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
```
By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap. | I think the suggestions in the Python documentation pretty much cover what you want. Look at the example pystartup file toward the end of section 13.3:
* <http://docs.python.org/tutorial/interactive.html>
or see this page:
* <http://rc98.net/pystartup>
But, for an out of the box interactive shell that provides all this and more, take a look at using IPython:
* <http://ipython.scipy.org/moin/> | Try using [IPython](http://ipython.scipy.org/moin/) as a python shell. It already has everything you ask for. They have packages for most popular distros, so install should be very easy. | Persistent Python Command-Line History | [
"",
"interpreter",
"python",
""
] |
I have a question on how to determine an object's Nullable property type.
`ObjectA` has a property `DateTime? CreateDate;`
When I iterate through its properties like the following code, how do I check if a property is a `Nullable DateTime` type?
```
foreach (PropertyInfo pi in ObjectA.GetType().GetProperties())
{
//do the compare here
}
``` | ```
pi.PropertyType == typeof(DateTime?)
``` | ```
pi.PropertyType == typeof(Nullable<DateTime>);
``` | C# determine a Nullable property DateTime type when using reflection | [
"",
"c#",
"reflection",
"nullable",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.