Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a .jsp page where I have a GUI table that displays records from an Oracle database. This table allows typical pagination behaviour, such as "FIRST", "NEXT", "PREVIOUS" and "LAST". The records are obtained from a Java ResultSet object that is returned from executing a SQL statement.
This ResultSet might be very big, so my question is:
If I have a ResultSet containing one million records but my table only displays the data from the first ten records in the ResultSet, is the data only fetched when I start requesting record data or does all of the data get loaded into memory entirely once the ResultSet is returned from executing a SQL statement? | The Java ResultSet is a pointer (or cursor) to the results in the database. The ResultSet loads records in blocks from the database. So to answer your question, the data is only fetched when you request it but in blocks.
If you need to control how many rows are fetched at once by the driver, you can use the [setFetchSize(int rows)](https://docs.oracle.com/javase/10/docs/api/java/sql/ResultSet.html#setFetchSize(int)) method on the ResultSet. This will allow you to control how big the blocks it retrieves at once. | The JDBC spec does not specify whether the data is streamed or if it is loaded into memory. Oracle streams by default. MySQL does not. To get MySQL to stream the resultset, you need to set the following on the Statement:
```
pstmt = conn.prepareStatement(
sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
pstmt.setFetchSize(Integer.MIN_VALUE);
``` | Does a ResultSet load all data into memory or only when requested? | [
"",
"java",
"database",
"jdbc",
""
] |
Suppose I have the two following Linq queries I want to refactor:
```
var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
.Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
.Take( 10 );
```
Note that only the Where parameter changes. There is any way to put the query inside a method and pass the Where parameter as an argument? | Of couse there is. The where parameter is just a simple closure of type `Func<T, bool>` (where T is the type of your DB items - I don't know them out of your code) and you can wrap it into a (anonymous) function.
```
Func<Func<T, bool>, IEnumerable<T>> MakeQuery = (Func<T, bool> whereParam) => db.TableAs.Where(whereParam).Take(10);
```
Use it like this
```
var query1 = MakeQuery(a => a.TableBS.Count() > someValue1);
``` | You can using [`Predicate<T>`](http://msdn.microsoft.com/de-de/library/bfcke1bz.aspx).
```
public IQueryable<TableA> Helper(Predicate<TableA> predicate)
{
return db.TableAs.Where(predicate).Take(10);
}
```
The just call it like that.
```
var query1 = Helper(a => a.TableBs.Count() > someValue1);
var query2 = Helper(a => a.TableBs.First().item1 == someValue2);
```
And give a better namen than `Helper`. | How to refactor multiple similar Linq queries? | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"refactoring",
""
] |
I'd like to calculate the mean of an array in Python in this form:
```
Matrice = [1, 2, None]
```
I'd just like to have my `None` value ignored by the `numpy.mean` calculation but I can't figure out how to do it. | You are looking for [masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html). Here's an example.
```
import numpy.ma as ma
a = ma.array([1, 2, None], mask = [0, 0, 1])
print "average =", ma.average(a)
```
From the numpy docs linked above, "The numpy.ma module provides a nearly work-alike replacement for numpy that supports data arrays with masks." | haven't used numpy, but in standard python you can filter out `None` using list comprehensions
or the filter function
```
>>> [i for i in [1, 2, None] if i != None]
[1, 2]
>>> filter(lambda x: x != None, [1, 2, None])
[1, 2]
```
and then average the result to ignore the `None` | How to use numpy with 'None' value in Python? | [
"",
"python",
"numpy",
"mean",
""
] |
I'm always using an output variable in PHP where I gather all the content before I echo it. Then I read somewhere (I don't remember where, though) that you get best performance if you split the output variable into packets and then echo each packet instead of the whole output variable.
How is it really? | If you are outputting really big strings with echo, it is better to use multiple echo statements.
This is because of the way [Nagle's algorithm](http://en.wikipedia.org/wiki/Nagle%27s_algorithm) causes data to be buffered over TCP/IP.
Found an note on Php-bugs about it:
<http://bugs.php.net/bug.php?id=18029> | This will automatically break up big strings into smaller chunks and echo them out:
```
function echobig($string, $bufferSize = 8192) {
$splitString = str_split($string, $bufferSize);
foreach($splitString as $chunk) {
echo $chunk;
}
}
```
Source: <http://wonko.com/post/seeing_poor_performance_using_phps_echo_statement_heres_why> | PHP echo performance | [
"",
"php",
"performance",
"printing",
"echo",
""
] |
I'm sure the answer is something obvious, and I'm kind of embarrassed that I don't really know the answer already, but consider the following code sample I picked up while reading "Professional ASP.NET MVC 1.0":
```
public static class ControllerHelpers
{
public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors)
{
foreach (RuleViolation issue in errors)
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
```
I understand what this static method is doing, but what I don't understand is what purpose the word "this" is serving in the method signature. Can anyone enlighten me? | That is a new C# 3.0 feature called [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx).
It means, that you add a new method to your ModelStateDictionary objects. You can call it like a normal method:
```
yourModelStateDictionary.AddRuleViolations( errors );
```
See, that the first parameter (the 'this'-parameter) is skipped. It assigns just ModelStateDictionary as a valid target for your extension method.
The clue is, that you can do this with any class - even sealed or 3rd party classes, like .Net framework classes (for instance on object or string). | It means the method in question is an "extension method" and can be called as if it was a method of the class itself. See this [article](http://msdn.microsoft.com/en-us/library/bb383977.aspx). | What does "this" mean when used as a prefix for method parameters? | [
"",
"c#",
"extension-methods",
"language-features",
""
] |
Simplifying
I have a text box and a button
The button just create an messagebox with the text from the textbox.
But i change the value of the textbox, the new value apears (Ex: Type 123) but the message box does not show the value.
If i try to use the value in the programming (get the value by textbox1.text) the variable has nothing ( textbox1.text = "") but i can still see what i typed in the form.
Anyone has any clue? | Thanks Eric and Crippledsmurf. As both of you said, its hard to help without the code.
The problem I found is that when calling the form, I send some objects by reference, so I can track them down and I found that when (don't ask me why it happens that way, I'm still working on it) the construtor is called he make an new component, so the component in the interface no longer represents the one pointed by the variable "textbox1" (Yes Crash893, I haven't mispelled the name).
I found that I was making some mess with the references, and probably that was causing the problem. I fixed the problem by changing the actions performed by references for delegates and events, but I couldn't track down the exactly source of the problem.
Thanks, again, everyone for the insights. | Your button's click event handler should look something like this
```
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox.Text);
}
```
I suspect you already have code similar to this and that at some point the textbox is cleared or otherwise set to String.Emppty but without seeing actual code it is difficult to help you | Problem changing values in textbox | [
"",
"c#",
"winforms",
""
] |
Scenario:
I have a base class "MyBase".
I have a custom attribute "MyAttrib"
With that I do this:
```
[MyAttrib(1234)]
class MyClass : MyBase()
{
MyClass()
{
}
}
```
Question:
Can I in any way force classes inherting from MyBase to have the attribute MyAttrib? | No, there is no way to have the compiler require an attribute in C#. You do have some other options available to you. You could write a unit test that reflects on all types in the assembly and checks for the attribute. But unfortunately there is no way to have the compiler force the usage of an attribute. | No longer relevant to the original poster I imagine, but here's something for anyone who's curious like I was if this was doable.
The following works, but sadly it's not a compile-time check and as such **I can't honestly recommend it used**. You're better off with interfaces, virtuals and abstracts for most things.
The required attribute:
```
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class RequiredRandomThingAttribute : Attribute { /* ... */ }
```
Parent class that requires it for derived classes:
```
public class ParentRequiringAttribute
{
public ParentRequiringAttribute()
{
if (this.GetType().GetCustomAttributes(typeof(RequiredRandomThingAttribute), false).Length == 0)
throw new NotImplementedException(this.GetType().ToString());
}
}
```
And to confirm it all works:
```
[RequiredRandomThing()]
public class CompleteSubclass : ParentRequiringAttribute { /* ... */ }
public class IncompleteSubclass : ParentRequiringAttribute { /* ... */ }
static public int Main(string[] args)
{
var test1 = new CompleteSubclass();
var test2 = new IncompleteSubclass(); // throws
}
```
It should be fairly easy to improve the validation, but my own investigation stopped here. | Force usage of custom attribute | [
"",
"c#",
"attributes",
""
] |
I have a list of dictionaries, e.g:
```
dictList = [
{'a':3, 'b':9, 'c':4},
{'a':9, 'b':24, 'c':99},
{'a':10, 'b':23, 'c':88}
]
```
All the dictionaries have the same keys e.g. *a*, *b*, *c*. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same keys from all the dictionaries in the original list.
So for the above example, the output should be:
```
{'a':22, 'b':56, 'c':191}
```
What would be the most efficient way of doing this? I currently have:
```
result = {}
for myDict in dictList:
for k in myDict:
result[k] = result.setdefault(k, 0) + myDict[k]
``` | If all dicts have all keys, you could do this as:
```
>>> dict((key, sum(d[key] for d in dictList)) for key in dictList[0])
{'a': 22, 'b': 56, 'c': 191}
```
**[Edit]** If speed is a big priority, you can also shave off ~20% (though at the cost of some readability) with the following instead:
```
import operator, itertools
dict((key, sum(itertools.imap(operator.itemgetter(key), dictList)))
for key in dictList[0])
```
The speed depends on the size of the dict. I get the following timings for the original 3 item list, and for various different sizes (created by mutliplying the original list by 10, 100 or 1000 etc):
```
List Size Original dict+generator imap+itemgetter
3 0.054 0.090 0.097
30 0.473 0.255 0.236
300 4.668 1.884 1.529
3000 46.668 17.975 14.499
```
(All times for 10,000 runs)
So it's slightly slower for just 3, but two to three times as fast for larger lists. | Try this.
```
from collections import defaultdict
result = defaultdict(int)
for myDict in dictList:
for k in myDict:
result[k] += myDict[k]
``` | How to create single Python dict from a list of dicts by summing values with common keys? | [
"",
"python",
""
] |
I'm trying to create a Google Map with multiple markers on it, that loads an alert when a marker is clicked.
```
var map = null;
function setupMap() {
map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
map.setCenter(new GLatLng( 0, 0 ), 1);
map.enableDoubleClickZoom();
// Create the marker icon - will be repeated for each icon but
// truncated for brevity in example
var icon1 = new GIcon(G_DEFAULT_ICON);
icon1.image = "uploads/1.jpg";
icon1.shadow = "";
icon1.iconSize = new GSize( 50, 50 );
var latlng = new GLatLng( 0, 0 );
markerOptions = { icon:icon1 };
marker1 = new GMarker( latlng, markerOptions );
map.addOverlay( marker1 );
GEvent.addListener( marker1, "click", loadInfo(1) );
}
function loadInfo( a ) {
alert( a );
}
window.onload = setupMap;
```
In the working example, I'll pass the marker object to loadInfo() and then load an InfoWindow, but for now, I'm just trying to get the action to happen when the marker is clicked. What's actually happening is that an alert box is loading (with the '1' in it, as expected) when the map loads. Multiple markers don't load multiple alert boxes, and after the initial alert box has loaded (which I don't want) clicking the markers doesn't do anything.
Any help is much appreciated, thanks! | In your `addListener` invocation, you're actually calling `loadInfo` instead of passing a reference to it. Try the following instead:
```
GEvent.addListener( marker1, "click", function() {
loadInfo(1);
});
```
This will create an anonymous function which wraps your `loadInfo` method, calling the method when the anonymous function is executed.
Alternatively, if you weren't using any parameters in `loadInfo`, simply removing the parentheses would work too:
```
GEvent.addListener( marker1, "click", loadInfo);
```
Something worth keeping in mind when using such function references is the scope in which it will be called. If you were to use the `'this'` reference, you'll run into the situation where `'this'` within the callback function will in fact not refer to the scope in which it was created, but to the scope within which it's being executed which most likely will not contain the fields or methods you're expecting to call, resulting in errors stating `Undefined` instead. As Jonathan points out, you'll have to use the `call()` and `apply()` methods to bind explicitly to ensure your function executes within the correct scope. | You're calling loadInfo in the .addListener, not providing a refernce to it.
```
GEvent.addListener( marker1, "click", loadInfo(1) );
```
try:
```
function wrap(method) {
var args = Array.prototype.slice.apply(arguments,1);
return function () {
return method.apply(this,args);
}
}
GEvent.addListener( marker1, "click", wrap(loadInfo,1) );
```
see <http://www.alistapart.com/articles/getoutbindingsituations> for more information on binding arguments to functions.
also see <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply> for more information on the very useful apply() (also recommended you look at call() as well) | Google Maps - load window on marker click | [
"",
"javascript",
"google-maps",
""
] |
What is the easiest way to traverse a hashtable's keys in ascending alphabetical order? | This is fairly dependent upon what the type of the key is. But lets assume for a minute that they are strings. You could use the following LINQ query
```
Hashtable table = GetHashTable();
var keys = table.Keys.Cast<String>().OrderBy(x => x);
```
For more complex structures the LINQ query is only slightly different. Lets assume you had the following definition for a key
```
struct Name {
public string First;
public string Last;
// Equality code omitted
}
```
The LINQ code would be the following
```
Hashtable table = GetHashtable();
var keys = table.Keys.Cast<Name>().OrderBy(x => x.First).ThenBy(x => x.Last);
``` | Well, I found this snippet to be the most suitable to my situation:
```
Hashtable settings = GetSettings();
ArrayList keys = new ArrayList();
keys.AddRange(settings.Keys);
keys.Sort();
foreach (object key in keys)
{
// Logic here
}
``` | How to traverse keys of a Hashtable in alphabetical order? | [
"",
"c#",
"key",
"hashtable",
"traversal",
""
] |
```
$('<a/>').click(function(event) { ChangeXYZ(event); });
```
Problem with above is i do not want event but i someother var.
```
$('<a/>').click(function() { ChangeXYZ(var123); });
```
But problem with line is, it is getting value of var123 at runtime and as i am adding this in loop so always end up using last value of var123. Looks like it is using reference for var123. How can i make it use value of var123 when this was created instead of click time. | use closures
```
function (val) {
return function() {
ChangeXYZ(val);
}
}(var123);
```
note: not tested, but should work.
edit: fixed spelling | Let's say your for-loop looked like this:
```
for (var var123=0; var123<10; var123++) {
$('<a/>').click(function() { ChangeXYZ(var123); });
}
```
Change this to:
```
for (var var123=0; var123<10; var123++) {
(function() {
$('<a/>').click(function() { ChangeXYZ(var123); });
})();
}
```
Wrapping the for-loop with a closure would do the trick. In fact, if you run your program through JSLint, you'll get a warning saying "Be careful when making functions within a loop. Consider putting the function in a closure." | jquery.click(callmethod) | [
"",
"javascript",
"jquery",
""
] |
Running Umbraco 4x I am creating a helper method in C# that I can recursively call to create child categories of a particular node (category).
The method takes a parentNodeID as a parameter. I need to retrieve the properties of that parent node. I know I can use the static method Node.GetCurrent() but I'm looking for something like Node.GetNodeById(parentNodeID).
I just can't see where this method lives. I know there is the umbraco.library.getNodeXMLbyId method, but does that give me the name property of the node?
Me Umbraco N00b :) | You can just do
```
var node = new Node(nodeId).
```
Took me a while to find it too! | Use this
```
umbraco.NodeFactory.Node headerNode = uQuery.GetNode(NodeId);
```
add namespace
```
using umbraco.NodeFactory;
``` | Umbraco - Get Node by ID programmatically | [
"",
"c#",
"umbraco",
""
] |
I've been trying to smoothly animate some Windows Form location but I'm having some issues if I want the speed to be variable. In other words, if I want to allow the user to select the preferred speed for animation.
I've found the following article that helped me quite a bit to perform the animation I was looking for, for my form. It seems better in every way than a BackgroundWorker or Threads approach I tried in the past:
<http://www.vcskicks.com/animated-windows-form.html>
My only problem now, is to maintain a smooth animation if I want o have different speeds for the animation. There are two values that are important in my code, **FPS** and **PX**. FPS represents frames per second (what else) and PX represents the number of pixels to move the form.
**Problem 1)** To have the smoothest possible animation, I would prefer to have the form move 1px at a time but I don't think that I will be able to move the form as fast as I want like that. Increasing the FPS value to a very high value doesn't seem to take any effect, it's like there's a limit and above that limit, there will be no visible differences. I'm sure there's a good explanation for that.
My question here is: Do you have any good solution for this problem or the only solution is to change the PX value and move the form by more than 1px if I want a faster movement?
**Problem 2)** If the solution for the question above is to change the PX value accordingly, I found out (by testing different values) that a FPS value equal to 300 would suffice my needs to move the form as slow and as fast as I want it to. Then, if I wanted 10 speeds, moving the form by 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 pixels provides slow and fast smooth animations, just as I want it. If I wanted 5 speeds, I could use 2, 4, 6, 8, 10, for instance.
My question here is: Is there any problem to use a value like 300 for FPS? Are there any bad consequences for such a value?
And here's my current code:
```
public partial class Form1 : Form {
bool dir = true;
public Form1() {
InitializeComponent();
Location = new Point(1280/2 - Width, 800/2 - Height/2);
}
private void button1_Click(object sender, EventArgs e) {
double FPS = 300;
int PX = 1;
long lastTicks = 0;
long currentTicks = 0;
double interval = (double)Stopwatch.Frequency / FPS;
while(dir ? Left <= 1280/2 : Left >= 1280/2 - Width) {
Application.DoEvents();
currentTicks = Stopwatch.GetTimestamp();
if(currentTicks >= lastTicks + interval) {
lastTicks = Stopwatch.GetTimestamp();
this.Location = new Point(dir ? Left + PX : Left - PX, Top);
this.Invalidate(); //refreshes the form
}
Thread.Sleep(1); //frees up the cpu
}
dir = !dir;
}
}
```
**Note:** This is just sample code, for testing purposes, not real code but be my guest if you want to point out some very important things that I should consider when porting this to the real application. | Try this implementation of my prior suggestion (without accounting for FPS):
```
public partial class Form1 : Form
{
private bool go;
private int dx = 1;
public Form1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (go)
{
this.Location = new Point(this.Location.X + dx, this.Location.Y);
if (Location.X < 10 || Location.X > 1200)
{
go = false;
dx = -dx;
}
else
{
this.Invalidate();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
go = true;
this.Invalidate();
}
}
```
I think you will likely have to go outside of winforms to get higher FPS. | I think Windows limits the repaint rate, so it wouldn't matter if you cranked the FPS up to insane values; if you want to see higher frame rates you'll probably have to result to something like XNA/DirectX animation.
You could use a Timer, and write an elapsed event handler that would both move & invalidate your form. To that end you wouldn't have to do the Thread.Sleep or the book-keeping with the last ticks and interval calcs, and it would happen with a regular cadence. Additionally, instead of the conditional code around the 'dir' boolean, you could negate the PX value when you want to change directions (and do additions-only instead of the ternary operator on dir); this is possible since subtraction is the same as adding a negative.
This should make your animation easier to extend to do other things. For fun, you could also create a PY to move vertically as well. Whatever the case, I hope you have some fun with it. :) | How to smoothly animate Windows Forms location with different speeds? | [
"",
"c#",
"winforms",
"performance",
"animation",
"intervals",
""
] |
I've written class to parse some xml into an object and it's not working correctly, when I try and get the value of a node I get a null rather than the contents of the node.
Here is a simplified version of my class that just does the xml parsing of a single node:
```
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlReaderCutDown {
private static Logger logger = Logger.getLogger(CtiButtonsXmlReader.class);
public static void testXml(String confFile){
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(confFile));
doc.getDocumentElement().normalize();
if (logger.isDebugEnabled()){
logger.debug("The root element is " + doc.getDocumentElement().getNodeName());
}
NodeList rows = doc.getElementsByTagName("row");
NodeList topRowButtons = ((Element)rows.item(0)).getElementsByTagName("button");
logger.debug("Top row has " +topRowButtons.getLength() + " items.");
Node buttonNode = topRowButtons.item(0);
NodeList nodeList = ((Element)buttonNode).getElementsByTagName("id");
logger.debug("Node list count for "+ "id" + " = " + nodeList.getLength());
Element element = (Element)nodeList.item(0);
String xx = element.getNodeValue();
logger.debug(xx);
String elementValue = ((Node)element).getNodeValue();
if (elementValue != null) {
elementValue = elementValue.trim();
}
else {
logger.debug("Value was null");
}
logger.debug("Node id = "+ elementValue);
} catch (ParserConfigurationException e) {
logger.fatal(e.toString(),e);
} catch (SAXException e) {
logger.fatal(e.toString(),e);
} catch (IOException e) {
logger.fatal(e.toString(),e);
} catch (Exception e) {
logger.fatal(e.toString(),e);
}
}
public static void main(String[] args){
DOMConfigurator.configure("log4j.xml");
testXml("test.xml");
}
}
```
And here is a stripped down version of my xml file:
```
<?xml version="1.0"?>
<root>
<row>
<button>
<id>this is an id</id>
<action>action</action>
<image-src>../images/img.png</image-src>
<alt-text>alt txt</alt-text>
<tool-tip>Tool tip</tool-tip>
</button>
</row>
</root>
```
This is what the logging statments output:
DEBUG XmlReaderCutDown - The root element is root
DEBUG XmlReaderCutDown - Top row has 1 items.
DEBUG XmlReaderCutDown - Node list count for id = 1
DEBUG XmlReaderCutDown -
DEBUG XmlReaderCutDown - Value was null
DEBUG XmlReaderCutDown - Node id = null
Why isn't it getting the text in the xml node?
I'm running using JDK 1.6\_10 | Because the element you get is the parent element of the text one, containing the text you need. To access the text of this element, you shall use [getTextContent](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getTextContent()) instead of getNodeValue.
For more information, see the table in the [Node](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html) javadoc. | See <http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Node.html> . Element.getNodeValue() always returns null. You should use Element.getTextContent() | Why is this java code not parsing my Xml correctly? | [
"",
"java",
"xml",
"dom",
""
] |
I have a UserControl that uses a binding converter. I've made the converter an inner class of
```
public partial class MyPanel : UserControl
{
public class CornerRadiusConverter : IValueConverter
{
```
How do I reference the Converter class from the XAML? The following does not work:
```
<controls:MyPanel.CornerRadiusConverter x:Key="CornerRadiusConverter" />
```
It gives this error:
> The tag
> 'LensPanel.CornerRadiusConverter' does
> not exist in XML namespace
> 'clr-namespace:MyApp.Windows.Controls' | I was thinking about this problem again, and I came up with something similar to Dennis's solution : create a "proxy" converter class, with a Type property, which will create the instance of the actual converter and delegate the conversion to it.
```
public class Converter : IValueConverter
{
private Type _type = null;
public Type Type
{
get { return _type; }
set
{
if (value != _type)
{
if (value.GetInterface("IValueConverter") != null)
{
_type = value;
_converter = null;
}
else
{
throw new ArgumentException(
string.Format("Type {0} doesn't implement IValueConverter", value.FullName),
"value");
}
}
}
}
private IValueConverter _converter = null;
private void CreateConverter()
{
if (_converter == null)
{
if (_type != null)
{
_converter = Activator.CreateInstance(_type) as IValueConverter;
}
else
{
throw new InvalidOperationException("Converter type is not defined");
}
}
}
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
CreateConverter();
return _converter.Convert(value, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
CreateConverter();
return _converter.ConvertBack(value, targetType, parameter, culture);
}
#endregion
}
```
You use it like that :
```
<Window.Resources>
<my:Converter x:Key="CornerRadiusConverter" Type="{x:Type controls:MyPanel+CornerRadiusConverter}"/>
</Window.Resources>
``` | It could be possible. A few months ago I wrote a markup extension to create the converter for you inline. It keeps a dictionary of weak references so that you don't create multiple instances of the same converter. Handles creating converters with different arguments too.
In XAML:
```
<TextBox Text="{Binding Converter={NamespaceForMarkupExt:InlineConverter {x:Type NamespaceForConverter:ConverterType}}}"/>
```
C#:
```
[MarkupExtensionReturnType(typeof(IValueConverter))]
public class InlineConverterExtension : MarkupExtension
{
static Dictionary<string, WeakReference> s_WeakReferenceLookup;
Type m_ConverterType;
object[] m_Arguments;
static InlineConverterExtension()
{
s_WeakReferenceLookup = new Dictionary<string, WeakReference>();
}
public InlineConverterExtension()
{
}
public InlineConverterExtension(Type converterType)
{
m_ConverterType = converterType;
}
/// <summary>
/// The type of the converter to create
/// </summary>
/// <value>The type of the converter.</value>
public Type ConverterType
{
get { return m_ConverterType; }
set { m_ConverterType = value; }
}
/// <summary>
/// The optional arguments for the converter's constructor.
/// </summary>
/// <value>The argumments.</value>
public object[] Arguments
{
get { return m_Arguments; }
set { m_Arguments = value; }
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
PropertyInfo propertyInfo = target.TargetProperty as PropertyInfo;
if (!propertyInfo.PropertyType.IsAssignableFrom(typeof(IValueConverter)))
throw new NotSupportedException("Property '" + propertyInfo.Name + "' is not assignable from IValueConverter.");
System.Diagnostics.Debug.Assert(m_ConverterType != null, "ConverterType is has not been set, ConverterType{x:Type converterType}");
try
{
string key = m_ConverterType.ToString();
if (m_Arguments != null)
{
List<string> args = new List<string>();
foreach (object obj in m_Arguments)
args.Add(obj.ToString());
key = String.Concat(key, "_", String.Join("|", args.ToArray()));
}
WeakReference wr = null;
if (s_WeakReferenceLookup.TryGetValue(key, out wr))
{
if (wr.IsAlive)
return wr.Target;
else
s_WeakReferenceLookup.Remove(key);
}
object converter = (m_Arguments == null) ? Activator.CreateInstance(m_ConverterType) : Activator.CreateInstance(m_ConverterType, m_Arguments);
s_WeakReferenceLookup.Add(key, new WeakReference(converter));
return converter;
}
catch(MissingMethodException)
{
// constructor for the converter does not exist!
throw;
}
}
}
``` | Binding converter as inner class? | [
"",
"c#",
".net",
"wpf",
"xaml",
""
] |
I want to use the content pipeline for building objects in my level, and I tried to use the microsoft tutorial for writing a content importer and all the rest, but IIRC it didnt work. Anyone know where a decent tutorial or two is? | Here is one over at Ziggyware and another at [XNAWiki](http://www.xnawiki.com/index.php/XNA_Content_Pipeline_using_VB.NET). Have Fun. | I don't program in XNA, but would this help?
<http://blogs.msdn.com/shawnhar/archive/2008/11/24/content-pipeline-assemblies.aspx>
And a collection of links about the XNA Content Pipeline:
<http://blogs.msdn.com/etayrien/archive/2008/02/15/useful-content-pipeline-links.aspx> | XNA Content Pipeline Tutorial | [
"",
"c#",
"xna",
""
] |
Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..
I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:
```
for( int i = 0; array[i] != NULL; i++) {
........
}
```
But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array.. | The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:
```
template <typename T, int N>
void func(T (&a) [N]) {
for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
}
```
then you can do this:
```
int x[10];
func(x);
```
but note, this only works for **arrays**, not pointers.
However, as other answers have noted, using `std::vector` is a better choice. | If it's within your control, use a STL container such as a vector or deque instead of an array. | determine size of array if passed to function | [
"",
"c++",
"arrays",
"null",
"pointers",
""
] |
I'm developing a web app using Django, and I'll need to add search functionality soon. Search will be implemented for two models, one being an extension of the auth user class and another one with the fields `name`, `tags`, and `description`. So I guess nothing too scary here in context of searching text.
For development I am using [SQLite](http://en.wikipedia.org/wiki/SQLite) and as no database specific work has been done, I am at liberty to use any database in production. I'm thinking of choosing between [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL) or [MySQL](http://en.wikipedia.org/wiki/MySQL).
I have gone through several posts on Internet about search solutions, nevertheless I'd like to get opinions for my simple case. Here are my questions:
1. is full-text search an overkill in my case?
2. is it better to rely on the database's full-text search support? If so, which database should I use?
3. should I use an external search library, such as [Whoosh](http://whoosh.ca/), [Sphinx](http://en.wikipedia.org/wiki/Sphinx_%28search_engine%29), or [Xapian](http://en.wikipedia.org/wiki/Xapian)? If so, which one?
**EDIT:**
`tags` is a Tagfield (from the django-tagging app) that sits on a m2m relationship. `description` is a field that holds HTML and has a max\_length of 1024 bytes. | If that field `tags` means what I think it means, i.e. you plan to store a string which concatenates multiple tags for an item, then you might need full-text search on it... but it's a bad design; rather, you should have a many-many relationship between items and a tags table (in another table, ItemTag or something, with 2 foreign keys that are the primary keys of the items table and tags table).
I can't tell whether you need full-text search on `description` as I have no indication of what it is -- nor whether you need the reasonable but somewhat rudimentary full-text search that MySQL 5.1 and PostgreSQL 8.3 provide, or the more powerful one in e.g. sphinx... maybe talk a bit more about the context of your app and why you're considering full-text search?
Edit: so it seems the only possible need for full-text search might be on `description`, and that looks like it's probably limited enough that either MySQL 5.1 or PostgreSQL 8.3 will serve it well. Me, I have a sweet spot for PostgreSQL (even though I'm reasonably expert at MySQL too), but that's a general preference, not specifically connected to full-text search issues. [This blog](http://www.espace.com.eg/blog/2009/02/15/full-text-search-postgresql-beats-mysql/) does provide one reason to prefer PostgreSQL: you can have full-text search and still be transactional, while in MySQL full-text indexing only work on MyISAM tables, not InnoDB [[except if you add sphinx, of course]] (also see [this follow-on](http://www.espace.com.eg/blog/2009/03/15/postgresql-an-ultimate-strategy-for-full-text-search/) for a bit more on full-text search in PostgreSQL and Lucene). Still, there are of course other considerations involved in picking a DB, and I don't think you'll be doing terribly with either (unless having to add sphinx for full-text plus transaction is a big problem). | Django has [full text searching](http://docs.djangoproject.com/en/dev/ref/models/querysets/#search) support in its QuerySet filters. Right now, if you only have two models that need searching, just make a view that searches the fields on both:
```
search_string = "+Django -jazz Python"
first_models = FirstModel.objects.filter(headline__search=search_string)
second_models = SecondModel.objects.filter(headline__search=search_string)
```
You could further filter them to make sure the results are unique, if necessary.
Additionally, there is a [regex filter](http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex) that may be even better for dealing with your html fields and tags since the regex can instruct the filter on exactly how to process any delimiters or markup. | Search functionality for Django | [
"",
"python",
"database",
"django",
"search",
"full-text-search",
""
] |
I'd like to emulate violent system shutdown, i.e. to get as close as possible to power outage on an application level. We are talking about c/c++ application on Linux. **I need the application to terminate itself.**
Currently i see several options:
1. call [exit()](http://linux.die.net/man/3/exit)
2. call [\_exit()](http://linux.die.net/man/2/exit)
3. call [abort()](http://linux.die.net/man/3/abort)
4. do division by zero or dereference NULL.
5. other options?
What is the best choice?
Partly duplicate of [this question](https://stackoverflow.com/questions/397075/what-is-the-difference-between-exit-and-abort) | At the application level, the most violent you can get is `_exit()`. Division by zero, segfaults, etc are all signals, which can be trapped - if untrapped, they're basically the same as `_exit()`, but may leave a coredump depending on the signal.
If you truly want a hard shutdown, the best bet is to cut power in the most violent way possible. Invoking `/sbin/poweroff -fn` is about as close as you can get, although it may do some cleanup at the hardware level on its way out.
If you really want to stress things, though, your best bet is to really, truly cut the power - install some sort of software controlled relay on the power cord, and have the software cut that. The uncontrolled loss of power will turn up all sorts of weird stuff. For example, data on disk can be corrupted due to [RAM losing power before the DMA controller or hard disk](http://zork.net/%7Enick/mail/why-reiserfs-is-teh-sukc). This is not something you can test by anything other than actually cutting power, in your production hardware configuration, over multiple trials. | IMHO the closest to come to a power outrage is to run the application in a VM and to power of the VM without shutting down. In all other cases where the OS is still running when the application terminates the OS will do *some* cleanup that would not occur in a real power outage. | What is the most violent way that an application can terminate itself (linux) | [
"",
"c++",
"c",
"linux",
"operating-system",
""
] |
How do I detect if an arbitrary user is an administrator on a machine? I have the user's domain and username but not password. The user is NOT the currently logged in user, so I can't just use WindowsIdentity.GetCurrent. | Use LDAP. See examples [here](http://www.codeproject.com/KB/system/everythingInAD.aspx#38). | Using [UserPrincipal.GetAuthorizationGroups](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.getauthorizationgroups.aspx) to check if the user is in a group that is allowed administrative access to the machine.
First get a UserPrincipal object using FindByIdentity. Then get the authorization groups that the user is a member of. Check each group to see if matches the builtin administrators group. If the builtin administrators group is not in the user's authorization groups, then the user is not an administrator on the local machine.
```
using System.DirectoryServices.AccountManagement;
using System.Linq;
var name = Environment.UserName;
var user = UserPrincipal.FindByIdentity( new PrincipalContext( ContextType.Domain ), name );
var groups = user.GetAuthorizationGroups();
var isAdmin = groups.Any( g => g.Name == "Administrators" );
Console.WriteLine( "Admin: " + isAdmin );
``` | Detect if user is in a group | [
"",
"c#",
".net",
"vb.net",
""
] |
I have a page that has a left menu in it. This left menu is an HTML file [LeftFrame.htm] and is included in the aspx page using the following code.
```
<!-- #include file="LeftFrame.htm"-->
```
Now I need to change the file name to LeftFrameOthers.htm from C# code.
Eg:
```
if ( arg == 1 )
{
divMenu.InnerHTML = "<!-- #include file="LeftFrame.htm"-->";
}
else
{
divMenu.InnerHTML = "<!-- #include file="LeftFrameOthers.htm"-->";
}
```
But it creates an error and left menu is not loaded. Is there a way to manage this from C# code.
I don't want to use two divs for this purpose like..
```
<div id="divOwnLeftFrame" runat="server" style="DISPLAY: block">
<!-- #include file="LeftFrame.htm"--></div><div id="divOthersLeftFrame" runat="server" style="DISPLAY: block">
<!-- #include file="LeftProfileFrame.htm"-->
</div>
```
and change the display property of the divs from C# code.
**I am using VS 2003** | The use of include files in ASP.NET has generally been superseded by user controls which are much more powerful. Here's another alternative to using include files:
ASPX:
```
<asp:Literal ID="FrameLiteral" runat="server" />
```
Code behind:
```
private string GetFrameContent(int arg)
{
string filename = (arg == 1) ? "LeftFrame.htm" : "LeftFrameOthers.htm";
string path = Server.MapPath("./" + filename);
string content = System.IO.File.ReadAllText(path);
return content;
}
// Populate Literal
FrameLiteral.Text = GetFrameContent(arg);
```
Not as elegant as doing it with user controls, but it should do the job and is relatively neat and tidy. | You could create a set of LeftFrame user controls which you could replace in the codebehind. That way, you could dynamically chose which control you load at runtime.
For example . . .
```
ILeftFrame {}
LeftFrame : ILeftFrame {}
LeftFrameOthers : ILeftFrame {}
```
Then, the control itself
```
LeftFrameControl : System.Web.Ui.UserControl {}
```
Then, in your page, you have a
```
<myns:LeftFrameControl runat="Server">.
```
That control would have a property allowing you to specify which ILeftFrame you are using, would load it, would execute the appropriate behaviors, and all would be well in the world of object orientation. | Include HTML file in C# code | [
"",
"c#",
""
] |
While reading Jon Skeet's article on [fields vs properties](http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx) he mentions that changing fields to properties is a breaking change.
I would like to understand the common scenarios in which this change can cause breaks. Along with the scenario, if you can, please provide any details.
For starters, the following points have been mentioned elsewhere:
* You can't change fields to properties if you are using reflection on the class. This is obvious even though I don't have details. Serialization is one scenario where reflection is used to iterate over the object and changing fields to properties will break the serializer or change the output
* You can't easily bind against fields. (Why is this? I read it [here](https://stackoverflow.com/questions/174198/c3-0-automatic-properties-why-not-access-the-field-directly))
* ???
EDIT: Robert has a comprehensive list of reasons for choosing [properties over fields](https://stackoverflow.com/questions/205568/have-trivial-properties-ever-saved-your-bacon/207146#207146) and also explains how switching between them can cause a breaking change. | Properties can throw any arbitrary exceptions, whereas fields can't (at least when compiler knows about field assignment at compile time). | If you have a public field and another assembly has code that is using it, it will need to be recompiled.
IOW the definition of breaking includes "will need to be recompiled". | Changing fields to property is a breaking change under what scenarios? | [
"",
"c#",
".net",
"properties",
"field",
""
] |
Yeah, sorry about asking a stupid n00b question. So I have a C# program. I have a class
```
class foo
{
public int bar, wee, someotherint, someyetanotherint;
public foo()
{
this.bar = 1:
this.wee = 12;
this.someotherint = 1231;
this.someyetanotherint = 443;
}
}
```
And I want to make a class called spleen that inherits from foo
```
class spleen : foo
{
}
```
What is the quickest, easiest syntax to make the class spleen inherit the constructor from foo without having to copy/paste the entire constructor from foo? I don't want to hear that I already have too many parameters. I already know that. (edit: Actually, no. I'm an idiot) I know I should probably somehow call the parent constructor, but I don't know how. How do I do that.
Edit: I realize now that I should have taken more time to write my question. It looks like I was trying to ask two questions at the same time without realizing it (how to inherit constructors with no parameters, and how to inherit constructors with parameters) , and somehow jumbled it all up. However the answers provided were very helpful and solved my problem. Thanks, and sorry for being such an idiot! | What you're looking for is the base keyword. You can use it to call into the base constructor and provide the necessary arguments.
Try the following. I picked 0 as a default for lack of a better option
```
class spleen : foo {
public spleen() : base(0,0,0,0)
{
}
}
```
**EDIT**
Based on your new version of the code, the simplest way to call the constructor is to quite literally do nothing. The default constructor generated for spleen will automatically call the base empty constructor of foo.
```
class spleen : foo {
public spleen() {}
}
``` | You just create it, and call the base constructor:
```
public spleen(int bar, int wee, int someotherint, int someyetanotherint)
: base(bar,wee,someotherint,someyetanotherint)
{
// Do any spleen specific stuff here
}
``` | easiest way to make a class inherit constructors (C#) | [
"",
"c#",
"inheritance",
"constructor",
""
] |
I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.
Example: My config file looks like this.
```
Job {
Name = "host.domain.com-foo"
Client = host.domain.com-fd
JobDefs = "DefaultJob"
FileSet = "local"
Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr"
Pool = storage-disk1
}
```
Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? | There are numorous existing alternatives for this task, json, pickle and yaml to name 3. Unless you really want to implement this yourself, you should use one of these. Even if you do roll your own, following the format of one of the above is still a good idea.
Also, it's a much better idea to use a parser/generator or similar tool to do the parsing, regex's are going to be harder to maintain and more inefficient for this type of task. | If you can change the configuration file format, you can directly write your file as a Python file.
### config.py
```
job = {
'Name' : "host.domain.com-foo",
'Client' : "host.domain.com-fd",
'JobDefs' : "DefaultJob",
'FileSet' : "local",
'Write Bootstrap' : "/etc/foo/host.domain.com-foo.bsr",
'Pool' : 'storage-disk1'
}
```
### yourscript.py
```
from config import job
print job['Name']
``` | Python Advice for a beginner. Regex, Dictionaries etc? | [
"",
"python",
"regex",
"dictionary",
"configuration-files",
""
] |
I am having a small stupid issue and I was hoping you guys could join in with your experience.
I need a textbox with the following (dynamic) data:
```
TEXT
TEXT
TEXT
TEXT
_______________________
Name: Amount:
Blah 3
Blahblah 10
_______________________
```
But the text inside the box is the issue.
So far I am making all this text with a `StringBuilder` called `SB` and in the end I set `MyTextBox.Text` = `SB.ToString()`;
I set the header inside the box like this:
```
SB.AppendLine("Name\t\Amount:");
```
I generate the data inside a loop like this:
```
SB.AppendLine(name + "\t\t" + amount);
```
But it doesn't align neatly like my example!
If the name is longer than the previous name, the amount will be appear a whole different place on the line - compared to the previous.
Fx. like this:
```
TEXT
TEXT
TEXT
TEXT
__________________
Navn Antal:
SpecSaver 1
MadEyes 1
Gucci 1
__________________
```
**My first problem:** How can I prevent this? What do you usually do when you need a multiline textbox to contain a lot of data.
**My second problem:** When I export it to a .txt document like this:
```
using(var text = new StreamWriter("textfile.txt", false))
{
text.Write(SB);
}
```
It gives yet another version of the data, completely misaligned. It should be identical to the MyTextBox.Text. | First off you'll need to pick a [`Fixed-Width`](http://en.wikipedia.org/wiki/Monospaced_font) font for your text box.
Next, you can provide a [Padding amount](http://msdn.microsoft.com/en-us/library/txafckwd.aspx) to `string.Format()`
(or to `StringBuilder.AppendFormat`)
```
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("{0, -20}{1, -10}", "Title 1", "Title 2"));
sb.AppendLine(string.Format("{0, -20}{1, -10}", "Val Col 1 A", "Val Col 2 A"));
sb.AppendLine(string.Format("{0, -20}{1, -10}", "Val Col 1 B", "Val Col 2 B"));
Console.WriteLine(sb.ToString());
```
Results in:
```
Title 1 Title 2
Val Col 1 A Val Col 2 A
Val Col 1 B Val Col 2 B
``` | Character alignment is achieved with fixed-pitch fonts - select something like `courier-new` as the font for both textbox and printing.
See [string-padding-problem](https://stackoverflow.com/questions/763257/string-padding-problem) (Maybe your MessageBox is showing variable-pitch font?). | How to neatly align text in a textbox and keep it when exporting to .txt | [
"",
"c#",
"winforms",
"textbox",
""
] |
I have a datagridview which gets filled with data returned from a linq query.
If the query returns no results I want to display a messagebox.
Is there a way of checking to see if the datagridview is empty?
Regards | You can find out if it is empty by checking the number of rows in the DataGridView. If `myDataGridView.Rows.Count == 0` then your DataGridView is empty. | The `DGV.Rows.Count` method of checking if DGV is empty does not work if the option `AllowUserToAddRows` is set to true.
You have to disable `AllowUserToAddRows = false` then check for empty like this:
```
if (dataGridView1.Rows != null && dataGridView1.Rows.Count != 0)
``` | C# DataGridView Check if empty | [
"",
"c#",
"winforms",
"datagridview",
""
] |
I have the following (errorous) Xml:
```
<jobs>
<job>
<id>1</id>
<state><![CDATA[IL]]></state>
</job>
<job>
<id>2</id>
</job>
</jobs>
```
both the id and the state node are reqired items. I wrote an Xsd for it:
```
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="importvalidator"
elementFormDefault="qualified"
targetNamespace="http://foo.org/importvalidator.xsd"
xmlns="http://foo.org/importvalidator.xsd"
xmlns:mstns="http://foo.org/importvalidator.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="jobs">
<xs:complexType>
<xs:sequence>
<xs:element name="job" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:all>
<xs:element name="id" type="xs:string" minOccurs="1"/>
<xs:element name="state" type="xs:string" minOccurs="1"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
```
And it still validates as a structurally valid Xml. What am I missing here?
Update1: the code I'm using is in C#:
```
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("http://foo.org/importvalidator.xsd", "validator.xsd");
XDocument doc = XDocument.Load(fileName);
if (doc == null | doc.Root == null)
{
throw new ApplicationException("xml error: the referenced stream is not xml.");
}
doc.Validate(schemas, (o, e) =>
{
throw new ApplicationException("xsd validation error: xml file has structural problems");
});
``` | Please format your xml so it's easier to read - like this:
```
<jobs>
<job>
<id>1</id>
<state><![CDATA[IL]]></state>
</job>
<job>
<id>2</id>
</job>
</jobs>
```
I think you're not actually validating it - the namespaces mean that that XML does not validate, even with a "`<state>`" in the second "`<job>`". Specifically, the XSD has a target namespace of "`http://foo.org/importvalidator.xsd`", but the XML has no namespace given.
Set up a trivial test case of XSD and XML, that you definitely know will fail - use that to track down why you aren't validating.
Also, your XSD is missing the close tags for element and schema, so it should give an error - or it's just a mis-paste :-)
---
You can remove the targetNamespace from the schema:
```
<xs:schema id="importvalidator"
elementFormDefault="qualified"
targetNamespace="http://foo.org/importvalidator.xsd ← DELETE THIS"
xmlns="http://foo.org/importvalidator.xsd"
xmlns:mstns="http://foo.org/importvalidator.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
```
So it looks like this:
```
<xs:schema id="importvalidator"
elementFormDefault="qualified"
xmlns="http://foo.org/importvalidator.xsd"
xmlns:mstns="http://foo.org/importvalidator.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
```
PS: anyone know if/how you can highlight parts of source code with SO's markdown? | @13ren has the correct answer. It is not an error if a node does not match any schema. It's only a warning. I can see the warnings in the code below:
```
private static void ValidateDocument(XmlSchemaSet schemas, string uri)
{
var settings = new XmlReaderSettings
{
Schemas = schemas,
ValidationFlags =
XmlSchemaValidationFlags.
ProcessIdentityConstraints |
XmlSchemaValidationFlags.
ReportValidationWarnings,
ValidationType = ValidationType.Schema
};
settings.ValidationEventHandler += OnValidationEventHandler;
using (var validatingReader = XmlReader.Create(uri, settings))
{
XDocument.Load(
validatingReader,
LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
}
return;
}
```
This produces the following:
Warning: Could not find schema information for the element 'jobs'.
Warning: Could not find schema information for the element 'job'.
Warning: Could not find schema information for the element 'id'.
Warning: Could not find schema information for the element 'state'.
Warning: Could not find schema information for the element 'job'.
Warning: Could not find schema information for the element 'id'.
Changing your XML and running again:
```
<?xml version="1.0" encoding="utf-8" ?>
<jobs xmlns="http://foo.org/importvalidator.xsd">
<job>
<id>1</id>
<state><![CDATA[IL]]></state>
</job>
<job>
<id>2</id>
</job>
</jobs>
```
produces the error you expected:
Error: The element 'job' in namespace '<http://foo.org/importvalidator.xsd>' has incomplete content. List of possible elements expected: 'state' in namespace '<http://foo.org/importvalidator.xsd>'. | Xsd validation problem | [
"",
"c#",
"xsd",
""
] |
Something strange happened -at least for me - , as I know in a 3 tier model you make DLLs and let your UI make a reference to them , right now I'm working like this: ClassLibrary project for the DAL, another one for the BLL with reference to the DAL DLL located on the DAL bin/debug directory so that the BLL ClassLibrary project implements the DAL changes immediately , then a Windows Application project with references to both BLL and DAL DLLs located on their respective bin/debug directories .
Then I wanted to test and to examine the exceptions generated when the aplication can't find the DLLs it's referencing , I cutted the DLLs and putted them in another location , the Application is still working fine !!? , thats was strange enough but I guessed maybe when running the Windows application it recreates those DLLs again so I put those DLLs on another folder in the Desktop and I delete the old references from the Windows application and recreated them pointing this time to the ones on the Desktop folder and tested it , after that I delete the Desktop folder and the application still working fine and connecting to the database and every thing ???
Environment:
XP SP2 VisualStudio 2008 C# | You can't test this within Visual Studio as the build / debug / run will rebuild the references.
Removing the references will break your code as the compiler will balk and refuse to compile the app as you have noted.
You will need to compile the app, then remove the DLLs from the bin folder using windows explorer and then run the application by double clicking the app. not using Visual Studio.
This will throw an exception of some descrioption which will pop up in a little box. The JIT Debugger might also catch it (maybe??) and let you attach to the process using VS but I'm not sure. | The compiler copies the dll's in it's own bin folder and uses those. So you have to clean your project to see a difference. | DLLs locations issue | [
"",
"c#",
"dll",
""
] |
I am building a plugin for a LAN party website that I wrote that would allow the use of a Round Robin tournament.
All is going well, but I have some questions about the most efficient way to rank over two criteria.
Basically, I would like the following ranking layout:
```
Rank Wins TotalScore
PersonE 1 5 50
PersonD 2 3.5 37
PersonA 2 3.5 37
PersonC 4 2.5 26
PersonB 5 2.5 24
PersonF 6 0 12
```
In SQL server, I would use:
```
SELECT
[Person],
RANK() OVER (ORDER BY Wins DESC, TotalScore DESC) [Rank],
[Wins],
[TotalScore]
```
Now, I only have List, Dictionary, and etc. to work with
Specifically:
```
Dictionary<TournamentTeam, double> wins = new Dictionary<TournamentTeam, double>();
Dictionary<TournamentTeam, double> score = new Dictionary<TournamentTeam, double>();
```
**Is there a way to do this style of ranking with LINQ?**
If not, is there an *extensible* way that would allow me later to take in to account Win-Loss-Draw instead of just wins if I choose to?
**Edit:**
My adaptation of TheSoftwareJedi's answer:
```
private class RRWinRecord : IComparable
{
public int Wins { get; set; }
public int Losses { get; set; }
public int Draws { get; set; }
public double OverallScore { get; set; }
public double WinRecord
{
get
{
return this.Wins * 1.0 + this.Draws * 0.5 + this.Losses * 0.0;
}
}
public int CompareTo(object obj) { ... }
public override bool Equals(object obj) { ... }
public override int GetHashCode() { ... }
public static bool operator ==(RRWinRecord lhs, RRWinRecord rhs) { ... }
public static bool operator !=(RRWinRecord lhs, RRWinRecord rhs) { ... }
public static bool operator >(RRWinRecord lhs, RRWinRecord rhs) { ... }
public static bool operator <(RRWinRecord lhs, RRWinRecord rhs) { ... }
public static bool operator >=(RRWinRecord lhs, RRWinRecord rhs) { ... }
public static bool operator <=(RRWinRecord lhs, RRWinRecord rhs) { ... }
}
...
int r = 1, lastRank = 1;
RRWinRecord lastRecord = null;
var ranks = from team in records.Keys
let teamRecord = records[team]
orderby teamRecord descending
select new RRRank() { Team = team, Rank = r++, Record = teamRecord };
foreach (var rank in ranks)
{
if (rank.Record != null && lastRecord == rank.Record)
{
rank.Rank = lastRank;
}
lastRecord = rank.Record;
lastRank = rank.Rank;
string scoreDescription = String.Format("{0}-{1}-{2}", rank.Record.Wins, rank.Record.Losses, rank.Record.Draws);
yield return new TournamentRanking(rank.Team, rank.Rank, scoreDescription);
}
yield break;
``` | This should work for a non-dense rank:
```
static class Program
{
static IEnumerable<Result> GetResults(Dictionary<TournamentTeam, double> wins, Dictionary<TournamentTeam, double> scores)
{
int r = 1;
double lastWin = -1;
double lastScore = -1;
int lastRank = 1;
foreach (var rank in from name in wins.Keys
let score = scores[name]
let win = wins[name]
orderby win descending, score descending
select new Result { Name = name, Rank = r++, Score = score, Win = win })
{
if (lastWin == rank.Win && lastScore == rank.Score)
{
rank.Rank = lastRank;
}
lastWin = rank.Win;
lastScore = rank.Score;
lastRank = rank.Rank;
yield return rank;
}
}
}
class Result
{
public TournamentTeam Name;
public int Rank;
public double Score;
public double Win;
}
``` | Ranking isn't too hard. Just mishmash OrderBy and Select implementation patterns together and you can have an easy to use Ranking extension method. Like this:
```
public static IEnumerable<U> Rank<T, TKey, U>
(
this IEnumerable<T> source,
Func<T, TKey> keySelector,
Func<T, int, U> selector
)
{
if (!source.Any())
{
yield break;
}
int itemCount = 0;
T[] ordered = source.OrderBy(keySelector).ToArray();
TKey previous = keySelector(ordered[0]);
int rank = 1;
foreach (T t in ordered)
{
itemCount += 1;
TKey current = keySelector(t);
if (!current.Equals(previous))
{
rank = itemCount;
}
yield return selector(t, rank);
previous = current;
}
}
```
Here's some test code
```
string[] myNames = new string[]
{ "Bob", "Mark", "John", "Jim", "Lisa", "Dave" };
//
var query = myNames.Rank(s => s.Length, (s, r) => new { s, r });
//
foreach (var x in query)
{
Console.WriteLine("{0} {1}", x.r, x.s);
}
```
Which yields these results:
```
1 Bob
1 Jim
3 Mark
3 John
3 Lisa
3 Dave
``` | C# Ranking of objects, multiple criteria | [
"",
"c#",
"linq",
"linq-to-objects",
"ranking",
""
] |
This is part of an events page that can be filtered by date (using pre-defined date ranges or a date picker).
I want to avoid repeating the whole `foreach ($days as $day_number)...` etc. loop for every condition.
I guess that whole loop could be moved to a function, but I'm not sure how to implement it.
```
<?php
// open the db connection
$db = new wpdb('user', 'pass', 'db', 'server');
// $today = date('Y-m-d');
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+1, date('Y')) );
$seven_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+6, date('Y')) );
$thirty_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+29, date('Y')) );
echo '<div class="column first">';
if ( ! empty($_REQUEST['date_range']) )
{
// user has chosen a date/range, show matching events
$date_range = mysql_real_escape_string($_REQUEST['date_range']);
switch( $date_range )
{
case 'all':
// code here
break;
case 'next_7_days':
// code here
break;
case 'next_30_days':
// code here
break;
default:
// code here
}
}
else
{
// no date selected, show todays events
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
echo '</div> <!--/column-->';
function convert_date_to_day_number($date)
{
global $db;
$sql = "SELECT day_number FROM days WHERE day_date = '$date'";
$day_numbers = $db->get_results($sql);
foreach ($day_numbers as $key => $value)
{
$day_number[] = $value->day_number;
}
return $day_number;
}
function get_events($where)
{
global $db;
$sql = "SELECT
e.id,
TIME_FORMAT(e.start_time, '%H:%i' ) AS start_time,
e.x_prod_desc AS title,
-- e.title_en AS title,
p.name_en AS place,
et.name_en AS type,
w.week_number,
d.day_date AS start_date
FROM event AS e
LEFT JOIN place AS p ON p.id = e.place_id
LEFT JOIN event_type AS et ON et.id = e.event_type_id
LEFT JOIN days AS d ON d.id = e.day_id
LEFT JOIN week AS w ON w.id = d.week_id ";
$sql .= $where;
$events = $db->get_results($sql);
return $events;
}
function render_event($event)
{
$request_uri = $_SERVER['REQUEST_URI'];
$output = <<<EOD
<tr class="week-$event->week_number">
<td class="topic"></td>
<td class="time">$event->start_time</td>
<td class="summary">
<a href="$request_uri&event_id=$event->id">$event->title</a>
</td>
<td class="type">$event->type</td>
<td class="location">
<span class="addr">$event->place</span>
</td>
</tr>
EOD;
echo $output;
}
function render_day( $day_number )
{
global $db;
$sql = "SELECT
d.day_number,
DATE_FORMAT( d.day_date, '%W %e %M %Y' ) AS date,
DATE_FORMAT( d.day_date, '%b' ) AS month,
DATE_FORMAT( d.day_date, '%e' ) AS day
FROM days AS d
WHERE day_number = " . $day_number;
$day = $db->get_results($sql);
$day = $day[0];
$output = <<<EOD
<tr class="day">
<th colspan="5">
<em class="date">
<abbr class="dtstart" title="20090605T1806Z">
<span title="$day->date">
<span class="month">$day->month</span>
<span class="day">$day->day</span>
</span>
</abbr>
</em>
$day->date
<span class="event-day">Day $day->day_number</span>
</th>
</tr>
EOD;
echo $output;
}
?>
``` | ```
function generateEventsTable($dateStr)
{
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
```
Call it like this:
```
generateEventsTable($today);
``` | First, you may want to use `strtotime` for relative dates :
```
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', strtotime('+1 day') );
$seven_days_ahead = date( 'Y-m-d', strtotime('+7 days') );
$thirty_days_ahead = date( 'Y-m-d', strtotime('+30 day') );
// or +1 month (=> calendar month)
```
Second, you can set two variables with begin & end dates, then:
```
$date = $start_date; // 'Y-m-d' format
while( $date <= $end_date ) {
//code here or fill up a table with your days
// using $date
$date = date( 'Y-m-d', strtotime( '+1day', strtotime($date) ) );
}
```
Whenever working with dates in PHP, you should check [`strtotime`](http://www.php.net/manual/en/function.strtotime.php). | How to refactor this conditional to avoid repetition? | [
"",
"php",
"dry",
""
] |
I have three tables:
Table User( userid username)
Table Key( userid keyid)
Table Laptop( userid laptopid)
i want all users who have either a key or a laptop, or both. How do i write the query so that it uses a join between table User and table Key, as well as a join between table User and table Laptop?
The main problem is that in the actual scenario, there are twelve or so table joins, sth like:
" select .. From a left join b on (...), c join d on (..),e,f,g where ...",
and i see that a could be joined to b, and a could also be joined to f. So assuming i can't make the tables a,b, and f appear side-by-side, how do i write the sql query? | You can use multiple joins to combine multiple tables:
```
select *
from user u
left join key k on u.userid = k.userid
left join laptop l on l.userid = u.userid
```
A "left join" also finds users which do not have a key or a laptop. If you replace both with "inner join", it would find only users with a laptop and a key.
When a "left join" does not find a row, it will return NULL in its fields. So you can select all users that have either a laptop or a key like this:
```
select *
from user u
left join key k on u.userid = k.userid
left join laptop l on l.userid = u.userid
where k.userid is not null or l.userid is not null
```
NULL is special, in that you compare it like "field is not null" instead of "field <> null".
Added after your comment: say you have a table Mouse, that is related to Laptop, but not to User. You can join that like:
```
select *
from user u
left join laptop l on l.userid = u.userid
left join mouse m on m.laptopid = l.laptopid
```
If this does not answer your question, you gotta clarify it some more. | ```
select distinct u.userid, u.username
from User u
left outer join Key /* k on u.userid = k.userid */
left outer join Laptop /* l on u.userid = l.userid */
where k.userid is not null or l.userid is not null
```
**EDIT**
*"The main problem is that in the actual scenario, there are twelve or so table joins, sth like:
" select .. From a left join b on (...), c join d on (..),e,f,g where ...",
and i see that a could be joined to b, and a could also be joined to f. So assuming i can't make the tables a,b, and f appear side-by-side, how do i write the sql query?"*
You can have as many left outer joins as required. Join the table with the primary key to the rest of the tables or on any other field where field values of one table should match field values of other table.
eg will explain better than words
```
select *
from a
left outer join b on a.pk = b.fk -- a pk should match b fk
left outer join c on a.pk = c.fk -- a pk should match c fk
left outer join d on c.pk = d.fk -- c pk should match d fk
```
and so on | joining one table multiple times to other tables | [
"",
"sql",
""
] |
I would like to define my own operator. Does python support such a thing? | No, you can't create new operators. However, if you are just evaluating expressions, you could process the string yourself and calculate the results of the new operators. | While technically you cannot define new operators in Python, this [clever hack](http://code.activestate.com/recipes/384122/) works around this limitation. It allows you to define infix operators like this:
```
# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8
# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
print [1,2,3] <<isa>> []
# => True
``` | Python: defining my own operators? | [
"",
"python",
"operators",
""
] |
I have used the following code in a number of applications to load .DLL assemblies that expose plugins.
However, I previously was always concerned with functionality, rather than security.
I am now planning to use this method on a web application that could be used by groups other than me, and I would like to make sure that the security of the function is up-to-snuff.
```
private void LoadPlugins(string pluginsDirectory)
{
List<IPluginFactory> factories = new List<IPluginFactory>();
foreach (string path in Directory.GetFiles(pluginsDirectory, "*.dll"))
{
Assembly assembly = Assembly.LoadFile(path);
foreach (Type type in assembly.GetTypes())
{
IPluginEnumerator instance = null;
if (type.GetInterface("IPluginEnumerator") != null)
instance = (IPluginEnumerator)Activator.CreateInstance(type);
if (instance != null)
{
factories.AddRange(instance.EnumerateFactories());
}
}
}
// Here, I would usually collate the plugins into List<ISpecificPlugin>, etc.
}
```
The first few concerns I have:
1. This function reads the entire directory and doesn't care about what assemblies it loads, and instead just loads all of them. Is there a way to detect whether an assembly is a valid, functional .NET assembly before loading it with Assembly.LoadFile()?
2. What kind of exception handling should be added to the function to prevent initialization of the assembly from halting my code?
3. If I want to deny the assembly the right to do the following: Read/Write files, Read/Wite the registry, etc, how would I do that?
Are there any other security concerns I should be worried about?
**EDIT: Keep in mind that I want anybody to be able to write a plug-in, but I still want to be secure.** | 1) strong name the assembly with a certain key.
* you do **not** have to put it in the GAC
* you can re-use a key to sign more than one assembly
* when you re-use the key, you get the same "public key" on each signed assembly
2) on load, check that the assembly has been strong named with the key you're expecting
* You can store the public key as a binary file, an embedded resource,
or use the existing public key of the executing assembly
* this last way may not be the best way as you may want to differentiate assemblies
signed with the "plugin" key from those signed with a regular key)
Example:
```
public static StrongName GetStrongName(Assembly assembly)
{
if(assembly == null)
throw new ArgumentNullException("assembly");
AssemblyName assemblyName = assembly.GetName();
// get the public key blob
byte[] publicKey = assemblyName.GetPublicKey();
if(publicKey == null || publicKey.Length == 0)
throw new InvalidOperationException( String.Format("{0} is not strongly named", assembly));
StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
// create the StrongName
return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
}
// load the assembly:
Assembly asm = Assembly.LoadFile(path);
StrongName sn = GetStrongName(asm);
// at this point
// A: assembly is loaded
// B: assembly is signed
// C: we're reasonably certain the assembly has not been tampered with
// (the mechanism for this check, and it's weaknesses, are documented elsewhere)
// all that remains is to compare the assembly's public key with
// a copy you've stored for this purpose, let's use the executing assembly's strong name
StrongName mySn = GetStrongName(Assembly.GetExecutingAssembly());
// if the sn does not match, put this loaded assembly in jail
if (mySn.PublicKey!=sn.PublicKey)
return false;
```
note: code has not been tested or compiled, may contain syntax errors. | I don't know if this is the best way but when you call LoadFile on an invalid assembly you will get a BadImageFOrmatException because the assembly does not have a manifest.
The way your code is written currently you are pretty wide open to a [Process Control Attack](http://cwe.mitre.org/data/definitions/114.html). Anyone who can get access to the directory and drop down an assembly that implements your interface can execute this attack. They do not even have to implement the interface very well, they can just provide a default constructor and do all the damage in that. This allows an attacker to execute code under the privilege of your application which is always bad.
So your only current protection is to protect access to the directory on an OS level. This may work for you but it is only one level of defense and you are reliant on security state you cannot control.
Here are two things you could look at:
1. Strong naming the assembly and requiring the assembly be registered in the GAC is most likely the safest way to do this. If you can do this you need to find a way to provide the Assembly's full name to your application and load it with Assembly.Load().
However I doubt you want to install these plugins into the GAC so you could do it this way:
2. Within your application provide a way for users to register a plugin, essentially a mini-GAC. When they do you store the location and name of the Assembly as well as the public key. This requires that the Assembly is strong named.
This way you will only load Assemblies that someone with privilege to your application has provided, most likely someone who has rights to add a plugin. Before you load the Assembly you can check that the Public Key matches what was provided when the Assembly was registered to prevent an attacker from just replacing the Assembly. This code is fairly simple:
```
private bool DoPublicKeysCompare(Assembly assembly, byte[] expectedPublicKey)
{
byte[] assemblyKey = assembly.GetName().GetPublicKey();
return expectedPublicKey.SequenceEqual(assemblyKey);
}
```
So now to execute an attack on you I must somehow get privileged to change the PublicToken value and get access to the directory and change out the file. | .NET Assembly Plugin Security | [
"",
"c#",
"security",
"reflection",
"plugins",
""
] |
I have a function which extracts a file into a byte array (data).
```
int contentLength = postedFile.ContentLength;
byte[] data = new byte[contentLength];
postedFile.InputStream.Read(data, 0, contentLength);
```
Later I use this byte array to construct an System.Drawing.Image object
(where data is the byte array)
```
MemoryStream ms = new MemoryStream(data);
Image bitmap = Image.FromStream(ms);
```
I get the following exception "ArgumentException: Parameter is not valid."
The original posted file contained a 500k jpeg image...
Any ideas why this isnt working?
Note: I assure you I have a valid reason for converting to a byte array and then to a memorystream!! | That's most likely because you didn't get all the file data into the byte array. The Read method doesn't have to return as many bytes as you request, and it returns the number of bytes actually put in the array. You have to loop until you have gotten all the data:
```
int contentLength = postedFile.ContentLength;
byte[] data = new byte[contentLength];
for (int pos = 0; pos < contentLength; ) {
pos += postedFile.InputStream.Read(data, pos, contentLength - pos);
}
```
This is a common mistake when reading from a stream. I have seen this problem a lot of times.
Edit:
With the check for an early end of stream, as Matthew suggested, the code would be:
```
int contentLength = postedFile.ContentLength;
byte[] data = new byte[contentLength];
for (int pos = 0; pos < contentLength; ) {
int len = postedFile.InputStream.Read(data, pos, contentLength - pos);
if (len == 0) {
throw new ApplicationException("Upload aborted.");
}
pos += len;
}
``` | You're not checking the return value of postedFile.InputStream.[Read](http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx). It is *not* at all guaranteed to fill the array on the first call. That will leave a corrupt JPEG in data (0's instead of file content). | C# bitmap images, byte arrays and streams! | [
"",
"c#",
"arrays",
"image",
"stream",
"byte",
""
] |
I am trying to wrap my head around the idea of classes, data visibility and closures (specifically in Javascript) and I am On the jQuery docs page for types, it mentions that closures are used to hide data:
> The pattern allows you to create objects with methods that operate on data that isn't visible to the outside—the very basis of object-oriented programming.
The example:
```
function create() {
var counter = 0;
return {
increment: function() {
counter++;
},
print: function() {
console.log(counter);
}
}
}
var c = create();
c.increment();
c.print(); // 1
```
By declaring the variable counter with the keyword var, it is already locally scoped inside the function/class definition. As far as I know and can tell, it isn't accessible from the outside to begin with. Am I missing something from a data visibility perspective.
Second, is there an advantage to writing the class like above versus like below:
```
function create() {
var counter = 0;
this.increment = function() {
counter++;
}
this.print = function() {
console.log(counter);
}
return this;
}
var c = create();
c.increment();
c.print(); // 1
```
As I understand it, these are more or less semantically the same thing - the first is just more "jQuery style". I am just wondering if there is an advantage or other nuance I don't fully appreciate from the first example. If I am correct, both examples create closures in that they are accessing data declared outside their own scope.
[<http://docs.jquery.com/Types#Closures>](http://docs.jquery.com/Types#Closures) | First of all, you are correct that both versions use closures.
The first version is cleaner (in my opinion) and more popular in modern javascript. The major potential drawback of the first style is that you cannot effectively assign objects to the constructor's prototype, which is useful (and more efficient) if you are creating a lot of the same objects.
The second style, I've actually never seen in production Javascript. Normally, you would instantiate `create` with `new`, instead of returning `this` in the `create()` function, like so:
```
function create() {
var counter = 0;
this.increment = function() {
counter++;
}
this.print = function() {
console.log(counter);
}
}
var c = new create();
c.increment();
c.print(); // 1
``` | > By declaring the variable counter with
> the keyword var, it is already locally
> scoped inside the function/class
> definition. As far as I know and can
> tell, it isn't accessible from the
> outside to begin with. Am I missing
> something from a data visibility
> perspective.
It's not that the `counter` variable isn't accessible from outside the function to begin with, it's that it is accessible to the `increment` and `print` functions after `create` function has exited that makes [closures](http://www.jibbering.com/faq/faq_notes/closures.html) so useful. | Javascript Closure and Data Visibility | [
"",
"javascript",
"closures",
""
] |
How to save c++ object into a xml file and restore back? | [Boost.Serialization](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/index.html) and [libs11n](http://s11n.net/s11n/) can both do this. The libs11n manual (available [here](http://s11n.net/download/)) has an extensive comparison of the two.
As Tobias said, the [C++ FAQ](http://www.parashift.com/c%2B%2B-faq-lite/serialization.html) has good background information. | Boost's [serialization library](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/index.html) might be implementing a lot of the functionality you are looking for. | How to save c++ object into a xml file and restore back? | [
"",
"c++",
"xml",
"serialization",
""
] |
I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly? | Either use the system control panel to set the `PATH` environment variable that applies permanently or
Reinstall Python as a system administrator so that the installer can set the registry and environment variables for you.
If you install the "just for me" option, then you have to set the `PATH` variable in the control panel. | You probably need to add Python to you dos path. Here's a video that may help you out:
<http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96> | python not starting properly | [
"",
"python",
"windows",
"django-admin",
""
] |
I have a project that imports a DLL (written by me). Sometimes when an exception is raised within a method in the DLL, the host project opens a tab and let me see the code within the DLL. I can also put breakpoints within it.
But this behavior seems quite random, I cannot have it on purpose and not always works. Plus, I can't see the file name in the project explorer window.
Any help on debugging DLLs? Thanks | The enhanced debugging (for a dll not in the current solution) depends largely on whether you have the debugging symbols file (.pdb) in an obvious location - in particular, next to the dll itself. You can also load symbols manually from the modules window (when debugging, Debug -> Windows -> Module, right-click, Load Symbols From...) | What may be getting in your way here is a feature known as Just My Code (JMC). This is a debugger / CLR feature designed at limiting a users view of the world to just the code that they've written. The various ways in how a piece of code or DLL is determined to be yours or not can be confusing at times.
Next time you hit this problem, try disabling JMC and see if it fixes your problem
* Navigate: Tools -> Options
* Navigate: Debugger -> General
* Uncheck the Just My Code option | VisualStudio / C#: Debugging imported DLL | [
"",
"c#",
"visual-studio",
"dll",
""
] |
I have a stored procedure in SQL Server 2000 that performs a search based on parameter values. For one of the parameters passed in, I need a different `WHERE` clause depending on its value - the problem is that the 3 values would be where `MyColumn`
1. `IS NULL`
2. `IS NOT NULL`
3. `ANY VALUE (NULL AND NOT NULL)` (essentially no `WHERE` clause)
I'm having some mental block in coming up with the correct syntax. Is this possible to do in one select statement without performing some `IF @parameter BEGIN ... END` branching? | Here is how you can solve this using a single `WHERE` clause:
```
WHERE (@myParm = value1 AND MyColumn IS NULL)
OR (@myParm = value2 AND MyColumn IS NOT NULL)
OR (@myParm = value3)
```
A naïve usage of the CASE statement **does not work**, by this I mean the following:
```
SELECT Field1, Field2 FROM MyTable
WHERE CASE @myParam
WHEN value1 THEN MyColumn IS NULL
WHEN value2 THEN MyColumn IS NOT NULL
WHEN value3 THEN TRUE
END
```
It is possible to solve this using a case statement, see onedaywhen's [answer](https://stackoverflow.com/a/811579/61989) | You could just do something like this:
```
SELECT *
FROM foo
WHERE (@param = 0 AND MyColumn IS NULL)
OR (@param = 1 AND MyColumn IS NOT NULL)
OR (@param = 2)
```
Something like that. | WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I have a project that uses generics and a few Java 1.5/6 bits and pieces.
Is it possible to compile this code to work on a system running a 1.4 JRE?
I use an ANT build script and javac task to compile the library. This builds fine while the target attribute is 1.5.
If I change the target to be 1.4 I get the following error:
```
generics are not supported in -source 1.4
(use -source 5 or higher to enable generics)
```
So I add a source attribute and try a value of 5 and 1.5. New error:
```
javac: source release 5 requires target release 1.5
```
Am I going to have to go through all my code and change the 1.5 stuff to make this work? | I've not used either of these solutions, but there is
1. [Retroweaver](http://retroweaver.sourceforge.net/)
2. specifying the unsupported `-target jsr14` *may* work
3. [Retrotranslator](http://retrotranslator.sourceforge.net/)
4. [Declawer](http://sites.google.com/site/glazedlists/Home/declawer)
5. [JBossRetro](http://www.jboss.org/community/wiki/JBossRetro)
You might also find `javac -XD-printflat` useful (though take care not to overwrite your original source). | > I have a project that uses generics
> and a few Java 1.5/6 bits and pieces.
> Is it possible to compile this code to
> work on a system running a 1.4 JRE?
No.
> Am I going to have to go through all
> my code and change the 1.5 stuff to
> make this work?
Yes. But there's a way to automate that, using a tool called [Retroweaver](http://retroweaver.sourceforge.net/). There's no guarantee that it will catch everything though. | Compiling Java code written for 1.5 to work with 1.4 JRE? | [
"",
"java",
"ant",
"compilation",
"backwards-compatibility",
""
] |
I have one binary and one shared library.
The shared library is compiled with:
```
all:
g++ -g -shared -fpic $(SOURCES) -o libmisc.so
```
the binary is compiled with:
```
LIBS=-L../../misc/src
LDFLAGS=-lmisc
all:
g++ -g -o mainx $(INCLUDE) $(SOURCE) $(LIBS) $(LDFLAGS)
```
I set in `~/.bashrc`
```
export LD_LIBRARY_PATH=/mnt/sda5/Programming/misc/src/
```
to the `libmisc.so` output path.
Debugging from console works fine:
```
gdb mainx
```
However from Emacs22, launching gdb fails with the following message:
> Starting program: /mnt/sda5/Programming/main/src/mainx
> /mnt/sda5/Programming/main/src/mainx: error while loading shared libraries: libmisc.so: cannot open shared object file: No such file or directory
This looks very tricky for the moment, and I couldn't solve it. I am not sure if this a emacs's problem, or I should pass a parameter in gdb's command line. | Emacs probably does not read your .bashrc before it invokes gdb. Try to put 'set solib-search-path' and 'set solib-absolute-path in your .gdbinit file instead | Emacs doesn't invoke gdb via bash, but rather invokes it directly, and so .bashrc changes do not take effect and `LD_LIBRARY_PATH` is not set.
If you quit emacs, open a new shell (so `LD_LIBRARY_PATH` is set), start emacs in it, and then do `M-X gdb`, then it would work.
Setting `solib-search-path` in GDB is a hack.
A much better fix is to build the executable in such a way that it doesn't need `LD_LIBRARY_PATH` to begin with:
```
LDFLAGS=-lmisc -Wl,-rpath=/mnt/sda5/Programming/misc/src
``` | gdb says "cannot open shared object file" | [
"",
"c++",
"linux",
"emacs",
"gdb",
""
] |
I am currently designing a website in C#, which uses some very complex code to generate a search list, which I am currently designing as a *tree*-like structure.
The main reason I am using a tree is the fact that this website is high-traffic and has a very complex search filter, which means scalability is very important. However, I am worried that the memory requirements of the tree may outweigh the effective processing requirements of simply recalculating values every time.
Is there a reliable way to measure the size of a dictionary in C#? The Marshal.SizeOf() method will not allow this as the code is not unmanaged. | The best bet is to run the load on the site under different models and check [the relevant performance counters](http://msdn.microsoft.com/en-us/library/x2tyfybc.aspx).
As a simplification, you could extract just the code that creates and stores data structures, and embed that into a console application. Run a simulated load and check the performance counters there. You can vary things and measure the impact on memory consumption and garbage collection. Doing this would isolate the effects you want to measure.
If you're thinking, "gee, that sounds like a lot of work," then you are better off just buying more memory. | One way to do it ... initialize your tree with an arbitrary number of elements, measure the memory size consumed by the process, add 1000 new elements, measure the memory size again, subtract and divide. | Size of a dictionary | [
"",
"c#",
"memory-management",
"tree",
""
] |
```
class Test1<T> {
Test1(Class<T> type) {}
}
class Test2 extends Test1<Class> {
Test2() {
super(Class.class);
}
}
```
This works, but, I am warned about use of a raw generic type in "`Test1<Class>`". I understand that, but, changing it to "`Class<?>`" (which should be equivalent?) gives a compiler error in the call to super() -- Class.class is apparently of type "`Class<Class>`" instead of "`Class<Class<?>>`".
Variants on these all seem to result in a compile error.
Can anyone see how to resolve this, such that I am always using a type param with Class, and hence don't get an IDE warning? It seems better that way, even if it works as-is.
I am open to changes in the structure of these two classes two as long as it preserves the basic intent: Test2 is a special type of Test1, specialized for "Class" objects. | Your warnings stem from the fact that `Class` is itself a paramterized class: `public final class Class<T>`. The simplest way to remove the warnings is to make the `T` the type parameter instead of `Class<T>`:
```
class Test1<T> {
Test1(T type) { Class<?> classType = type.getClass();}
}
class Test2 extends Test1<String> {
Test2() {
super("");
}
}
``` | `Class` and `Class<?>` aren't *exactly* equivalent. They're *semantically* equivalent, but the latter is effectively telling the compiler, "Yes, I know this is a generic type, but I don't know anything about the type parameter." The former is just the raw type, which can often be a sign that it's old code which hasn't been migrated to use generics.
This is covered in the [Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) - see the question "What is the difference between the unbounded wildcard parameterized type and the raw type?" in the [parameterized types section](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html). | Resolve IDE warning with generics, Class<?> type | [
"",
"java",
"generics",
"class",
""
] |
I'm making a custom message box that lets you copy text, but I wanted it to look exactly like a standard message box, so I would like to set the buttons text to whatever the system language is, as the MessageBox class does.
Does anyone knows how to get that text ("Yes", "No", "Cancel", etc)?. | Thanks for your answers with Snarfblam link I could figure out the rest.
```
class Program {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
[DllImport("kernel32")]
static extern IntPtr LoadLibrary(string lpFileName);
private const uint OK_CAPTION = 800;
private const uint CANCEL_CAPTION = 801;
private const uint ABORT_CAPTION = 802;
private const uint RETRY_CAPTION = 803;
private const uint IGNORE_CAPTION = 804;
private const uint YES_CAPTION = 805;
private const uint NO_CAPTION = 806;
private const uint CLOSE_CAPTION = 807;
private const uint HELP_CAPTION = 808;
private const uint TRYAGAIN_CAPTION = 809;
private const uint CONTINUE_CAPTION = 810;
static void Main(string[] args) {
StringBuilder sb = new StringBuilder(256);
IntPtr user32 = LoadLibrary(Environment.SystemDirectory + "\\User32.dll");
LoadString(user32, OK_CAPTION, sb, sb.Capacity);
string ok = sb.ToString();
LoadString(user32, CANCEL_CAPTION, sb, sb.Capacity);
string cancel = sb.ToString();
LoadString(user32, ABORT_CAPTION, sb, sb.Capacity);
string abort = sb.ToString();
LoadString(user32, RETRY_CAPTION, sb, sb.Capacity);
string retry = sb.ToString();
LoadString(user32, IGNORE_CAPTION, sb, sb.Capacity);
string ignore = sb.ToString();
LoadString(user32, YES_CAPTION, sb, sb.Capacity);
string yes = sb.ToString();
LoadString(user32, NO_CAPTION, sb, sb.Capacity);
string no = sb.ToString();
LoadString(user32, CLOSE_CAPTION, sb, sb.Capacity);
string close = sb.ToString();
LoadString(user32, HELP_CAPTION, sb, sb.Capacity);
string help = sb.ToString();
LoadString(user32, TRYAGAIN_CAPTION, sb, sb.Capacity);
string tryAgain = sb.ToString();
LoadString(user32, CONTINUE_CAPTION, sb, sb.Capacity);
string cont = sb.ToString();
}
``` | These strings appear to be stored in the User32.dll library. There are details in [this discussion](http://www.purebasic.fr/english/viewtopic.php?t=24134&sid=cf59f7045f38869cb347d09ad9e73f6e) on the Pure BASIC forum, towards the bottom. | How do I get MessageBox button caption? | [
"",
"c#",
".net",
"winforms",
"messagebox",
""
] |
Given the following code in Eclipse:
```
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class Question {
public static void main(String[] args) {
String source = "class Bob {}";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(source.toCharArray());
CompilationUnit result = (CompilationUnit) parser.createAST(null);
String source2 = "class Bob {public void MyMethod(){}}";
ASTParser parser2 = ASTParser.newParser(AST.JLS3);
parser2.setSource(source2.toCharArray());
CompilationUnit result2 = (CompilationUnit) parser2.createAST(null);
}
}
```
How do you use the Eclipse Compare API (org.eclipse.compare) to find the AST difference? (And can this be done outside of a plugin?)
I'm looking at the following APIs
<http://kickjava.com/src/org/eclipse/compare/structuremergeviewer/Differencer.java.htm>
<http://kickjava.com/src/org/eclipse/jdt/internal/ui/compare/JavaStructureCreator.java.htm>
<http://kickjava.com/src/org/eclipse/compare/CompareUI.java.htm>
Can anyone point to example code (or an API - but the code is preferred). | Given that Eclipse doesn't do AST differencing, perhaps what the OP wanted to find differences between two files in terms of the language constructs ignoring white spaces and comments. Our [Smart Differencer tool](http://www.semanticdesigns.com/Products/SmartDifferencer) compares two source files in terms of the langauge constructs (variables, expressions, statements, blocks, methods, ...) and describes the differences in terms of abstract editing operations over these elements (delete, copy, move, rename identifier in region, ...) | [GumTree](https://github.com/GumTreeDiff/gumtree) does the job, for free :)
It also supports other languages such as javascript. | Eclipse Abstract Syntax Tree Diff | [
"",
"java",
"eclipse",
"diff",
"abstract-syntax-tree",
"compilationunit",
""
] |
Given a list of mailing addresses, I need to open an existing Word document, which is formatted for printing labels, and then insert each address into a different cell of the table. The current solution opens the Word application and moves the cursor to insert the text. However, after reading about the security issues and problems associated with opening the newer versions of Word from a web application, I have decided that I need to use another method.
I have looked into using Office Open XML, but I have not found any good resources that provide concrete information on exactly how to use it. Also, someone suggested that I use SQL reporting services, but searching for information on how to use them, lead me nowhere.
Which method do you think is the most appropriate for my problem?
Code samples and links to good tutorials would be extremely helpful. | Thanks for all the answers, but I really did not want to pay for a plugin and using Word automation was out of the question. So I kept searching and eventually, through some trial and error, found some answers.
After throughly searching through Microsoft's site, I found some newer articles on the Office Open XML SDK. I downloaded the new tools and just started going through each them.
I then found the Document Reflector, which creates a class to generate XML code based off an existing Word Document (.docx). Using my Label Template Document and the code this tool generated, I went through and added a loop that appends table cells for each address. It actually proved to be fairly simple and way faster than using Word automation.
So, if you're still using Word automation check out the Office Open XML tools. Their surprisingly extensive for a free download from Microsoft.
[Office Open XML SDK 2.0 Download](http://www.microsoft.com/downloads/details.aspx?FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&displaylang=en) | I use the Words plugin from [Aspose.com](http://www.aspose.com/) to do mail merges ([programming guide](http://www.aspose.com/documentation/file-format-components/aspose.words-for-.net-and-java/perform-mail-merge.html)). | Generating a Word Document with C# | [
"",
"c#",
".net",
"reporting-services",
"ms-word",
"openxml",
""
] |
I am working with JDBC and MySQL. I have a date column that I need included in my result set. Unfortunately, I cannot find a class in Java to retrieve the date. The SQL Date class is deprecated. How do you get Date objects from a result set? | You use [java.sql.Date](http://java.sun.com/javase/6/docs/api/java/sql/Date.html). A constructor and some methods are deprecated. The class isn't. Confused by this versus, say, [java.util.Date](http://java.sun.com/javase/6/docs/api/java/util/Date.html) or [java.util.Calendar](http://java.sun.com/javase/6/docs/api/java/util/Calendar.html)? Look at [Making Sense of Java's Dates](http://www.onjava.com/pub/a/onjava/2003/06/05/java_calendar.html).
There are three JDBC date/time types:
* [DATE](http://java.sun.com/javase/6/docs/api/java/sql/Types.html#DATE): granularity of days, use [java.sql.Date](http://java.sun.com/javase/6/docs/api/java/sql/Date.html);
* [TIMESTAMP](http://java.sun.com/javase/6/docs/api/java/sql/Timestamp.html): date and time, use [java.sql.Timestamp](http://java.sun.com/javase/6/docs/api/java/sql/Timestamp.html);
* [TIME](http://java.sun.com/javase/6/docs/api/java/sql/Types.html#TIME), just the time with no date, use [java.sql.Time](http://java.sun.com/javase/6/docs/api/java/sql/Time.html).
The confusion probably arises from the fact that java.sql.Date extends java.util.Date and thus inherits its deprecated methods.
Just use the right type for the type of your column. | I don't think the java.sql.Date class itself it deprecated, only one of its constructors. You should be safe to continue using it. | JDBC Dates Deprecated in Java (java.sql package) | [
"",
"java",
"jdbc",
""
] |
I want to loop through this array:
```
$securePages=array("admin.php","addslot.php","classpost.php");
$pagename="admin.php"
```
Then if admin.php is found then execute this code:
```
header("location:index.php");
exit();
```
How would I put together this looping statement? | ```
if (in_array("admin.php", $securePages)) {
header("location:index.php");
exit();
}
``` | ```
if (in_array($pagename, $securePages)) {
header("Location: http://example.com/index.php");
exit();
}
``` | how to loop through this array in php | [
"",
"php",
"arrays",
"loops",
""
] |
## First, some backstory:
I'm making what may amount to be a "[roguelike](http://en.wikipedia.org/wiki/Roguelike)" game so i can exersize some interesting ideas i've got floating around in my head. The gameplay isn't going to be a dungeon crawl, but in any case, the display is going to be done in a similar fasion, with simple ascii characters.
Being that this is a self exercise, *I endeavor to code most of it myself*.
Eventually I'd like to have the game runnable on arbitrarily large game worlds. (to the point where i envision havening the game networked and span over many monitors in a computer lab).
Right now, I've got some code that can read and write to arbitrary sections of a text console, and a simple partitioning system set up so that i can path-find efficiently.
---
## And now the question:
I've ran some benchmarks, and the biggest bottleneck is the re-drawing of text consoles.
Having a game world that large will require an intelligent update of the display. I don't want to have to re-push my entire game buffer every frame... **I need some pointers on how to set it up so that it only draws sections of the game have have been updated.** (and not just individual characters as I've got now)
I've been manipulating the windows console via windows.h, but I would also be interested in getting it to run on linux machines over a puTTY client connected to the server.
I've tried adapting some video-processing routines, as there is nearly a 1:1 ratio between pixel and character, but I had no luck.
Really I want a simple explanation of some of the principles behind it. But some example (psudo)code would be nice too. | I am not going to claim to understand this, but I believe this is close to the issue behind James Gosling's legendary [Gosling Emacs](http://en.wikipedia.org/wiki/Gosling_Emacs) redrawing code. See his paper, titled appropriately, "A Redisplay Algorithm", and also the general [string-to-string correction problem](http://en.wikipedia.org/wiki/String-to-string_correction_problem). | Use Curses, or if you need to be doing it yourself, read about the VTnnn control codes. Both of these should work on windows and on \*nix terms and consoles (and Windows). You can also consult the nethack source code for hints. This will let you change characters on the screen wherever changes have happened. | Help with algorithm to dynamically update text display | [
"",
"c++",
"perl",
"console-application",
"ascii-art",
""
] |
when programming in Java I practically always, just out of habit, write something like this:
```
public List<String> foo() {
return new ArrayList<String>();
}
```
Most of the time without even thinking about it. Now, the question is: should I *always* specify the interface as the return type? Or is it advisable to use the actual implementation of the interface, and if so, under what circumstances?
It is obvious that using the interface has a lot of advantages (that's why it's there). In most cases it doesn't really matter what concrete implementation is used by a library function. But maybe there are cases where it does matter. For instance, if I know that I will primarily access the data in the list randomly, a `LinkedList` would be bad. But if my library function only returns the interface, I simply don't know. To be on the safe side I might even need to copy the list explicitly over to an `ArrayList`:
```
List bar = foo();
List myList = bar instanceof LinkedList ? new ArrayList(bar) : bar;
```
but that just seems horrible and my coworkers would probably lynch me in the cafeteria. And rightfully so.
What do you guys think? What are your guidelines, when do you tend towards the abstract solution, and when do you reveal details of your implementation for potential performance gains? | > For instance, if I know that I will
> primarily access the data in the list
> randomly, a LinkedList would be bad.
> But if my library function only
> returns the interface, I simply don't
> know. To be on the safe side I might
> even need to copy the list explicitly
> over to an ArrayList.
As everybody else has mentioned, you just mustn't care about how the library has implemented the functionality, to reduce coupling and increasing maintainability of the library.
If you, as a library client, can demonstrate that the implementation is performing badly for your use case, you can then contact the person in charge and discuss about the best path to follow (a new method for this case or just changing the implementation).
That said, your example reeks of premature optimization.
If the method is or can be critical, it might mention the implementation details in the documentation. | Return the appropriate interface to hide implementation details. Your clients should only care about what your object offers, not how you implemented it. If you start with a private ArrayList, and decide later on that something else (e.g., LinkedLisk, skip list, etc.) is more appropriate you can change the implementation without affecting clients if you return the interface. The moment you return a concrete type the opportunity is lost. | When should I return the Interface and when the concrete class? | [
"",
"java",
"collections",
"abstraction",
""
] |
In terms of coder productivity what is the quickest way in VS 2005 or 2008 to determine if Foo implements IDisposable. It has happened to me on more than one occasion that I've been caught using a type without a `using` block because it never occured to me that the thing would need to implement IDisposable. | Put it in a using statement and see if it compiles:
```
using (var x = new TypeInQuestion(params)) {}
```
This won't compile if the `TypeInQuestion` doesn't implement IDisposable.
The other fastest way is to use ReSharper, click on the variable (`x` in this case), and see if it has a suggestion to put it in a using statement. | If you've got [ReSharper](http://www.jetbrains.com/resharper/), highlight the variable, wait for the lightbulb, and then hit Alt+Enter. If one of the options is "Wrap with 'using'", it's IDisposable. | while coding what's the quickest way to determine if a type is IDisposable | [
"",
"c#",
"visual-studio",
""
] |
My code is below, the code works fine when the strFilterText has a value but if the string is empty then it filters the rows that have no value which are the ones I want to show, for example if strFilterText contains "shoes" then the datagrid shows all the rows that contain "shoes" but if I want to find rows that have no category i.e. the catergory is NULL then strFilterText contains "" and I would like it to return everything with "" in the category but the code below shows me everything with a category if strFilterText is "".
Thanks for the help.
```
strFilterText += " LIKE '%" + txtboxValue.Text + "%'";
performFilter(strFilterText);
}
private void performFilter(string strFilterText)
{
DataTable table = dataGridView1.DataSource as DataTable;
if (table != null)
{
List<DataRow> filteredRows = new List<DataRow>(table.Select(strFilterText));
CurrencyManager cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
cm.SuspendBinding();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Visible = filteredRows.Contains(((DataRowView)row.DataBoundItem).Row);
}
cm.ResumeBinding();
}
}
``` | Try to change the first line to:
```
strFilterText+= string.IsNullOrEmpty(txtboxValue.Text)? " IS NULL" : " LIKE '%" + txtboxValue.Text + "%'";
``` | did you consider using a BindingSource as the DataSource for your DataGridView? It contains a property named "Filter", which you can assign a filter string to.
You will have to change strFilterText, however. To filter for you should use *FieldName IS NULL*. You may want to try this in your code as well - it might work for *table.Select*... | C# Removing rows from a datagrid where a cell value is not NULL using LIKE | [
"",
"c#",
"datagrid",
""
] |
I'm trying to copy data from one Oracle schema (`CORE_DATA`) into another (`MY_DATA`) using an `INSERT INTO (...)` SQL statement.
What would the SQL statement look like? | Prefix your table names with the schema names when logged in as a user with access to both:
```
insert into MY_DATA.table_name select * from CORE_DATA.table_name;
```
Assuming that the tables are defined identically in both schemas, the above will copy all records from the table named table\_name in CORE\_DATA to the table named table\_name in MY\_DATA. | ```
usage: COPY FROM [db] TO [db] [opt] [table] { ([cols]) } USING [sel]
[db] : database schema string, e.g., grprass/grprass@grprass, pplan/pplan@prassm1
[opt] : ONE of the keywords: APPEND, CREATE, INSERT or REPLACE
[table]: name of the destination table
[cols] : a comma-separated list of destination column aliases ( optional )
[sel] : any valid SQL SELECT statement
SQL> COPY FROM scott/tiger@schema1 TO scott/tiger@schema2 insert mytable using select * from mytable;
``` | Copying data between Oracle schemas using SQL | [
"",
"sql",
"oracle",
"insert",
"oracle10g",
"bulkinsert",
""
] |
Is it possible to see which constructor was the generic one?
```
internal class Foo<T>
{
public Foo( T value ) {}
public Foo( string value ) {}
}
var constructors = typeof( Foo<string> ).GetConstructors();
```
The property 'ContainsGenericParameters' returns me for both constructors false. Is there any way to find out that constructors[0] is the generic one? They both have the same signature, but I would like to call the "real" string one.
**EDIT:**
I want to invoke the given type using
```
ilGen.Emit( OpCodes.Newobj, constructorInfo );
```
so I need to work with the bound version. But I would like to invoke the "best" constructor. That should be the standard behaviour. When I call
```
new Foo<string>()
```
the constructor with the string-signature (and not the one with the generic signature) is called. The same should happen with my code. | You want System.Reflection.ParameterInfo.ParameterType.IsGenericParameter. Here's a VS2008 unit test that passes that illustrates this:
Class:
```
public class Foo<T>
{
public Foo(T val)
{
this.Value = val.ToString();
}
public Foo(string val)
{
this.Value = "--" + val + "--";
}
public string Value { get; set; }
}
```
Test method:
```
Foo<string> f = new Foo<string>("hello");
Assert.AreEqual("--hello--", f.Value);
Foo<int> g = new Foo<int>(10);
Assert.AreEqual("10", g.Value);
Type t = typeof(Foo<string>);
t = t.GetGenericTypeDefinition();
Assert.AreEqual(2, t.GetConstructors().Length);
System.Reflection.ConstructorInfo c = t.GetConstructors()[0];
System.Reflection.ParameterInfo[] parms = c.GetParameters();
Assert.AreEqual(1, parms.Length);
Assert.IsTrue(parms[0].ParameterType.IsGenericParameter);
c = t.GetConstructors()[1];
parms = c.GetParameters();
Assert.AreEqual(1, parms.Length);
Assert.IsFalse(parms[0].ParameterType.IsGenericParameter);
```
The notable point here is the parms[0].ParameterType.IsGenericParameter check which checks if the parameter is a generic or not.
Once you've found your constructor then you've got the ConstructorInfo to pass to Emit.
```
public System.Reflection.ConstructorInfo FindStringConstructor(Type t)
{
Type t2 = t.GetGenericTypeDefinition();
System.Reflection.ConstructorInfo[] cs = t2.GetConstructors();
for (int i = 0; i < cs.Length; i++)
{
if (cs[i].GetParameters()[0].ParameterType == typeof(string))
{
return t.GetConstructors()[i];
}
}
return null;
}
```
Not exactly sure what your intention is though. | Slight clarification. Neither of the constructors are generic methods. They are normal methods on a generic class. For a method to be "generic" it must have a generic parameter . So doing a test like "IsGenericMethod" will return false.
It's also not easy to simply look at the parameters and determine if they are generic. For the sample you gave it's possible to walk the arguments and look for a generic parameter. But also consider the following code
```
public Foo(IEnumerable<T> p1) ...
public Foo(IEnumerable<KeyValuePair<string,Func<T>>> p1) ...
```
You'll need to take items like this into account.
**EDIT**
The reason you're seeing all arguments as string is because you explicitly bound the type Foo before getting the constructors. Try switching your code to the following which uses an unbound Foo and hence will return generic parameters in the methods.
```
var constructors = typeof( Foo<> ).GetConstructors();
``` | Generic constructors and reflection | [
"",
"c#",
"generics",
"reflection",
""
] |
Let's say I have two or more tables filled with users and I want to retrieve all users from those tables in the same query.
Tables share some columns and those columns that have the same name are the ones I'm trying to retrieve.
Something like:
```
SELECT name, age FROM users1;
SELECT name, age FROM users2;
etc.
```
Note: this is just an example and not the real problem. I cannot combine those tables into one. | You can use [UNION](http://dev.mysql.com/doc/refman/5.0/en/union.html):
> UNION is used to combine the result from multiple SELECT statements into a single result set.
>
> The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type.
An example:
```
mysql> SELECT 1 as ColumnA,'a' as ColumnB
-> UNION
-> SELECT 2, 'b'
-> UNION
-> SELECT 3, 'c';
+---------+---------+
| ColumnA | ColumnB |
+---------+---------+
| 1 | a |
| 2 | b |
| 3 | c |
+---------+---------+
3 rows in set (0.05 sec)
```
Also note:
> The default behavior for UNION is that duplicate rows are removed from the result. The optional DISTINCT keyword has no effect other than the default because it also specifies duplicate-row removal. With the optional ALL keyword, duplicate-row removal does not occur and the result includes all matching rows from all the SELECT statements.
An example:
```
mysql> SELECT 1 as x
-> UNION
-> SELECT 1;
+---+
| x |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
mysql> SELECT 1 as x
-> UNION ALL
-> SELECT 1;
+---+
| x |
+---+
| 1 |
| 1 |
+---+
2 rows in set (0.00 sec)
``` | You can use `union` or `union all`, depending on what behaviour you want:
```
select name, age from users1
union
select name, age from users2
union
select name, age from users3
```
or:
```
select name, age from users1
union all
select name, age from users2
union all
select name, age from users3
```
The difference is that `union` removes duplicates, while `union all` doesn't.
If you know that there are no duplicates, you should use `union all` so that the database doesn't have to make the extra work of trying to find duplicates. | How can I retrieve similar rows from different tables in the same query? | [
"",
"sql",
"mysql",
""
] |
I have a string from an xml document:
```
<title type="html">
```
Is there a way for me to write this string like `"<title type="html">"`? I've had similar problems writing javascript as a string but I did see some solutions in the past (which I can't remember)?
Thanks | You can escape quotes in a string using a \
```
String s = "this is my \"data\" in the string";
``` | You need to escape your double quotes..
```
string blah = "<title type=\"html\">";
OR
string blah = @"<title type=""html"">";
```
Alternatively you could use single quotes in your tag, which will serve the same purpose.
```
string blah = "<title type='html'>";
``` | Writing a string which contains " " | [
"",
"c#",
""
] |
I have the following object in a list:
```
public class DemoClass
{
public int GroupKey { get; set; }
public string DemoString { get; set; }
public object SomeOtherProperty { get; set; }
}
```
Now, I want to create following dictionary out of it:
```
Dictionary<int, List<DemoClass>>
```
I want to group the `List<DemoClass>` by the property `GroupKey`, but I don't understand how this is done and some help.
After thinking a bit, I achieved the needed behaviour with:
```
var groupedDemoClasses = from demoClass in mySepcialVariableWhichIsAListOfDemoClass
group demoClass by demoClass.GroupKey
into groupedDemoClass
select groupedDemoClass;
var neededDictionary = groupedDemoClass.ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
```
but, is there a way to make this into a single statement? | ```
var groupedDemoClasses = (from demoClass in mySepcialVariableWhichIsAListOfDemoClass
group demoClass by demoClass.GroupKey
into groupedDemoClass
select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
```
This one will work !!! | Just to make [mquander's suggestion](https://stackoverflow.com/questions/938040/what-linq-statement-to-create-a-dictionary-on-a-list-with-group/938069#938069) concrete:
```
var groupedDemoClasses = mySpecialVariableWhichIsAListOfDemoClass
.GroupBy(x => x.GroupKey)
.ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
```
You'd make it shorter if you used shorter variable names too, of course :)
However, might I suggest that a [Lookup](http://msdn.microsoft.com/en-us/library/bb460184.aspx) might be more appropriate? A Lookup is basically a dictionary from a key to an `IEnumerable<T>` - unless you really *need* the values as a list, it makes the code even shorter (and more efficient) with the [ToLookup](http://msdn.microsoft.com/en-us/library/bb549073.aspx) call:
```
var groupedDemoClasses = mySpecialVariableWhichIsAListOfDemoClass
.ToLookup(x => x.GroupKey);
``` | Create a dictionary on a list with grouping | [
"",
"c#",
".net",
"linq",
".net-3.5",
""
] |
I have a byte array and wish to find the first occurance (if any) of a specific byte.
Can you guys help me with a nice, elegant and efficient way to do it?
```
/// Summary
/// Finds the first occurance of a specific byte in a byte array.
/// If not found, returns -1.
public int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{
}
``` | ```
public static int GetFirstOccurance(byte byteToFind, byte[] byteArray)
{
return Array.IndexOf(byteArray,byteToFind);
}
```
It will return -1 if not found
Or as Sam pointed out, an extension method:
```
public static int GetFirstOccurance(this byte[] byteArray, byte byteToFind)
{
return Array.IndexOf(byteArray,byteToFind);
}
```
Or to make it generic:
```
public static int GetFirstOccurance<T>(this T[] array, T element)
{
return Array.IndexOf(array,element);
}
```
Then you can just say:
```
int firstIndex = byteArray.GetFirstOccurance(byteValue);
``` | [Array.IndexOf](http://msdn.microsoft.com/en-us/library/system.array.indexof.aspx)? | Find First Specific Byte in a Byte[] Array c# | [
"",
"c#",
"design-patterns",
"arrays",
"search",
""
] |
I've got the following JSON:
```
{
"row": [
{
"sort":3,
"type":"fat",
"widgets":
[
{"values": [3,9] },
{"values": [8,4] }
]
},
{
"sort":2,
"type":"three",
"widgets":
[
{"values": [3,4] },
{"values": [12,7] },
{"values": [12,7] }
]
}
]
}
```
And this PHP to output it:
```
foreach ( $value->row as $therow )
{
echo "<div class='row ".$therow->type."'>";
foreach ( $therow->widgets as $thewidgets )
{
echo "<div class='widget'>";
echo $thewidgets->values[0];
echo "</div>";
}
echo "</div>";
}
```
What I would like to do is sort the ouput based on the sort value in the JSON, any ideas? | Use [usort](http://au.php.net/usort):
```
function my_sort($a, $b)
{
if ($a->sort < $b->sort) {
return -1;
} else if ($a->sort > $b->sort) {
return 1;
} else {
return 0;
}
}
usort($value->row, 'my_sort');
``` | See here:
[Sorting an associative array in PHP](https://stackoverflow.com/questions/777597/sorting-an-associative-array-in-php/777625)
for user-defined sorting. | Sorting JSON Output in PHP | [
"",
"php",
"arrays",
"json",
"sorting",
""
] |
I would like to create a C# ASP.Net application and query (read-on) information from our companies SharePoint site. Is this possible and if so how? | The best way for a standalone application to read data from a Sharepoint site from outside the farm is through [Sharepoint Web Services](http://www.csharphelp.com/archives4/archive602.html). That page has a high-level summary of what services are available and what each one does. In Visual Studio, you can connect to these by creating [Web References](http://msdn.microsoft.com/en-us/library/d9w023sx.aspx) to the desired services in your application. | Probably want to use the Lists.asmx service. From my memory, you should be able to reference the sharepoint services by http:///\_vti\_bin/Lists.asmx. There are services for data access, site/page management, security, etc..
As a default, If you have a list on a page called HR on a server called MyServer, it would be <http://MyServer/HR/_vti_bin/Lists.asmx>. Each new site will have these web services automatically created.
You can also reference the SAMS book "Microsoft Sharepoint 2007 Development". I used that for previous projects and it help. | Using SharePoint as a data source | [
"",
"c#",
"asp.net",
"sharepoint",
""
] |
Is there a method that I can add to my module, which will get called when destructing the class?
We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.
Was hoping there would be a `__del__` method either for modules or classes that don't have instances? | When destructing which class? I though you said module?
Your module lives until the interpreter stops. you can add something to run at that time using the "atexit" module:
```
import atexit
atexit.register(myfunction)
```
---
EDIT: Based on your comments.
Since you don't want it as a destructor, my answer above is correct. Just def another function (or static method if you wish) and register it with the atexit:
```
def close_database():
proceed_to_close()
import atexit
atexit.register(close_database)
```
Now a quick note on your definition.
You said the class doesn't have any instances. So why make it a class? Why not define the functions in the module level instead? modules are first-class objects, cached and imported only once...
Example, instead of defining `database.py`:
```
class DataBase(object):
@staticmethod
def execute_some_query(query):
code_here()
some_code()
@staticmethod
def close_database():
proceed_to_close()
import atexit ; atexit.register(DataBase.close_database)
```
and using:
```
from database import DataBase
DataBase.execute_some_query(query)
```
You could do this instead on `database.py`:
```
def execute_some_query(query):
code_here()
some_code()
def close_database():
proceed_to_close()
import atexit ; atexit.register(close_database)
```
And use it like this:
```
import database
database.execute_some_query(query)
```
---
Or better yet: Use [sqlalchemy](http://www.sqlalchemy.org/) and avoid all this trouble of creating your own database interface. | The class destructor method you're looking for is `__del__`. There are some nuances to when it's called, and to how exceptions and subclassing should be handled in `__del__`, so be sure to read the [official docs](http://docs.python.org/reference/datamodel.html#special-method-names).
A quick note on terminology, too: in python a `module` is the file in which your code is located... a namespace, in essence. A single module can contain many classes, variables, and functions. The `__del__` method is located on the class, not on the module. | Method that gets called on module deletion in Python | [
"",
"python",
"destructor",
"shutdown",
""
] |
I have a List and want to reduce it to a single value (functional programming term "fold", Ruby term `inject`), like
```
Arrays.asList("a", "b", "c") ... fold ... "a,b,c"
```
As I am infected with functional programming ideas (Scala), I am looking for an easier/shorter way to code it than
```
sb = new StringBuilder
for ... {
append ...
}
sb.toString
``` | What you are looking for is a string `join()` method which Java has since 8.0. Try one of the methods below.
1. Static method [`String#join(delimiter, elements)`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-):
```
Collection<String> source = Arrays.asList("a", "b", "c");
String result = String.join(",", source);
```
2. [Stream](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html) interface supports a fold operation very similar to Scala’s `foldLeft` function. Take a look at the following concatenating [Collector](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html):
```
Collection<String> source = Arrays.asList("a", "b", "c");
String result = source.stream().collect(Collectors.joining(","));
```
You may want to statically import `Collectors.joining` to make your code clearer.
By the way this collector can be applied to collections of any particular objects:
```
Collection<Integer> numbers = Arrays.asList(1, 2, 3);
String result = numbers.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
``` | To answer your original question:
```
public static <A, B> A fold(F<A, F<B, A>> f, A z, Iterable<B> xs)
{ A p = z;
for (B x : xs)
p = f.f(p).f(x);
return p; }
```
Where F looks like this:
```
public interface F<A, B> { public B f(A a); }
```
As dfa suggested, [Functional Java](https://github.com/functionaljava/functionaljava) has this implemented, and more.
Example 1:
```
import fj.F;
import static fj.data.List.list;
import static fj.pre.Monoid.stringMonoid;
import static fj.Function.flip;
import static fj.Function.compose;
F<String, F<String, String>> sum = stringMonoid.sum();
String abc = list("a", "b", "c").foldLeft1(compose(sum, flip(sum).f(",")));
```
Example 2:
```
import static fj.data.List.list;
import static fj.pre.Monoid.stringMonoid;
...
String abc = stringMonoid.join(list("a", "b", "c"), ",");
```
Example 3:
```
import static fj.data.Stream.fromString;
import static fj.data.Stream.asString;
...
String abc = asString(fromString("abc").intersperse(','));
``` | How to implement a list fold in Java | [
"",
"java",
"collections",
"functional-programming",
"folding",
""
] |
I'm writing an installer that will tune the configuration of the product for the particular hardware on which it will be run. In particular, I want to determine how much physical RAM is installed in the system so I can estimate how much memory to allocate to the product when it runs.
Ideally, I'd like to do this in a platform-independent, pure Java way, as the installer will need to run on several different platforms, but in case this isn't possible, solutions for Windows are preferred as that's the most common deployment platform.
In this case, it's safe to assume that the product will be the only/main application running on the box, so I don't have to worry about squeezing anyone else out. I don't want to over-allocate as this, in our experience, can hurt performance. | For windows, you'll need to access WMI - this will get you going: [Accessing Windows Management Instrumentation (WMI) from Java](http://j-integra.intrinsyc.com/support/com/doc/other_examples/WMI_Scripting_from_Java.htm).
You'll want to use this section of WMI: Win32\_LogicalMemoryConfiguration.
There may be a pure java way of doing this, but I am unaware of it. | You can use the following Java code to query the physical memory:
```
com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
long physicalMemorySize = os.getTotalPhysicalMemorySize();
```
But the package `com.sun.management` is optional and need not be available on every platform. | How do I find the physical memory size in Java? | [
"",
"java",
"memory",
"installation",
"memory-management",
""
] |
I'm working with Drupal at the moment and I'm having a real hard time searching the contents of various .module files. For example I want to search for something like "`div style="border: 1px solid red;`" and find out which file it's in.
All my code editors ignore the .module files in their search because it is a strange extension. Windows won't do it because it's on a networked location.
Any ideas? | Install [Cygwin](http://www.cygwin.com/), open a shell in your Drupal site's directory, and use `grep` --- a commandline utility to search files using regular expressions.
Something like this:
```
grep -r 'div style="border: 1px solid red;"' *
```
would recursively search every file for that string.
Or:
```
find . -name '*.module' -exec grep -H 'div style="border: 1px solid red;"' {} \;
```
would search only the `.module` files. | [ack](http://betterthangrep.com/) can do that for you pretty happily. For more convenience, you can also add in your `.ackrc` file the following:
--type-set=drupal=.php,.inc,.module,.install,.info,.engine
--type=drupal
So that typing
```
$ ack string
```
will find `string` in all drupal files under the current directory.
(Yes, it runs on windows, see the link). | How can I search the contents of .module files? | [
"",
"php",
"search",
"drupal",
"ide",
"dreamweaver",
""
] |
i have a WPF Application with a LoginWindow to access,so i create a Splash Screen for this Login window as follow :
**- in App.xaml**
```
< Application x:Class="WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup"
/>
```
-**in App.xaml.cs:**
```
private void Application_Startup(object sender, StartupEventArgs e)
{
Login login = new Login();
login.Show();
}
```
-**and in Login.xaml.cs if the log in is succesful :**
```
PrimaryWindow mainWindow= new PrimaryWindow ();
Application.Current.MainWindow = mainWindow;
this.Close();
mainWindow.Show();
```
.This code is right but sincerely with my poor knowledge i don't know that's a good method to apply for a Login Window or not and i don't know if this method can be "dangerous" for my application that store data from a database and has many features , so i ask you if my way is good or not and if you have a better way can you suggest or show me that?
Thanks for your attention.
Have a lucky day. | I would handle this with 2 windows and an Application\_Startup method. Here is what my app (which has a similar login idea) looks like:
```
/// In App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application {
private MainWindow main = new MainWindow();
private LoginWindow login = new LoginWindow();
private void Application_Startup(object sender, StartupEventArgs e) {
Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
Application.Current.MainWindow = login;
login.LoginSuccessful += main.StartupMainWindow;
login.Show();
}
}
/// In LoginWindow.xaml.cs
/// <summary>
/// Interaction logic for LoginWindow.xaml
/// </summary>
public partial class LoginWindow : Window {
internal event EventHandler LoginSuccessful;
public LoginWindow() { InitializeComponent(); }
private void logInButton_Click(object sender, RoutedEventArgs e) {
if ( // Appropriate Login Check Here) {
LoginSuccessful(this, null);
Close();
} else {
// Alert the user that login failed
}
}
}
/// In MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() { InitializeComponent(); }
internal void StartupMainWindow(object sender, EventArgs e) {
Application.Current.MainWindow = this;
Show();
}
}
```
This allows the user to close the application simply by closing the login window (i.e. not logging in at all) or by closing the main window AFTER they have used it for a while. | Im using this one
```
void App_Startup(object sender, StartupEventArgs e)
{
this.MainWindow = new MainWindow();
LoginWindow loginWindow = new LoginWindow();
if (loginWindow.ShowDialog() ?? false)
{
this.MainWindow.Show();
}
else
{
this.Shutdown();
}
}
```
Or this in case when MainWindow must be created *after* checking credentials.
```
void App_Startup(object sender, StartupEventArgs e)
{
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
LoginWindow loginWindow = new LoginWindow();
if (loginWindow.ShowDialog() ?? false)
{
this.ShutdownMode = ShutdownMode.OnMainWindowClose;
this.MainWindow = new MainWindow();
this.MainWindow.Show();
}
else
{
this.Shutdown();
}
}
``` | Login Wpf ...is it right? | [
"",
"c#",
".net",
"wpf",
""
] |
I want to be able to give a stored procedure a Month and Year and have it return everything that happens in that month, how do I do this as I can't compare between as some months have different numbers of days etc.?
What's the best way to do this? Can I just ask to compare based on the year and month?
Thanks. | I think the function you're looking for is [`MONTH(date)`](http://msdn.microsoft.com/en-us/library/ms187813.aspx). You'll probably want to use ['YEAR'](http://msdn.microsoft.com/en-us/library/ms187813.aspx) too.
Let's assume you have a table named `things` that looks something like this:
```
id happend_at
-- ----------------
1 2009-01-01 12:08
2 2009-02-01 12:00
3 2009-01-12 09:40
4 2009-01-29 17:55
```
And let's say you want to execute to find all the records that have a `happened_at` during the month 2009/01 (January 2009). The SQL query would be:
```
SELECT id FROM things
WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009
```
Which would return:
```
id
---
1
3
4
``` | Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.
I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.
You can then use
```
SELECT ... FROM ...
WHERE DateColumn >= @StartDate
AND DateColumn < DATEADD(month, 1, @StartDate)
```
If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from [a SQL Server blog](http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx).
```
create function Date(@Year int, @Month int, @Day int)
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
```
The query then becomes:
```
SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
``` | How to write a WHERE Clause to find all records in a specific month? | [
"",
"sql",
"sql-server-2008",
""
] |
After seeing some of the benefits of GWT, my partner and I decided that it would be a good front end for the web app we hope to build. A main part of this web app will be content management. We were hoping to use a CMS framework and put GWT on the front end, but all the open source CMS systems we find seem to be very tied to their front end.
Does anybody know of a CMS that would work well with GWT? | I think it all depends on how much integration you want, specifically, what you want to do with GWT. We have successfully integrated GWT with Documentum + Java on the back end.
With that said, our integration is fairly light. The site is largely a content oriented website, but we use GWT to:
1. Implement certain more dynamic widgets (e.g., text box with intelligent auto completion, font size changers).
2. Enhance content in the CMS to make it more animated (for instance, instead of displaying lots of content in a single screen, we use GWT's tab panel to display chunks at a time, while still allowing content authors to manage our content).
3. Implement "mini-apps" within the site.
Unfortunately, since this is something I do for a client, I cannot specifically mention the site by name in public, but if you're interested, I can share some details with you via e-mail. | No, but I can tell you that using a Java based CMS will make your life much much easier. GWT lives on RPC calls, and while translation / JSON overlays are possible, you're much better off with a Java backend.
You mind find this difficult, though, because when you want to use GWT you're doing a massive amount of work on the front end, leaving the backend mostly data processing and storage. Since very few CMSs are designed to do nothing more than processing and storage, you might be better off building your own.
That said, you might find it very easy if you're open to using App Engine. The GWT + App Engine stack works really well, now has a great Eclipse plugin dedicated to it, and is free to get started with. | GWT with a Content Management System | [
"",
"java",
"gwt",
"content-management-system",
""
] |
I am working on a project which involves the ExtJS library and I came upon this piece of code which did not make sense (but it works). Please help :(.
```
TreePanel.on('click', showDocumentFromTree);
function showDocumentFromTree(node) {
if (TreePanel.getSelectionModel().isSelected(node)) {
dataStore.baseParams = {
node : node.id,
limit : 10
}
dataStore.load({
params : {
start : 0
}
});
}
};
```
So the function definition for "showDocumentFromTree" has a parameter called "node" but when the code calls it, it did not pass in anything. Also, the object "node" is not a global (as far as I know).
So I'm confused on how that works? Is this some magic that Javascript has?
Also, when I do a console.debug to print "node" it has stuff in it. (console.debug for FireBug)
Thank you for your time,
J | In this case, the parameter to `showDocumentFromTree` is a magic parameter that is supplied by the browser when the user clicks on the element to which the action is attached. In this case, `node` will refer to the `TreePanel`. [Javascript - The this keyword](http://www.quirksmode.org/js/this.html) explains more detail about this mechanism. It is probably more common to use the parameter name `this` than `node` as in your example. | When the code is doing `TreePanel.on('click', showDocumentFromTree)', it *isn't* calling showDocumentFromTree, it's *passing* the function showDocumentFromTree as an argument. It will then be called later, by the onclick event handler that it's being set up for, and it will be passed its node argument then. | Javascript function parameters | [
"",
"javascript",
"function",
"parameters",
""
] |
In GMail, the mails are listed. When we we have lots of mails (ex:50), we can select and go to next page, select some more mail, and come back to page 1. But whatever mails the user checked will still be checked.
I just want to implement the same operation. How would I do that?
Thanks,
Krish
**Note**: I don't want to use AJAX. I'd rather use Javascript, CGI, PERL, etc. | 1. `<input type="checkbox" onclick="toggleValue(this)">` and in handler check the value and store it in array.
2. JQuery
```
$('input[type=checkbox].mail').click(
function()
{
if (this.checked) $(this).addClass('checked');
else $(this).removeClass('checked');
}
);
$('input[type=checkbox].mail.checked').each(function_here);
```
Can have some typos in the second one...
PS: don't know why, but the code above is not being formatted ( | Simple in theory. Just store the ids of checked mail in a JavaScript variable and/or cookie, and let them access (via AJAX) as many checkbox lists as they want, before submitting. | Multiple Page Check Box Handling | [
"",
"javascript",
"ajax",
"perl",
"cgi",
""
] |
I have this object `PreloadClient` which implements `IDisposable`, I want to dispose it, but after the asynchronous methods finish their call... which is not happening
```
private void Preload(SlideHandler slide)
{
using(PreloadClient client = new PreloadClient())
{
client.PreloadCompleted += client_PreloadCompleted;
client.Preload(slide);
}
// Here client is disposed immediately
}
private void client_PreloadCompleted(object sender, SlidePreloadCompletedEventArgs e)
{
// this is method is called after a while,
// but errors are thrown when trying to access object state (fields, properties)
}
```
So, any ideas or work arounds ?? | 1. You shouldn't use the `using` construct, but rather dispose your objects when they are no longer needed:
```
// keep a list of strong references to avoid garbage collection,
// and dispose them all in case we're disposing the encapsulating object
private readonly List<PreloadClient> _activeClients = new List<PreloadClient>();
private void Preload(SlideHandler slide)
{
PreloadClient client = new PreloadClient();
_activeClients.Add(client);
client.PreloadCompleted += client_PreloadCompleted;
client.Preload(slide);
}
private void client_PreloadCompleted(object sender,
SlidePreloadCompletedEventArgs e)
{
PreloadClient client = sender as PreloadClient;
// do stuff
client.PreloadCompleted -= client_PreloadCompleted;
client.Dispose();
_activeClients.Remove(client);
}
```
2. in this case, you have to dispose all clients when disposing the main class:
```
protected override Dispose(bool disposing)
{
foreach (PreloadClient client in _activeClients)
{
client.PreloadCompleted -= client_PreloadCompleted;
client.Dispose();
}
_activeClients.Clear();
base.Dispose(disposing);
}
```
3. **Note that this implementation is not thread safe**
* Access to the `_activeClients` list **must** be [made thread-safe](http://msdn.microsoft.com/en-us/library/ms173179%28v=vs.110%29.aspx), as your `PreloadCompleted` method is called from a different thread
* Your containing object may be disposed before a client fires the event. In that case "do stuff" should do nothing, so this is another thing you should take care of.
* It might be a good idea to use a `try`/`finally` block inside your event handler, to make sure that the object gets disposed in all cases | Why not dispose the client in the callback? | How to dispose objects having asynchronous methods called? | [
"",
"c#",
".net",
"asynchronous",
"dispose",
"idisposable",
""
] |
I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list. | Just create a string out of it.
```
myinteger = 212345
number_string = str(myinteger)
```
That's enough. Now you can iterate over it:
```
for ch in number_string:
print ch # will print each digit in order
```
Or you can slice it:
```
print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit
```
---
Or better, don't convert the user's input to an integer (the user types a string)
```
isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
```
For more information read a [tutorial](http://docs.python.org/tut). | ```
while number:
digit = number % 10
# do whatever with digit
# remove last digit from number (as integer)
number //= 10
```
On each iteration of the loop, it removes the last digit from number, assigning it to `digit`.
It's in reverse, starts from the last digit, finishes with the first | Split an integer into digits to compute an ISBN checksum | [
"",
"python",
"integer",
"decimal",
""
] |
What is the best practice when returning a smart pointer, for example a boost::shared\_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code):
```
class X
{
public:
boost::shared_ptr<Y> getInternal() {return m_internal;}
private:
boost::shared_ptr<Y> m_internal;
}
```
However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it? | There is no "right" way. It really depends on the context.
You can internally handle memory with a smart pointer and externally give references or raw pointers. After all, the user of your interface doesn't need to know how you manage memory internally. In a synchronous context this is safe and efficient. In an asynchronous context, there are many pitfalls.
If you're unsure about what to do you can safely return smart pointers to your caller. The object will be deallocated when the references count reaches zero. Just make sure that you don't have a class that keeps smart pointers of objects for ever thus preventing the deallocation when needed.
As a last note, in C++ don't overuse dynamically allocated objects. There are many cases where you don't need a pointer and can work on references and const references. That's safer and reduces the pressure on the memory allocator. | It depends on what the meaning of the pointer is.
When returning a shared\_pointer, you are syntactically saying "You will share ownership of this object", such that, if the the original container object dies before you release your pointer, that object will still exist.
Returning a raw pointer says: "You know about this object, but don't own it". It's a way of passing control, but not keeping the lifetime tied to the original owner.
(in some older c-programs, it means "It's now your problem to delete me", but I'd heavily recommend avoiding this one)
Typically, defaulting to shared saves me a lot of hassle, but it depends on your design. | best practice when returning smart pointers | [
"",
"c++",
"boost",
"smart-pointers",
""
] |
I'm trying to learn c++ and I really want to do a lot of coding but I'm not sure what I can code.. Tbh, book exercises are not very interesting to me (usually because they're just too short). I like to code OS related stuff like I/O stuff..
I'm thinking of looking at linux and try mimicking some of the tools there.. is that a good idea? | Rewriting tools is a good idea - my C++ professor made us rewrite all the standard library string functions by hand before we were allowed to use them in our homework assignments so that is something that may help you as well. You could also check out [Project Euler](http://projecteuler.net/). | Here's a good task that involves I/O, has interesting algorithm, is not too simple, not too difficult, and can even have practical application:
**Write a simple compressor / decompressor.**
Simple ideas to start with: LZW, Huffman codes. | learn and practice c++ | [
"",
"c++",
""
] |
How can I create a Timestamp with the date 23/09/2007? | By `Timestamp`, I presume you mean [`java.sql.Timestamp`](http://java.sun.com/javase/6/docs/api/java/sql/Timestamp.html). You will notice that this class has a constructor that accepts a `long` argument. You can parse this using the `DateFormat` class:
```
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
``` | What about this?
```
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");
``` | Java Timestamp - How can I create a Timestamp with the date 23/09/2007? | [
"",
"java",
"datetime",
"timestamp",
"date",
""
] |
I currently use Zend\_Db to manage my queries.
I've written already code that preforms queries like the one below:
```
$handle->select()->from('user_id')
->where('first_name=?', $id)
->where('last_name=?', $lname)
```
I've done this without sanitizing the input, assuming Zend\_Db will. Does Zend do this?
Another question:
Does Zend\_Db sanitize `insert('table', $data)` and `update` queries?
Thanks. | I wrote a lot of the code for database parameters and quoting in Zend Framework while I was the team lead for the project (up to version 1.0).
I tried to encourage best practices where possible, but I had to strike a balance with ease of use.
Note that you can always examine the string value of a `Zend_Db_Select` object, to see how it has decided to do quoting.
```
print $select; // invokes __toString() method
```
Also you can use the `Zend_Db_Profiler` to inspect the SQL that is run on your behalf by `Zend_Db`.
```
$db->getProfiler()->setEnabled(true);
$db->update( ... );
print $db->getProfiler()->getLastQueryProfile()->getQuery();
print_r $db->getProfiler()->getLastQueryProfile()->getQueryParams();
$db->getProfiler()->setEnabled(false);
```
Here are some answers to your specific questions:
* `Zend_Db_Select::where('last_name=?', $lname)`
Values are quoted appropriately. Although the "`?`" looks like a parameter placeholder, in this method the argument is actually quoted appropriately and interpolated. So it's not a true query parameter. In fact, the following two statements produce exactly the same query as the above usage:
```
$select->where( $db->quoteInto('last_name=?', $lname) );
$select->where( 'last_name=' . $db->quote($lname) );
```
However, if you pass a parameter that is an object of type `Zend_Db_Expr`, then it's not quoted. You're responsible for SQL injection risks, because it's interpolated verbatim, to support expression values:
```
$select->where('last_modified < ?', new Zend_Db_Expr('NOW()'))
```
Any other part of that expression that needs to be quoted or delimited is your responsibility. E.g., if you interpolate any PHP variables into the expression, safety is your responsibility. If you have column names that are SQL keywords, you need to delimit them yourself with `quoteIdentifier()`. Example:
```
$select->where($db->quoteIdentifier('order').'=?', $myVariable)
```
* `Zend_Db_Adapter_Abstract::insert( array('colname' => 'value') )`
Table name and column names are delimited, unless you turn off `AUTO_QUOTE_IDENTIFIERS`.
Values are parameterized as true query parameters (not interpolated). Unless the value is a `Zend_Db_Expr` object, in which case it's interpolated verbatim, so you can insert expressions or `NULL` or whatever.
* `Zend_Db_Adapter_Abstract::update( array('colname' => 'value'), $where )`
Table name and column names are delimited, unless you turn off `AUTO_QUOTE_IDENTIFIERS`.
Values are parameterized, unless they are `Zend_Db_Expr` objects, as in `insert()` method.
The `$where` argument is not filtered at all, so you're responsible for any SQL injection risks in that one. You can make use of the `quoteInto()` method to help make quoting more convenient. | Yes. See <http://framework.zend.com/manual/en/zend.db.select.html> . Don't worry. You're right to be skeptical. | avoiding MySQL injections with the Zend_Db class | [
"",
"php",
"mysql",
"zend-framework",
"zend-db-table",
""
] |
I'm writing a (Win32 Console) program that wraps another process; it takes parameters as in the following example:
```
runas.exe user notepad foo.txt
```
That is: `runas` parses `user` and then will run notepad, passing the remaining parameters.
My problem is that `argv` is broken down into individual parameters, but `CreateProcessAsUser` requires a single `lpszCommandLine` parameter.
Building this command line is probably not as simple as just joining `argv` back together with spaces. Any pointers?
This is just an example. My first argument isn't actually a user name, and might have spaces in it. This makes manually parsing the result of `GetCommandLine` tricky.
Similarly, a naive concatenation of `argv` won't work, because it needs to deal with the case where the original arguments were quoted and might have spaces in them. | **Manually recombining them is hard:**
You could try to re-combine them, I think it would work, but be sure to following [the same command line escaping rules that windows has](http://msdn.microsoft.com/en-us/library/17w5ykft.aspx). This could be more than the trivial solution you're looking for.
Also if there are any parameters that have spaces in them, then you would want to join them to the string with quotes around them. Here is an example of a strange escaping rule: if you have --folderpath `"c:\test\"` then the last backslash has to be doubled --folderpath `"c:\test\\"`.
**If you are using MFC:**
You can can get the value you want from your derived CWinApp's theApp.m\_lpCmdLine. Note you could still access them the other way too with \_\_argc, and \_\_argv or [CommandLineToArgvW](http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx).
**If you are using Win32 only (even without a GUI):**
You can get it from [WinMain](http://msdn.microsoft.com/en-us/library/ms633559(VS.85).aspx). Which can be your program's entry point.
Note you could still access them the other way too with \_\_argc, and \_\_argv or [CommandLineToArgvW](http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx).
**If you must use a console based application with main or wmain:**
The Win32 API [GetCommandLine](http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx) seems to be the way to go. You would need to still parse this to get past the .exe name though. Take into account quotes around the exe name/path too. If there are no such quotes at the start, then just go to the next space for the start. | You can use the [GetCommandLine](http://msdn.microsoft.com/en-us/library/ms683156(VS.85).aspx) function.
Why not use 'WinMain' instead of 'main'? This should give you the string in the format you want. | Converting argv back to a single string | [
"",
"c++",
"winapi",
"command-line",
""
] |
```
<script language="javascript" type="text/javascript">
var scrt_var = 10;
</script>
```
HTML Part:
```
<html>
this is a <a href ="2.html & Key= scrt_var">Link </a>
</html>
```
I just want to sent the javascript variable to link (url parameter)
No AJAX | If you want it to be dynamic, so that the value of the variable at the time of the click is used, do the following:
```
<script language="javascript" type="text/javascript">
var scrt_var = 10;
</script>
<a href="2.html" onclick="location.href=this.href+'?key='+scrt_var;return false;">Link</a>
```
Of course, that's the quick and dirty solution. You should really have a script that after DOM load adds an onclick handler to all relevant `<a>` elements. | put id attribute on anchor element
```
<a id="link2">
```
set href attribute on page load event:
```
(function() {
var scrt_var = 10;
var strLink = "2.html&Key=" + scrt_var;
document.getElementById("link2").setAttribute("href",strLink);
})();
``` | Passing Javascript variable to <a href > | [
"",
"javascript",
""
] |
It is my understanding that the default model binder is capable of turning
```
<input type="text" name="myType.property1" value="John Doe" />
<input type="text" name="myType.property2" value="22" />
```
into:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeAction(MyType myType)
{
// This will be "John Doe"
String someName = myType.property1;
// This will be 22
Int32 someNumber = myType.property2;
//
// irrelevant magic
}
```
In what scenario would I use the non-default model binder? I can't think of a reason not to name the HTML input's any differently than class property names. Please clarify, with an example.
Thank you! | In the scenario that your `MyType` for instance doesn't have a default constructor (the default modelbinder needs a default constructor).
This can happen if you use the factory method pattern for creating a new object (very simple example just for illustration ;-):
```
public class MyType
{
private MyType() // prevent direct creation through default constructor
{
}
public static MyType CreateNewMyType()
{
return new MyType();
}
}
```
Then you would have to implement a custom modelbinder which calls the factory method `CreateNewMyType()` instead of creating a new `MyType` through reflection:
```
public class MyTypeBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext,
Type modelType)
{
return MyType.CreateNewMyType();
}
}
```
Also if you're not happy with the current functionality or implementation of the default modelbinder, then you can easily replace it with your own implementation. | Scott Hanselman has [a simple case study for a custom model binder.](http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx)
The point of the post isn't that what he's trying to do can't be done other ways with the default binding, but that he's attempting it allows him to re-use code that will do the job for him. | C# MVC: When to use a specific (non-default) ModelBinder? | [
"",
"c#",
"asp.net-mvc",
""
] |
I tried to display the url using all sorts of methods of HttpRequest, I tried VirtualPathUtility object as well, but I never was able to display the hidden portion "default.aspx" of the default... what is the method or property that retrieves this segment of the url?
reason being, I am so close to creating a 404 on application level that catches all 404s, even html pages, by using File.Exist() on the mapped path of the url, unfortunately, that does not work on the default page.
I have seen few articles trying to do the opposite, remove default.aspx when it occurs, this is not the case here.
Edit: here is what I am trying:
```
string fullOrigionalpath = context.Request.CurrentExecutionFilePath.ToString();
bool newUrl = System.IO.File.Exists(context.Server.MapPath(fullOrigionalpath));
if (!newUrl) throw new HttpException(404,"page not found");
```
now you see, if the page is **localhost/lexus/default.aspx**, it works fine with no errors, but if I type in the address **<http://localhost/lexus/>**, the error is thrown, because if you try to output the fullOriginalPath, it does not have "default.aspx" part of it, so Exists returns false! do you have a better way of checking for validity of physical files? | I don't think this is at all possible, so I relied on IIS7.0 rewrite feature to force the default.aspx to appear at all times.. | I'm not sure what you mean by "hidden portion" but have you tried ...
```
Request.Url.ToString()
``` | retrieve the hidden default.aspx segment of a url | [
"",
"c#",
"asp.net",
"http-status-code-404",
""
] |
I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP\_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.
```
print "connecting"
server = smtplib.SMTP("smtp.gmail.com", 465)
print "ehlo"
server.ehlo()
print "start tls"
server.starttls()
print "ehlo"
server.ehlo()
print "log in"
if self.smtpuser:
server.login(smtpuser, smtppassword)
```
Does anybody have any advice for getting the above code to work with python 2.4? | When I tried setting something similar up for Django apps, I could never get it to work on port 465. Using port 587, which is the other port listed in the [GMail docs](http://mail.google.com/support/bin/answer.py?hl=en&answer=13287) seemed to work. | try
server.ehlo('user.name@gmail.com')
in both places above
also look at setting
server.set\_debuglevel(1) value as required for more info | Sending email using google apps SMTP server in Python 2.4 | [
"",
"python",
"python-2.4",
""
] |
I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json\_encode($arr);" it works fine, but I need to save the Object for caching).
> {"247":{"0":"This is a
> question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
> 2","962","0"],["Answer
> 3","961","0"],["Answer
> 4","963","0"]]},{"248":{"0":"This is a
> question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
> 2","962","0"],["Answer
> 3","961","0"],["Answer
> 4","963","0"]]}}
*just an excerpt*
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8\_general\_ci collation
Update 2: Maybe a little bit more code:
```
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
```
this loads the script and should alert "This is a question"
```
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
```
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
```
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
``` | I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
```
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
```
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
```
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
```
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
```
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
```
Hope that helps! | I got this to work in a slightly different manner. I've tried to illustrate how this was done.
**In Plain English:**
use *urldecode()*
**In Commented Code Fragments**
```
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
```
Hope this is helpful | JSON save in Database and load with JQuery | [
"",
"php",
"jquery",
"mysql",
"database",
"json",
""
] |
Here's my problem:
I have 2 projects - one 'common' projects with acts like a library with all kinds of support code, and the actual program that uses said project in many of its calls. We'll call these projects "Common" and "Program". They are both in the same solution.
Within "Common", I have a class for common reflection tasks, like creating an instance. If I call GetExecutingAssembly, it gets all the "Common" Types, however when I use GetEntryAssembly I get the "Program" types.
While I certainly could edit the code to work with 2 sets of asm, I'm afraid of a situation where there are more than just 2 projects in the solution - lets say 5 (don't know why, but lets just go there for now), and I'm afraid that calling GetExecutingAssembly and GetEntryAssembly will not get all the Types in the entire program.
Is there something else that i can do to get all the Types in a *solution*? | ```
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
```
This will get all of the loaded assemblies in the current AppDomain.
As noted in the comments, it's possible to spawn multiple AppDomains, in which case each can have its own assemblies. The immediate advantage to doing so is that you can unload Assemblies by unloading the containing AppDomain. | This is a *really* old question, but for future reference here's a complete implementation:
```
public static IEnumerable<Assembly> GetAssemblies()
{
var list = new List<string>();
var stack = new Stack<Assembly>();
stack.Push(Assembly.GetEntryAssembly());
do
{
var asm = stack.Pop();
yield return asm;
foreach (var reference in asm.GetReferencedAssemblies())
if (!list.Contains(reference.FullName))
{
stack.Push(Assembly.Load(reference));
list.Add(reference.FullName);
}
}
while (stack.Count > 0);
}
``` | C# Reflection: Get *all* active assemblies in a solution? | [
"",
"c#",
"reflection",
""
] |
I just listened to [podcast of Chris Smith talking about F#](http://www.code-magazine.com/codecast/index.aspx?messageid=7feb501f-25c8-432a-9624-97082f1e75e8) in which he talks about how F# is a language which allows you to **approach problems in a different way** than in C#/VB.NET, i.e. instead of "pushing bits around" you "chain together data transformations", and that how F# will "become like XML", something that you use in addition to your language of choice (C# or VB.NET) in order to solve certain problems in a more efficient way.
This **got me to thinking** about the relationship of the .NET languages, here's how I understand them:
* C# and VB.NET are **syntactically but not substantially different**, i.e. a C# programmer would not learn VB.NET in order to "approach problems in a new way"
* however, a C# or VB.NET programmer would learn F# in order to "approach programming problems **in a functional way**"
But what about **IronPython** and **IronRuby**? Chris mentioned that "F# learned a lot from Ruby and Python" so I would think that F# has a similar relationship to IronRuby/IronPython and C# has to VB.NET. However, a little googling around tells me that **IronRuby and IronPython are both built on the DLR but F# is not**.
**How are the relationships between F#, IronRuby and IronPython to be best understood?** | F# and IronPython/IronRuby are light years apart from a language perspective. F# is a functional, highly typed compiled language. IronRuby/IronPython are dynamically typed, interpreted languages.
I believe IronPython does additionally support compilation but I'm not 100% sure, and less about ruby.
The relationship between VB.Net and C# is much closer. | In many ways F# and Ruby/Python are superficially similar. All three languages allow you to concisely express ideas without littering your code with many types. However, F# is actually very different from Ruby and Python, since F# is a statically typed language, while Ruby and Python are dynamically typed. Idiomatic F# code rarely mentions types, but the compiler infers types and any type errors will be flagged by the compiler during compilation. For Ruby and Python, using a value at the wrong type will only generate errors at run-time. Ruby and Python’s dynamism means that both are more amenable to metaprogramming than F# is (types can be modified at runtime, for instance). On the other hand, F# is going to be more performant for most tasks (comparable to C#), and offers many nice functional abstractions such as discriminated unions with pattern matching. It’s certainly true that learning any of these languages well will lead you to think about problems differently than you do in C# or VB.NET, but your approach will probably vary a lot between F# and Python/Ruby as well. | is F# to IronPython/IronRuby as C# is to VB.NET? | [
"",
"c#",
"vb.net",
"f#",
"ironpython",
"ironruby",
""
] |
What is the best way to know if the code block is inside TransactionScope?
Is Transaction.Current a realiable way to do it or there are any subtleties?
Is it possible to access internal ContextData.CurrentData.CurrentScope (in System.Transactions) with reflection? If yes, how? | Here is more reliable way (as I said, Transaction.Current can be set manually and it doesn't always mean we are really in TransactionScope). It's also possible to get this information with reflection, but emiting IL works 100 times faster than reflection.
```
private Func<TransactionScope> _getCurrentScopeDelegate;
bool IsInsideTransactionScope
{
get
{
if (_getCurrentScopeDelegate == null)
{
_getCurrentScopeDelegate = CreateGetCurrentScopeDelegate();
}
TransactionScope ts = _getCurrentScopeDelegate();
return ts != null;
}
}
private Func<TransactionScope> CreateGetCurrentScopeDelegate()
{
DynamicMethod getCurrentScopeDM = new DynamicMethod(
"GetCurrentScope",
typeof(TransactionScope),
null,
this.GetType(),
true);
Type t = typeof(Transaction).Assembly.GetType("System.Transactions.ContextData");
MethodInfo getCurrentContextDataMI = t.GetProperty(
"CurrentData",
BindingFlags.NonPublic | BindingFlags.Static)
.GetGetMethod(true);
FieldInfo currentScopeFI = t.GetField("CurrentScope", BindingFlags.NonPublic | BindingFlags.Instance);
ILGenerator gen = getCurrentScopeDM.GetILGenerator();
gen.Emit(OpCodes.Call, getCurrentContextDataMI);
gen.Emit(OpCodes.Ldfld, currentScopeFI);
gen.Emit(OpCodes.Ret);
return (Func<TransactionScope>)getCurrentScopeDM.CreateDelegate(typeof(Func<TransactionScope>));
}
[Test]
public void IsInsideTransactionScopeTest()
{
Assert.IsFalse(IsInsideTransactionScope);
using (new TransactionScope())
{
Assert.IsTrue(IsInsideTransactionScope);
}
Assert.IsFalse(IsInsideTransactionScope);
}
``` | `Transaction.Current` should be reliable; I've just checked, at this works fine with suppressed transactions, too:
```
Console.WriteLine(Transaction.Current != null); // false
using (TransactionScope tran = new TransactionScope())
{
Console.WriteLine(Transaction.Current != null); // true
using (TransactionScope tran2 = new TransactionScope(
TransactionScopeOption.Suppress))
{
Console.WriteLine(Transaction.Current != null); // false
}
Console.WriteLine(Transaction.Current != null); // true
}
Console.WriteLine(Transaction.Current != null); // false
``` | How to know if the code is inside TransactionScope? | [
"",
"c#",
".net",
"transactionscope",
""
] |
I want to hide an external application, ie. not the current application. I want to give the title of the application and it will be hidden. How can I do this programmatically? | In general terms, you could call [`FindWindow`](http://msdn.microsoft.com/en-us/library/ms633499.aspx) to get the HWND of the window in question, then [`ShowWindow`](http://msdn.microsoft.com/en-us/library/ms633548.aspx) with `SW_HIDE` to hide the window. | You need to get a handle to the window (which you can do using [FindWindow()](http://msdn.microsoft.com/en-us/library/ms633499.aspx)). Then you need to call [ShowWindow()](http://msdn.microsoft.com/en-us/library/ms633548.aspx) and set it's shown state to hidden. | How to hide an external program's windows programmatically? | [
"",
"c++",
"c",
"windows",
"winapi",
""
] |
I have title (varchar), description (text), keywords (varchar) fields in my mysql table.
I kept keywords field as I thought I would be searching in this field only. But I now require to search among all three fields. so for keywords "word1 word2 word3", my query becomes
```
SELECT * FROM myTable
WHERE (
name LIKE '%word1%' OR description LIKE '%word1%' OR keywords LIKE '%word1%'
OR name LIKE '%word2%' OR description LIKE '%word2%' OR keywords LIKE '%word2%'
OR name LIKE '%word3%' OR description LIKE '%word3%' OR keywords LIKE '%word3%')
AND status = 'live'
```
Looks a bit messy but this works. But now I need to implement synonym search. so for a given word assuming there are a few synonyms available this query becomes more messy as I loop through all of the words. As the requirements are getting clearer, I will need to join this myTable to some other tables as well.
So
* Do you think the above way is messy and will cause problems as the data grow?
* How can I avoid above mess? Is there any cleaner solution I can go by? Any example will help me.
* Is there any other method/technique you can recommend to me?
With thanks
## EDIT
@Peter Stuifzand suggested me that I could create one search\_index table and store all 3 fields (title,keyword,desc) info on that and do full text search. I understand that additionally this table will include reference to myTable primary key as well.
But my advanced search may include joining mytable with Category table, geographic\_location table (for searching within 10, 20 miles etc), filtering by someother criteria and of course, sorting of search results. Do you think using mysql fulltext will not slow it down? | When your queries are getting out of hand, it's sometimes better to write parts of it in SQL and other parts in your programming language of choice.
And you could also use fulltext search for searching. You can create separate table with all fields that you want to search and add the `FULLTEXT` modifier.
```
CREATE TABLE `search_index` (
`id` INT NOT NULL,
`data` TEXT FULLTEXT,
);
SELECT `id` FROM `search_index` WHERE MATCH(`data`) AGAINST('word1 word2 word3');
``` | One more way (sometimes it's better but it depends...)
```
SELECT
id, name, description, keywords
FROM
myTable
WHERE
name REGEXP '.*(word1|word2|word3).*' OR
description REGEXP '.*(word1|word2|word3).*' OR
keywords REGEXP '.*(word1|word2|word3).*'
;
```
PS: But `MATCH(cols) AGAINST('expr')` possibly is better for your case. | Keyword search using PHP MySql? | [
"",
"php",
"mysql",
"search",
""
] |
I have created a messaging system which allows users to send messages to eachother. This works fine but when they reply I dont want them being taken to another page, I want a alert to say "sent" or "not sent". Below is my code which doesnt work.
in php:
```
echo"<form id=\"form\" name=\"form\" method=\"post\" onsubmit=\"send(reply)\">";
```
javascript:
```
function send(reply)
{
var httpRequest;
make_request()
function stateck()
{
if(httpxml.readyState==4)
{
alert (httpxml.responseText);
}
httpxml.onreadystatechange=stateck;
reply_url="compose.php?reply=" + reply.value + "&msgid="<?php echo $msgid; ?> + "&to="<?php echo $to; ?> + "&subject="<?php echo $subject; ?>";
httpxml.open("GET",reply_url,true);
httpxml.send(null);
}
}
```
I am using php php variables as this data needs to be accessed from the database.
Thanks | You need to tell the browser that you handled the event yourself by returning false in your on submit handler:
```
echo"<form id=\"form\" name=\"form\" method=\"post\" onsubmit=\"send(reply); return false;\">";
```
Also your send function looks like it is going to generate an error, which will cause the browser to submit. You are not assigning to httpxml anywhere. I assume you really want:
```
function send(reply) {
var httpxml;
httpxml = make_request();
stateck = function () {
if(httpxml.readyState==4){
alert (httpxml.status);// you will want to check the server response code too
alert (httpxml.responseText);
}
};
httpxml.onreadystatechange=stateck;
reply_url="compose.php?reply=" + reply.value + "&msgid="<?php echo $msgid; ?> + "&to="<?php echo $to; ?> + "&subject="<?php echo $subject; ?>";
httpxml.open("GET",reply_url,true);
httpxml.send(null);
}
``` | It took you to a different page because the form submit occurred. If you don't want the form submit to take place, use
```
onsubmit="send(reply); return false;"
```
By the way, you can use single quote: echo ' ... ' so that you don't need to escape all the double quotes in the string. | submit form using ajax and return result | [
"",
"javascript",
""
] |
My issue is that I want to run a query to check if the data I am using will be a duplicate of something already in the database, for example I have a Product Code and want to stop the same item being listed multiple times, and this Product Code is the Primary Key.
Can I avoid doing this:
```
SELECT ProductCode FROM tblProducts WHERE ProductCode = '12345'
```
And then checking for any returned records, or is there a more elegant solution, I don't mind using this method but it seems clunky to be. This is just some extra validation to my code as the insertion of a product should only happen once - but I want error checking on this as duplicates have been entered due to refresh or back button use (web-based system).
Wonder if this is the P = NP type problem or am I overthinking the problem?
My Database is MS SQL Server 2000 if this helps. | I would recommend just letting the SQL insertion fail and let SQL Server through a primary key violation error and handle it. SQL Server maintains an index and they have been doing it for years. I am pretty sure that their implementation is going to be many times better than most developers out there. If you are trying to program for that you will need to read in all the keys and keep them in an index somewhere. SQL Server is already doing that. So then you have double checking and double the amount of space needed.
The only time I would consider doing this if the connection to your database is very slow for some or other reason.
Otherwise let SQL Server do what it is good and you do the rest :) | Simply allow SQL to test first before inserting
```
IF NOT EXISTS (SELECT * FROM tblProducts WHERE tblProducts = '12345')
INSERT tblProducts (tblProducts, columnlist, ...)
VALUES ('12345', valuelist, ...)
```
This is better wrapped in a stored procedure so it's self contained in the database (but everyone has their own view on this). | Is it possible to easily detect or predict a Primary Key violation in SQL? | [
"",
"sql",
"sql-server",
"database",
"primary-key",
""
] |
I had found written in python, a very simple http server, it's do\_get method looks like this:
```
def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers();
filepath = self.path
print filepath, USTAW['rootwww']
f = file("./www" + filepath)
s = f.readline();
while s != "":
self.wfile.write(s);
s = f.readline();
return
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
```
It works ok, besides the fact - that it is not serving any css files ( it is rendered without css). Anyone got a suggestion / solution for this quirk?
Best regards,
praavDa | it seems to be returning the html mimetype for all files:
```
self.send_header('Content-type', 'text/html')
```
Also, it seems to be pretty bad. Why are you interested in this sucky server? Look at cherrypy or paste for good python implementations of HTTP server and a good code to study.
---
**EDIT**: Trying to fix it for you:
```
import os
import mimetypes
#...
def do_GET(self):
try:
filepath = self.path
print filepath, USTAW['rootwww']
f = open(os.path.join('.', 'www', filepath))
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
else:
self.send_response(200)
mimetype, _ = mimetypes.guess_type(filepath)
self.send_header('Content-type', mimetype)
self.end_headers()
for s in f:
self.wfile.write(s)
``` | You're explicitly serving all files as `Content-type: text/html`, where you need to serve CSS files as `Content-type: text/css`. See [this page on the CSS-Discuss Wiki](http://css-discuss.incutio.com/?page=MozillaCssMimeType) for details. Web servers usually have a lookup table to map from file extension to Content-Type. | Custom simple Python HTTP server not serving css files | [
"",
"python",
"css",
"http",
""
] |
I have a little issue that is causing me a headache. Our Report Server is SQL Ent 2008 on a Win 2008 server. When users that have Report Browser permissions try to set up a report subscription the To: field is grayed out and pre-populated with their username. They cannot change this and it won't deliver to their email address which would be username@domain.com. Any leads would be greatly appreciated. | "Site Settings".."Configure item-level role definitions".."Browser"
They can only "Manage individual subscriptions". SSRS won't allow the email address to be changed because they could put any stuff in there.
In BOL, [Managing Subscriptions](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms157339(v=sql.105))... and [How to: Subscribe to a Report (Report Manager)](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms157386(v=sql.105)), which leads to [Configuring a Report Server for E-Mail Delivery](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms159155(v=sql.105)). This says:
> Configuration Options for Setting the
> To: Field in a Message
>
> User-defined subscriptions that are
> created according to the permissions
> granted by the Manage individual
> subscriptions task contain a pre-set
> user name that is based on the domain
> user account. When the user creates
> the subscription, the recipient name
> in the To: field is self-addressed
> using the domain user account of the
> person creating the subscription.
>
> If you are using an SMTP server or
> forwarder that uses e-mail accounts
> that are different from the domain
> user account, the report delivery will
> fail when the SMTP server tries to
> deliver the report to that user.
>
> To workaround this issue, you can
> modify configuration settings that
> allow users to enter a name in the To:
> field:
>
> 1. Open RSReportServer.config with a text editor.
> 2. Set SendEmailToUserAlias to False.
> 3. Set DefaultHostName to the Domain Name System (DNS) name or IP
> address of the SMTP server or
> forwarder.
> 4. Save the file. | I realize that this is on a 3 year old post (there was activity on it 5 months ago as of this posting though) but I found one other tid-bit that may be of use to others trying to get around this.
As part of the configuration file RSReportServer.config as mentioned in above answers found at *installdir*\Reporting Services\ReportServer\ there is a section of the file that you can add your domain name to that works in conjunction with the users alias.
The tag to edit is **DefaultHostName** as stated in Microsofts documentation this value works with the **SendEmailToUserAlias** tag when it's set to true.
The end user still has a grayed out To: field that shows their AD user alias, however when they setup a subscription to email a report, at execution time the SMTP server appends the specified domain (from the DefaultHostName tag) to the alias.
I didn't want to go with the work-a-round specified in the previous answer as I did not want end users to be able to specify any email address.
This worked for me in SSRS for SQL 2008 R2. Documentation from Microsoft here (http://msdn.microsoft.com/en-us/library/ms157273.aspx#bkmk\_email\_extension)
N.B. make sure you turn of the reporting services process before changing the file, after making and saving the changes, start the process back up. | Reporting Services Subscriptions won't allow modification of the To: Field | [
"",
"sql",
"sql-server",
"sql-server-2008",
"reporting-services",
""
] |
I want to create a small function in PHP which takes in arguments like color, shape, transparency etc. and outputs a PNG image. I heard about PHP GD library but I want to know how can one create something as creative as [soon.media.mit.edu](http://soon.media.mit.edu/masthead/?short=1;solid=c30;fuzz=0.62) | [This is a good example](http://php.net/manual/en/image.examples-png.php), you can do virtually everything using [these functions](http://php.net/manual/en/book.image.php). While possible, creating an image like the one you described would be pretty hard by I have done some weird stuff with gradients, loops and colors though.
If you wanted to make an image like that dynamically based on some parameters you can always create the images beforehand in photoshop and then overlay them based on what a user selects.
There is a lot of fun you can have.
Edit: Oh by the way, if your interested [giving an invalid parameter shows some of the python code](http://soon.media.mit.edu/masthead/?short=0.4;solid=c30;fuzz=invalid) that is responsible for creating the image and causing the error. It would be a good place to get some idea of the code.
2nd Edit: This is just something I have done with this sort of technology. Bear in mind it was quite a while ago. It accepts a name based on the query string and basically does a few loops with a lot of random numbers.
Here is the source code, I apologize for any stupid code/quotes. This was written quite a while ago, when I was about 14 I believe (probably many flaws).
```
<?php
header("Content-type:image/jpeg");
$array=array("I am a monument to all your sins", "Currently making pizza","Best before 12/7/09", "Farming Onions");
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
// retrieve boundingbox
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
// calculate deviation
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0; // deviation left-right
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0; // deviation top-bottom
// new pivotpoint
$px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $y, $color, $fontfile, $text);
}
$image = imagecreate(500,90);
$black = imagecolorallocate($image,0,0,0);
$grey_shade = imagecolorallocate($image,40,40,40);
$white = imagecolorallocate($image,255,255,255);
$text = $array[rand(0,sizeof($array)-1)];
// Local font files, relative to script
$otherFont = 'army1.ttf';
$font = 'army.ttf';
if($_GET['name'] == ""){ $name = "Sam152";}else{$name= $_GET['name'];}
$name = substr($name, 0, 25);
//BG text for Name
while($i<10){
imagettftext_cr($image,rand(2,40),rand(0,50),rand(10,500),rand(0,200),$grey_shade,$font,$name);
$i++;
}
//BG text for saying
while($i<10){
imagettftext_cr($image,rand(0,40),rand(90,180),rand(100,500),rand(200,500),$grey_shade,$otherFont,$text);
$i++;
}
// Main Text
imagettftext_cr($image,35,0,250,46,$white,$font,$name);
imagettftext_cr($image,10,0,250,76,$white,$otherFont,$text);
imagejpeg($image);
?>
``` | Here's the code that I used before to generate an image with two names, which are accepted from query string parameters. I use a prepared background image and put the names on top of it.
```
<?php
// Print two names on the picture, which accepted by query string parameters.
$n1 = $_GET['n1'];
$n2 = $_GET['n2'];
Header ("Content-type: image/jpeg");
$image = imageCreateFromJPEG("images/someimage.jpg");
$color = ImageColorAllocate($image, 255, 255, 255);
// Calculate horizontal alignment for the names.
$BoundingBox1 = imagettfbbox(13, 0, 'ITCKRIST.TTF', $n1);
$boyX = ceil((125 - $BoundingBox1[2]) / 2); // lower left X coordinate for text
$BoundingBox2 = imagettfbbox(13, 0, 'ITCKRIST.TTF', $n2);
$girlX = ceil((107 - $BoundingBox2[2]) / 2); // lower left X coordinate for text
// Write names.
imagettftext($image, 13, 0, $boyX+25, 92, $color, 'ITCKRIST.TTF', $n1);
imagettftext($image, 13, 0, $girlX+310, 92, $color, 'ITCKRIST.TTF', $n2);
// Return output.
ImageJPEG($image, NULL, 93);
ImageDestroy($image);
?>
```
To display the generated image on the page you do something like this:
```
<img src="myDynamicImage.php?n1=bebe&n2=jake" />
``` | Create a dynamic PNG image | [
"",
"php",
"image",
"png",
""
] |
My application is configured by some Spring XML configuration files.
Is it good practice in Java to include the XML files in the classpath, and reference them in my application using the classpath? | I usually look in a system property first then the classpath. so:
```
java -DconfigFile=/filelocation/file.xml
```
can be read as:
```
String propfile = System.getProperty(configFile);
if (propfile != null) {
// read in file
new File(propfile);
...
} else {
// read in file from classpath
getClass.getResource("/configfile.xml")
}
``` | It's nice to be able to configure it both ways - either directly as a file, or via a resource on the classpath which may or may not be in a jar file. That gives you a lot of flexibility. | Good practice to include XML config in Java classpath? | [
"",
"java",
"spring",
""
] |
It is pretty common, especially in applications with an ORM, to have a two way mapping between classes. Like this:
```
public class Product
{
private List<Price> HistoricPrices { get; private set;}
}
public class Price
{
private Product Product { get; set; }
}
```
Is there an accepted way of maintaining this relationship in code? So that when I add a price to a product the Product property gets set automatically?
Ideally I am looking for an easily reusable solution. It seems wrong to have to add something to a collection and then set the opposite relations manually.
Please note that this is not a question about how to model products and prices, It is a question of how to model a 2 way relationship. There are plenty of situations where this is perfectly reasonable. | First, I think the example your present is confusing - it's uncommon for something like a Price to be modeled as an object or to have reference to the entities that would have a price. But I think the question is legitimate - in the ORM world this is sometimes referred to as graph consistency. To my knowledge there isn't *one* definitive way to tackle this problem, there are several ways.
Let's start by changing the example slightly:
```
public class Product
{
private Manufacturer Manufacturer { get; private set; }
}
public class Manufacturer
{
private List<Product> Products { get; set; }
}
```
So every Product has one Manufacturer, and each Manufacturer could have a list of products. The challenge with the model is that if the Product class and Manufacturer class maintain disconnected references to one another, updating one can invalidate the other.
There are several ways to address this issue:
1. Eliminate the circular reference. This solves the problem but makes the object model less expressive and harder to use.
2. Change the code so that the Manufacturer reference in Product and Products list in Manufacturer are *reflexive*. In other words, changing one affects the other. This generally requires some code the setter and the collection to intercept changes and *reflect* them into one another.
3. Manage one property in terms of the other. So, rather than storing a reference to a manufacturer within Product, you compute it by search through all Manufacturers until you find the one that owns you. Conversely, you could keep a reference to the Manufacturer in the Product class and build the list of Products dynamically. In this approach, you would generally make one side of the relationship read-only. This, by the way, is the standard relational database approach - entities refer to each other through a foreign key which is managed in one place.
4. Externalize the relationship from *both* classes and manage it in a separate object (often called a data context in ORM). When Product wants to return its manufacturer it asks the DataContext. When the Manufacturer want to return a list of Products it does the same. Internally, there are many ways to implement a data context, a set of bi-directional dictionaries is not uncommon.
Finally, I will mention, that you should consider using an ORM tool (like NHibernate or CSLA) that can help you manage graph consistency. This is generally not an easy problem to solve correctly - and it can easily become very complicated once you start exploring cases like many-to-many relationships, one-to-one relationships, and lazy loading of objects. You are better of using an existing library or product, rather than inventing a mechanism of your own.
Here are some [links](http://www.nablasoft.com/alkampfer/index.php/2009/05/05/maintain-integrity-in-nhibernate-bidirectional-association/) that talk about [bidirectional associations](http://sdesmedt.wordpress.com/2006/10/21/nhibernate-part-5-mapping-techniques-for-aggregation-many-to-one-and-many-to-many-mapping/) in NHibernate that you may find useful.
Here's a code example of managing the relationships directly yourself using method #2 - which is typically the simplest. Note that only one side of the relationship is editable (in this case, the Manufacturer) - external consumers cannot directly set the Manufacturer of a Product.
```
public class Product
{
private Manufacturer m_manufacturer;
internal Manufacturer Manufacturer
{
get { return m_manufacturer; }
set { m_manufacturer = value; }
}
}
public class Manufacturer
{
private List<Product> m_Products = new List<Product>();
public IEnumerable<Product> Products { get { return m_Products.AsReadOnly(); } }
public void AddProduct( Product p )
{
if( !m_Products.Contains( p ) )
{
m_Products.Add( p );
p.Manufacturer = this;
}
}
public void RemoveProduct( Product p )
{
m_Products.Remove( p );
p.Manufacturer = null;
}
}
``` | This is not the correct way to model this problem.
A `Product` ought to have a `Price`, a `Price` ought not to have a `Product`:
```
public class Product
{
public Price CurrentPrice {get; private set; }
public IList<Price> HistoricPrices { get; private set;}
}
public class Price { }
```
In your particular setup, what does it mean to for a `Price` to have a `Product`? In the class I created above you would be able to handle all pricing within the `Product` class itself. | Maintaining a two way relationship between classes | [
"",
"c#",
""
] |
I'm writing a plugin for an application with a .NET API. The objects of the program can have custom attributes applied through two methods of the root object type which assign key/value pairs to the objects.
```
BaseAppObject.GetUserString(string key, string value);
BaseAppObject.SetUserString(string key, ref string value);
```
I'm creating a set of my own custom classes that act as wrapper classes around instances of `BaseAppObject`. All my classes are derived from a class `Node` which has a field to store a reference to a `BaseAppObject`. Other properties of `Node` and types that derive from `Node` use the `GetUserString` and `SetUserString` methods of the associated `BaseAppObject` instance to read or write property values directly to or from the associated `BaseAppObjects`.
This way when the application is closed all the information needed to regenerate these wrapper classes later is stored in the actual document.
Here's a simplified version of what I have for my base class constructor:
```
public abstract class Node
{
BaseAppObject _baseObject;
public Node(BaseAppObject baseObject, string name)
{
this._baseObject = baseObject;
this.Name = name;
}
public string Name
{
get {
string name = "";
_baseObject.GetUserString("CPName", ref name);
return name;
}
set {
_baseObject.SetUserString("CPName", value);
}
}
}
```
Other classes derived from `Node` may add additional properties like this.
```
public CustomClass:Node
{
public CustomClass(BaseAppObject baseObj,string name, string color):base(baseObj,name)
public string Color
{
get {
string name = "";
this.BaseObject.GetUserString("Color", ref name);
return name;
}
set {
this.BaseObject.SetUserString("Color", value);
}
}
}
```
I'm trying to figure out the best way to setup the constructors and other methods of my classes to initiate and regenerate instances of my classes. I need to be able to create new instances of my classes based of *clean* instances of `BaseAppObject` that have no user strings defined, and also regenerate previously existing instance of my class based on the user strings stored in a existing `BaseAppObject`. | It looks like you have already figured out how to regenerate previously existing classes. To generate a clean object with no values, all you have to do is provide an additional overload that takes no parameters and creates \_baseObject. Once the object is created in this manner, you can use it's properties to set the member values.
```
public abstract class Node
{
BaseAppObject _baseObject;
//Empty constructor
public Node()
{
BaseAppObject = new BaseAppObject();
}
public Node(BaseAppObject baseObject, string name)
{
this.BaseObject = baseObject;
this.Name = name;
}
public string Name
{
get {
string name = "";
_baseObject.GetUserString("CPName", ref name);
return name;
}
set {
_baseObject.SetUserString("CPName", value);
}
}
}
public CustomClass:Node
{
// Empty constructor
public CustomClass() : Base() {}
public CustomClass(BaseAppObject baseObj,string name, string color):base(baseObj,name)
public string Color
{
get {
string name = "";
this.BaseObject.GetUserString("Color", ref name);
return name;
}
set {
this.BaseObject.SetUserString("Color", value);
}
}
}
```
Sample code for creating an empty object and populating it:
```
CustomClass node = new CustomClass();
node.Name = "foo";
node.Color = "bar";
``` | I have written a base Wrapper Object that I have all my wrappers inherit from.
```
public abstract class BaseWrapper<TBaseType>
where TBaseType : class
{
protected readonly TBaseType BaseItem;
protected BaseWrapper(TBaseType value)
{
BaseItem = value;
}
public bool IsNotNull()
{
return BaseItem != null;
}
}
``` | What is the correct way to write a constructor for a wrapper class? | [
"",
"c#",
"wrapper",
""
] |
In C++ it's possible to use a logical operator where a biwise operator was intended:
```
int unmasked = getUnmasked(); //some wide value
int masked = unmasked & 0xFF; // izolate lowest 8 bits
```
the second statement could be easily mistyped:
```
int masked = unmasked && 0xFF; //&& used instead of &
```
This will cause incorrect behaviour - `masked` will now be either 0 or 1 when it is inteded to be from 0 to 255. And C++ will not ever complain.
Is is possible to design code in such a way that such errors are detected at compiler level? | Ban in your coding standards the direct use of any bitwise operations in an arbitrary part of the code. Make it mandatory to **call a function** instead.
So instead of:
```
int masked = unmasked & 0xFF; // izolate lowest 8 bits
```
You write:
```
int masked = GetLowestByte(unmasked);
```
As a bonus, you'll get a code base which doesn't have dozens of error prone bitwise operations spread all over it.
Only in one place (the implementation of `GetLowestByte` and its sisters) you'll have the actual bitwise operations. Then you can read these lines two or three times to see if you blew it. Even better, you can unit test that part. | This is a bit [Captain Obvious](http://uncyclopedia.wikia.com/wiki/Captain_Obvious), but you could of course apply [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(computer_science)) and just hide the bitmask inside a class. Then you can use operator overloading to make sure that the boolean `operator&&()` as you see fit.
I guess that a decent implementation of such a "safe mask" need not be overly expensive performance-wise, either. | Prevent misuse of logical operator instead of bitwise operators | [
"",
"c++",
"bit-manipulation",
"operators",
""
] |
How can I transfer an array from an IFrame running a php script, to the parent PHP of the IFrame?
I have an Array of strings in PHP that need to be transferred to the main window so that when the iframe changes pages, the array is still stored.
I could use a cookie for this, though I'm not sure that would be the best idea.
Thanks. | Like [Tim Hoolihan](https://stackoverflow.com/questions/958761/send-a-variable-to-an-iframes-parent-in-php#958788) said, PHP is a server side language that is only responsible for generating the HTML *before* it is sent to the browser. Meaning once the page shows up in your browser window, PHP has done it's part.
However, with that said, if you control both the "parent" page and the page being iframed, you can [`json_encode`](http://php.net/json_encode) the array in the page being iframed and set it to Javascript variable, then on load pass it to a Javascript function on the parent page (assuming not violating any browser/domain sandbox constraints). At that point you can do whatever you want with it.
Take a look at [`jQuery`](http://jquery.com/) for your core Javascript/Ajax needs. | you can't do that in php. iframe is like a new browser window, so they are separate requests. separate requests can not transfer data between each other in a **server side** language.
if you give some detail as to what you're trying to accomplish, there may be another way around the issue that someone can suggest. | Send a Variable to an IFrame's Parent in PHP? | [
"",
"php",
"iframe",
""
] |
I have daily scheduled task that queries a table which includes column named AttemptDate with datetime as datatype. However the task queries all entries regardless of the date. So when the tasks executes, it outputs entries of all the dates as shown below:
```
2009-06-06 06:01:30.852
2009-06-07 01:41:46.719
2009-06-08 03:58:23.945
```
The SQL query is shown below:
```
SELECT AttemptDate from dbo.ChangeAttempt
```
The table dbo.ChangeAttempt has the following structure:
```
Column Data Type Constraints
------ --------- -----------
EventData xml NOT NULL
AttemptDate datetime NOT NULL DEFAULT GETDATE()
DBUser char(50) NOT NULL
```
My question is: From my existing TSQL query, how do I get entries of the current date part if I add where clause?
What I mean by current date here is the date the TSQL query is scheduled to run.
ADDITION:
The SQL Server version I am running the TSQL query against is 2005. | ```
SELECT AttemptDate
FROM dbo.ChangeAttempt
WHERE AttemptDate >= cast(floor(cast(getdate() as float)) as datetime)
``` | ```
SELECT AttemptDate
FROM dbo.ChangeAttempt
WHERE DATEDIFF(d, AttemptDate, GetDate()) = 0
``` | How to get entries of current date portion from column with datetime as datatype (TSQL) | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
From a design perspective, I wonder why the .NET creators chose System.Object.GetType() instead of a System.Object.Type read-only property.
Is it just a (very minor) design flaw or is there rationale behind there?
Any lights welcome. | If you look at the GetType() declaration in Reflector you'll find this:
```
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
```
What that combination of attribute and extern means is that this method is actually implemented in unmanaged code inside the .NET runtime itself. The GUID question in [this article](http://msdn.microsoft.com/en-us/magazine/cc163896.aspx) goes into further details. They obviously did this for performance reasons after determining that figuring out the Type would be faster if handled at a lower level.
This leads to two reasons not to implement the GetType method as a property. Firstly you can't define properties extern as you can with methods, so it would need to be handled in native .NET code. Secondly even if you could define them as extern, performing an unsafe, unmanaged call from inside a property would definitely break the guidelines for property usage since it's much harder to guarantee that there are no side effects. | The guidelines say that a property should represent a state of the object, it should not be expensive performance wise, and it should not have side effects apart from computing/setting that state. My guess is GetType() does not respect these rules so they made it a method.
GetType() is a slightly expensive operation. If it were a property it would encourage uses like
```
DoStuff(obj.Type);
....
DoStuff(obj.Type);
```
etc.
instead of
```
Type type = obj.GetType();
DoStuff(type);
....
DoStuff(type);
```
and that would be not so optimal. So they made it a method to suggest that it should be called sparingly. | Why is Object.GetType() a method instead of a property? | [
"",
"c#",
".net",
"clr",
""
] |
I'd like to ask your input on what the best practice is for handling null or empty data values when it pertains to data warehousing and SSIS/SSAS.
I have several fact and dimension tables that contain null values in different rows.
Specifics:
**1)** What is the best way to handle null date/times values? Should I make a 'default' row in my time or date dimensions and point SSIS to the default row when there is a null found?
**2)** What is the best way to handle nulls/empty values inside of dimension data. Ex: I have some rows in an 'Accounts' dimensions that have empty (not NULL) values in the Account Name column. Should I convert these empty or null values inside the column to a specific default value?
**3)** Similar to point 1 above - What should I do if I end up with a Facttable row that has no record in one of the dimension columns? Do I need default dimension records for each dimension in case this happens?
**4)** Any suggestion or tips in regards to how to handle these operation in Sql server integration services (SSIS)? Best data flow configurations or best transformation objects to use would be helpful.
Thanks :-) | As the previous answer states there can be many different meanings attached to Null values for a dimension, unknown, not applicable, unknown etc. If it is useful to be able to distinguish between them in your application adding "pseudo" dimension entries can help.
In any case I would avoid having either Null fact foreign keys or dimension fields, having even a single 'unknown' dimension value will help your users define queries that include a catch-all grouping where the data quality isn't 100% (and it never is).
One very simple trick I've been using for this and hasn't bitten me yet is to define my dimensions surrogate keys using int IDENTITY(1,1) in T-sql (start at 1 and increment by 1 per row). Pseudo keys ("Unavailable", "Unassigned", "Not applicable") are defined as negative ints and populated by a stored procedure ran at the beginning of the ETL process.
For example a table created as
```
CREATE TABLE [dbo].[Location]
(
[LocationSK] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Abbreviation] [varchar](4) NOT NULL,
[LocationBK] [int] NOT NULL,
[EffectiveFromDate] [datetime] NOT NULL,
[EffectiveToDate] [datetime] NULL,
[Type1Checksum] [int] NOT NULL,
[Type2Checksum] [int] NOT NULL,
) ON [PRIMARY]
```
And a stored procedure populating the table with
```
Insert Into dbo.Location (LocationSK, Name, Abbreviation, LocationBK,
EffectiveFromDate, Type1Checksum, Type2Checksum)
Values (-1, 'Unknown location', 'Unk', -1, '1900-01-01', 0,0)
```
I have made it a rule to have at least one such pseudo row per dimension which is used in cases where the dimension lookup fails and to build exception reports to track the number of facts which are assigned to such rows. | 1. Either NULL or a reserved id from your date dimension with appropriate meaning. Remember NULL really can have many different meanings, it could be unknown, inapplicable, invalid, etc.
2. I would prefer empty string (and not NULLable), but in the project I'm working on now converts empty string to NULL and allows them in the database. A potential problem to be discussed is that a blank middle initial (no middle name, so middle initial is known to be empty) is different from an unknown middle initial or similar semantics. For money, our model allows NULLs - I have a big problem with this in the facts, since typically, they really should be 0, they are always used as 0 and they always have to be wraped with ISNULL(). But because of the ETL policy of converting empty string to NULL, they were set to NULL - but this was just an artifact of the fixed-width transport file format which had spaces instead of 0 from some source systems.
3. Our fact tables usually have a PK based on all the dimensions, so this wouldn't be allowed - it would be linked to a dummy or unknown dimension
4. In SSIS I made a trim component which trims spaces from the ends of all strings. We typically had to do a lot of date validation and conversion in SSIS, which would have been best in a component. | Handling nulls in Datawarehouse | [
"",
"sql",
"ssis",
"ssas",
"data-warehouse",
""
] |
I'm learning C++ on my own, and I thought a good way to get my hands dirty would be to convert some Java projects into C++, see where I fall down. So I'm working on a polymorphic list implementation. It works fine, except for one strange thing.
The way I print a list is to have the `EmptyList` class return "null" (a string, not a pointer), and `NonEmptyList` returns a string that's their data concatenated with the result of calling `tostring()` on everything else in the list.
I put `tostring()` in a `protected` section (it seemed appropriate), and the compiler complains about this line (`s` is a `stringstream` I'm using to accumulate the string):
```
s << tail->tostring();
```
Here's the error from the compiler:
```
../list.h: In member function 'std::string NonEmptyList::tostring() [with T = int]':
../list.h:95: instantiated from here
../list.h:41: error: 'std::string List::tostring() [with T = int]' is protected
../list.h:62: error: within this context
```
Here's most of `list.h`:
```
template <class T> class List;
template <class T> class EmptyList;
template <class T> class NonEmptyList;
template <typename T>
class List {
public:
friend std::ostream& operator<< (std::ostream& o, List<T>* l){
o << l->tostring();
return o;
}
/* If I don't declare NonEmptyList<T> as a friend, the compiler complains
* that "tostring" is protected when NonEmptyClass tries to call it
* recursively.
*/
//friend class NonEmptyList<T>;
virtual NonEmptyList<T>* insert(T) =0;
virtual List<T>* remove(T) =0;
virtual int size() = 0;
virtual bool contains(T) = 0;
virtual T max() = 0;
virtual ~List<T>() {}
protected:
virtual std::string tostring() =0;
};
template <typename T>
class NonEmptyList: public List<T>{
friend class EmptyString;
T data;
List<T>* tail;
public:
NonEmptyList<T>(T elem);
NonEmptyList<T>* insert(T elem);
List<T>* remove(T elem);
int size() { return 1 + tail->size(); }
bool contains(T);
T max();
protected:
std::string tostring(){
std::stringstream s;
s << data << ",";
/* This fails if List doesn't declare NonEmptyLst a friend */
s << tail->tostring();
return s.str();
}
};
```
So declaring `NonEmptyList` a friend of `List` makes the problem go away, but it seems really strange to have to declare a derived class as a friend of a base class. | Because `tail` is a `List<T>`, the compiler is telling you that you can't access a protected member of another class. Just as in other C-like languages, you can only access protected members in your instance of the base class, not other people's.
Deriving class A from class B does not give class A access to every protected member of class B on all instances that are of type class B or derived from that type.
[This MSDN article on the C++ `protected` keyword](http://msdn.microsoft.com/en-us/library/e761de5s.aspx) may be helpful in clarifying.
### Update
As suggested by [Magnus in his answer](https://stackoverflow.com/questions/977927/why-does-this-derived-class-need-to-be-declared-as-a-friend/977982#977982), in this instance, a simple fix might be to replace the call to `tail->tostring()` with the `<<` operator, which you've implemented for `List<T>` to provide the same behavior as `tostring()`. That way, you wouldn't need the `friend` declaration. | As Jeff said, the toString() method is protected and can't be called from your NonEmptyList class. But you have already provided a std::ostream& operator<< for the List class, so why dont you use it in NonEmptyList?
```
template <typename T>
class NonEmptyList: public List<T>{
// ..
protected:
std::string tostring(){
std::stringstream s;
s << data << ",";
s << tail; // <--- Here :)
return s.str();
}
};
``` | Why does this derived class need to be declared as a friend? | [
"",
"c++",
"inheritance",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.