Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there any way to have a map's placemark call a javascript method on the page that contains the map. For example: Say we have a google map that has pins for our customers. If the sales operator clicks on the pin of CompanyA, could the containing page use javascript to identify that ConpanyA's pin had been clicked. And show a quick report on that companies activities? EDIT: sorry guys, should have mentioned that we wanted to build and load the placemarks via KML
Yes, you can hook up an event to the marker (I use the Marker Manager). ``` GEvent.addListener(marker,'click',function(){..your code..}) ``` See the api doc here: <http://code.google.com/apis/maps/documentation/reference.html#GMarker> (scroll down to the "Events" section).
I did something like that [here](http://www.primrose-house.co.uk/localattractions.php). Feel free to check out the source :)
Any way for a Google Maps placemark to trigger a script in the page that contains an embedded map
[ "", "javascript", "google-maps", "kml", "" ]
It is not really a question because I have already found a solution. It took me a lot of time, that's why I want to explain it here. Msxml is based on COM so it is not really easy to use in C++ even when you have helpful classes to deal with memory allocation issues. But writing a new XML parser would be much more difficult so I wanted to use msxml. **The problem:** I was able to find enough examples on the internet to use msxml with the help of `CComPtr` (smart pointer to avoid having to call Release() for each IXMLDOMNode manually), `CComBSTR` (to convert C++ strings to the COM format for strings) and `CComVariant`. This 3 helpful classes are ATL classes and need an `#include <atlbase.h>`. Problem: Visual Studio 2008 Express (the free version) doesn't include ATL. **Solution:** Use `comutil.h` and `comdef.h`, which include some simple helper classes: * `_bstr_t` replaces more or less `CComBSTR` * `_variant_t` replaces more or less `CComVariant` * `_com_ptr_t` replaces indirectly `CComPtr` through the use of `_COM_SMARTPTR_TYPEDEF` **Small example:** ``` #include <msxml.h> #include <comdef.h> #include <comutil.h> // Define some smart pointers for MSXML _COM_SMARTPTR_TYPEDEF(IXMLDOMDocument, __uuidof(IXMLDOMDocument)); // IXMLDOMDocumentPtr _COM_SMARTPTR_TYPEDEF(IXMLDOMElement, __uuidof(IXMLDOMElement)); // IXMLDOMElementPtr _COM_SMARTPTR_TYPEDEF(IXMLDOMNodeList, __uuidof(IXMLDOMNodeList)); // IXMLDOMNodeListPtr _COM_SMARTPTR_TYPEDEF(IXMLDOMNamedNodeMap, __uuidof(IXMLDOMNamedNodeMap)); // IXMLDOMNamedNodeMapPtr _COM_SMARTPTR_TYPEDEF(IXMLDOMNode, __uuidof(IXMLDOMNode)); // IXMLDOMNodePtr void test_msxml() { // This program will use COM CoInitializeEx(NULL, COINIT_MULTITHREADED); { // Create parser IXMLDOMDocumentPtr pXMLDoc; HRESULT hr = CoCreateInstance(__uuidof (DOMDocument), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc); pXMLDoc->put_validateOnParse(VARIANT_FALSE); pXMLDoc->put_resolveExternals(VARIANT_FALSE); pXMLDoc->put_preserveWhiteSpace(VARIANT_FALSE); // Open file VARIANT_BOOL bLoadOk; std::wstring sfilename = L"testfile.xml"; hr = pXMLDoc->load(_variant_t(sfilename.c_str()), &bLoadOk); // Search for node <testtag> IXMLDOMNodePtr pNode; hr = pXMLDoc->selectSingleNode(_bstr_t(L"testtag"), &pNode); // Read something _bstr_t bstrText; hr = pNode->get_text(bstrText.GetAddress()); std::string sSomething = bstrText; } // I'm finished with COM // (Don't call before all IXMLDOMNodePtr are out of scope) CoUninitialize(); } ```
I'm happy I posted my question although I already had a solution because I got several alternative solutions. Thanks for all your answers. Using another parser such as [eXpat](http://expat.sourceforge.net/) or the maybe smaller (not so powerfull but enough for my needs) [TinyXML](http://www.grinninglizard.com/tinyxml) could actually be a good idea (and make it easier to port the program to another operating system). Using an [`#import`](http://msdn.microsoft.com/en-us/library/8etzzkb6%28VS.80%29.aspx) directive, apparently a Microsoft specific extension to simplify the use of COM, is also interesting and brought me to the following web page [`MSXML in C++ but as elegant as in C#`](http://blogs.microsoft.co.il/blogs/davids/archive/2008/12/24/msxml-in-c-but-as-elegant-as-in-c-part-3.aspx), which explain how to simplify the use of msxml as much as possible.
Maybe try using the `#import` statement. I've used it in a VS6 project I have hanging around, you do something like this (for illustrative purposes only; this worked for me but I don't claim to be error proof): ``` #import "msxml6.dll" ... MSXML2::IXMLDOMDocument2Ptr pdoc; HRESULT hr = pdoc.CreateInstance(__uuidof(MSXML2::DOMDocument60)); if (!SUCCEEDED(hr)) return hr; MSXML2::IXMLDOMDocument2Ptr pschema; HRESULT hr = pschema.CreateInstance(__uuidof(MSXML2::DOMDocument60)); if (!SUCCEEDED(hr)) return hr; pschema->async=VARIANT_FALSE; VARIANT_BOOL b; b = pschema->loadXML(_bstr_t( /* your schema XML here */ )); MSXML2::IXMLDOMSchemaCollection2Ptr pSchemaCache; hr = pSchemaCache.CreateInstance(__uuidof(MSXML2::XMLSchemaCache60)); if (!SUCCEEDED(hr)) return hr; _variant_t vp=pschema.GetInterfacePtr(); pSchemaCache->add(_bstr_t( /* your namespace here */ ),vp); pdoc->async=VARIANT_FALSE; pdoc->schemas = pSchemaCache.GetInterfacePtr(); pdoc->validateOnParse=VARIANT_TRUE; if (how == e_filename) b = pdoc->load(v); else b = pdoc->loadXML(bxmldoc); pXMLError = pdoc->parseError; if (pXMLError->errorCode != 0) return E_FAIL; // an unhelpful return code, sigh.... ```
How to use msxml with Visual Studio 2008 Express (no ATL classes) without becoming crazy?
[ "", "c++", "xml", "visual-studio-2008", "msxml", "" ]
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it? Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please. If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion
To enable code completion, go to Window > Preferences > Pydev > Editor > Code Completion, and check the 'Use Code Completion?' box, as well as the other boxes for what you want to complete on. It seems to take a second to load, the first time it has to complete something. Syntax coloring should just work by default. Right-click on the file in the package explorer, go to 'Open With', and make sure you're opening it with the Python Editor, and not the regular Text Editor. I don't know exactly what you mean by importing external modules. I have my source in a separate directory structure on disk; my PyDev projects contain folders linked to those. Code completion works for that, as well as other modules like 'os'. If you're having troubles, are the modules added to the PyDev's Python search path (not necessarily the same as the regular one)? I took a brief look at Komodo and Wingware a while back, so I can't answer the second part of your question. But ended up going with PyDev. I'm not a big fan of Eclipse, but PyDev works reasonably well for me.
The typical reason that code completion doesn't work under PyDev is that the libraries aren't in the PYTHONPATH. If you go into the Project Properties, and setup PyDev PYTHONPATH preferences to include the places where the code you are trying to complete lives, it will work just fine... Project > Properties > PyDev-PYTHONPAH > click 'Add source folder'
No code completion and syntax highlighting in Pydev
[ "", "python", "ide", "" ]
I have to build a rather large form with many controls. The controls are divided in *basic* controls/settings and *extended* controls/settings. The user can decide if he wants to see only the basic or both basic and extended controls. I've dropped all extended controls onto their own JPanel so that I can easily switch between the two views by showing or hiding this panel. Currently I'm using GroupLayout and what happens is that the controls on different panels are not aligned: ``` Label aaa: Text field Label a: Text field Label aaaaaa: Text field ---------------------------- Label b: Text field Label bbb: Text field Label bb: Text field ``` Unfortunatly I found now way to "synchronize" the layouts of the two panels (except using AbsoluteLayout and fixed control coordinates) * Is there any way to achive this? * Is my whole design flawed? **EDIT:** If it is possible I would like to keep the GroupLayout manager.
As far as I know, no Swing LayoutManager (from JRE or open source) can span several panels. I am currently working on such a feature (which I called "layouts synchronization") for my [DesignGridLayout](https://designgridlayout.dev.java.net/) project, but it is not something easy to implements (I have started about 2 weeks ago and I still don't see exactly if and when I will get to something interesting, but I still have high hope for it;-)) One option you could check would be to add all components to the same panel (with just one GroupLayout then) and hide/show them based on user's selection. Hopefully, GroupLayout will adapt the size to the situation (after calling pack()). If GroupLayout behaves well, then it would just be a matter of calling pack() each time after user changes his selection to show/hide extended fields. Else you would have to manually set the size of your panel every time the user changes his selection.
Probably the easiest (good) way to do it is to add all the components to the main panel. Set the subpanels to non-opaque, and add the also to the main panel. The main panel the needs optimised drawing to be switched off. Another technique is to add a spacer component. To the bottom panel add a component in the same column as the labels which dynamically takes the width component of its various size methods from the top labels. Do the same in reverse to the top panel.
Can a layout manager spawn several JPanels?
[ "", "java", "swing", "netbeans", "netbeans6.5", "layout-manager", "" ]
Does anyone know how to get the IP address in decimal or hex from standard IP address format string ("xxx.xxx.xxx.xxx")? I've tried to use the inet\_addr() function but didn't get the right result. I tested it on "84.52.184.224" the function returned 3770168404 which is not correct (the correct result is 1412741344). Thanks!
The htonl, htons, ntohl, ntohs functions can be used to convert between network and local byte orders.
You have just got the bytes reversed from what you expected - they are in [network byte order](https://en.wikipedia.org/wiki/Endianness#Networking) ``` 3770168404 = 0xE0 B8 34 54 network byte order | | \ / \ / \ / \ / /\ / \ / \ / \ | | 1412741344 = 0x54 34 B8 E0 machine order ``` You could use [ntohl()](http://msdn.microsoft.com/en-us/library/ms740069(VS.85).aspx) convert from network order to machine order.
How to convert standard IP address format string to hex and long?
[ "", "c++", "format", "ip-address", "" ]
The standard System.Windows.Forms.TabControl component draws a border around the TabPages it contains. If you set its Dock to Fill, these borders run up to the edge of the parent control, but they're still there, taking up screen space. In Visual Studio, if you dock two windows in the same place, you get a TabControl-like set of tabs along the bottom, but no borders along the sides. Is it possible to get a TabControl to display its TabPages in this manner, with no wasted screen space at the sides? If possible, I'd like to avoid solutions that involve painting the control myself.
Using the standard .NET tab control, this isn't directly possible. What is the ultimate goal for this? Are you trying to simulate the same type of tabbed-MDI style display as Visual Studio? If that's the case, there are several third-party solutions available - some open source and some commercial. The other responses about using the Anchor property in combination with setting the size so it is just a bit larger than the actual window might work, but I think it might look a bit odd visually. It should work regardless of the theme and accessibility settings, but you may end up having to programmatically set the size to be a few pixels larger than the parent.
1. Remove the height and width attributes from TabControl 2. Set horizontal and vertical alignment to stretch e.g. won't stretch; ``` <TabControl Height="373" Width="609" HorizontalAlignment="Stretch" Name="tabControl1" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch"> ``` e.g. will stretch; ``` <TabControl HorizontalAlignment="Stretch" Name="tabControl1" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch"> ```
How do I get a TabControl to use the full width of its parent?
[ "", "c#", ".net", "winforms", "tabcontrol", "" ]
I am doing a report on the various C++ dictionary implementations (map, dictionary, vectors etc). The results for insertions using a std::map illustrate that that the performance is O(log n). There are also consistent spikes in the performance. I am not 100% sure what's causing this; I think they are caused by memory allocation but I have been unsuccessful in finding any literature / documentation to prove this. Can anyone clear this matter up or point me in the right direction? Cheers.
You are right: it is O(log n) complexity. But this is due to the sorted nature of map (normally binary tree based). Also see <http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html> there is a note on insert. It’s worst case is O(log n) and amortized O(1) if you can hint where to do the insert. Maps are normally based on binary trees and need to be balanced to keep good performance. The load spikes you are observing probably correspond to this balancing process
The empirical approach isn't strictly necessary when it comes to STL. There's no point in experimenting when the standard clearly dictates the minimal complexity of operations such as std::map insertion. I urge you to read the standard so you're aware of the minimal complexity guarantees before continuing with experiments. Of course, there might be bugs in whatever STL implementation you happen to be testing; but the popular STLs are pretty well-debugged creatures and very widely used, so I'd doubt it.
Memory Allocation in std::map
[ "", "c++", "stl", "dictionary", "complexity-theory", "" ]
Is there a way to detect the network speed and bandwidth usage in C#? Even pointers to open-source components are welcome.
Try using the System.Net.NetworkInformation classes. In particular, [`System.Net.NetworkInformation.IPv4InterfaceStatistics`](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipv4interfacestatistics.aspx) ought to have some information along the lines of what you're looking for. Specifically, you can check the `bytesReceived` property, wait a given interval, and then check the `bytesReceived` property again to get an idea of how many bytes/second your connection is processing. To get a good number, though, you should try to download a large block of information from a given source, and check then; that way you should be 'maxing' the connection when you do the test, which should give more helpful numbers.
You should be able to calculate everything you need from the [IPGlobalStatistics](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalstatistics.aspx) class.
Detecting network connection speed and bandwidth usage in C#
[ "", "c#", "networking", "performance", "bandwidth", "detect", "" ]
What are the main components of a PHP application? I've come up with these: 1. Database 2. HTML templates 3. Sessions/Cookies/Authentication 4. User Input ($\_GET or $\_POST or URL segments) Are these the main components or are there any others? The reason I'm asking this is so I can put each 'Object' in its own class without having to worry about how it will be technically feasible. For example, I can have a Post class which allows you to add posts to a blog, without having to worry about how it will fit in with the rest of the system / php language, etc.
This sounds a lot like [this question](https://stackoverflow.com/questions/548399/what-php-application-design-design-patterns-do-you-use). I would strongly recommend that you take a look at Patterns of Enterprise Application Architecture by Martin Fowler. I would also recommend that you search for questions on this site related to the Model or Domain as well as Object Relational Mapping or Database Abstraction. I happen to know that there is a great deal of excellent content particularly in regard to PHP. I see two questions in this question that you've posted. First, what are the general architectural components of a site. Generally you'll have these three in some manifestation: 1. Database and Database Interaction Layer 2. Controller - handles $\_GET and $\_POST (the request) and assigning content to the View and ultimately rendering it. 3. View - should contain only HTML and very basic code such as loops for iterating over collections and variable output. Second question I see is where to place handling of a specific business object in the application. This is where the discussion gets a little more involved because I assume that you need to interact with Posts both as business objects (within the domain) and as rows in a database table. Both of these concerns can be wrapped inside of the same class utilizing a pattern called Active Record which has been popularized by Ruby on Rails. However, depending on the complexity of the application and database involved you may want to consider separating the business logic from the database interaction by creating one Post class that acts as the database interaction layer and another Post class that contains all of the business logic.
I would add a data access layer as a component that provides the interface to the database. There are existing patterns that take care of those types of concerns. And there are frameworks that are built upon those patterns that you might want to take a look at, where much of this work has already been done: [Cake PHP](http://cakephp.org/) [Solar PHP](http://solarphp.com/)
What are the main components/layers of a PHP application?
[ "", "php", "oop", "frameworks", "software-design", "" ]
**Hi All,** I'm thinking in this line of code ``` IDataReader myReader = questDatabase.ExecuteReader(getQuest); ``` I'm using DAAB but I can't understand how and what's the meaning of the fact the method ExecuteReader(DbCommand) returns an IDataReader Interface. **Anyone can Explain, Please**
It allows you to you DataReader without the need of knowing which type of DataReader you are using (i.e. `SqlDataReader, OleDbDataReader, EtcDataReader`), so if someday you want to change the datareader you are using it won't impact you logic, in other words it gives you abstraction. For example : you can use ``` IDbCommand command = GiveMeSomeCommand(); IDataReader r = command.ExecuteReader(); ``` without knowing which provider you are using it can be: ``` private static IDbCommand GiveMeSomeCommand() { return new OleDbCommand(); } ``` or it can be ``` private static IDbCommand GiveMeSomeCommand() { return new SqlCommand(); } ``` or whatever. EDIT: You can also use the DBFactories. ``` DbProviderFactory factory = GiveMeSomeFactory(); IDbCommand command = factory.CreateCommand(); IDataReader r = command.ExecuteReader(); //and create more objects IDataAdapter adapter = factory.CreateDataAdapter(); IDbConnection conn = factory.CreateConnection(); ``` and then create your provider in other layer ``` private DbProviderFactory GiveMeSomeFactory() { if(something) return SqlClientFactory.Instance; else if(somethingElse) return OracleFactory.Instance; else if(notThisAndNotThat) return MySqlFactory.Instance; else return WhateverFactory.Instance; } ```
The method will return an object, which is an instance of a class, and that type of class will support `IDataReader`. The point is, the type of the object isn't important, just the fact that the class implements the interface. If you're driving a car, you don't need to know if it's a ford, or a toyota, you drive the car the same way. The driving *interface* is the same, once the car supports the interface, you can drive it. Ditto with the `IDataReader`, once the class that is returned supports the interface, you can use it.
Method return an interface
[ "", "c#", ".net", "oop", "interface", "" ]
I would like to learn how a program can be written and installed without the use of the .net framework. I'm looking for a project that is known to be lightweight and robust. Something like the uTorrent client.
[chromium](http://code.google.com/chromium/), the open-source project behind [Google Chrome](http://www.google.com/chrome), is chalk full of clean, robust (and unit-tested) code. If you choose to dive in, keep the [map](http://dev.chromium.org/developers/how-tos/getting-around-the-chrome-source-code) handy.
Try [Anki](http://ichi2.net/anki/), a spaced learning tool.
What is the best open source example of a lightweight Windows Application?
[ "", "c++", "c", "windows", "open-source", "" ]
I am using firebug for debugging etc. When I deploy, it seems as though I have to remove all the console.log statements from my javascript code? When viewing on a browser that doesn't have firebug I am getting errors relating to console...
Yes, they will make IE error as IE does not have the console. It's also good practice.
I used [this post](https://stackoverflow.com/questions/398111/javascript-that-detects-firebug) to create a log function. It will avoid those errors. ``` function log(string) { if (window.console && window.console.firebug) { console.log(string); } } ``` It's also easier to type :)
When using firebug, do I have to remove the console outputs when deploying?
[ "", "javascript", "firebug", "" ]
I’m using an API that has an object that returns `IEnumerable<T>`, so something like `Object.GetEnum<T>`. I have a method that within it will call GetEnum but I want to add to the method’s parameters the ability to pass the parameter type. So for example I want to do: ``` private void myMethod(apiClass??? apiclass) { IEnumerable< itemType > enumX = ObjectGetEnum< itemType > } private void Main() { myMethod(apiClass1); myMethod(apiClass2); } ``` So as above I don’t know what the parameter type should be in myMethod or how to write the code that gets the enumerator. I tried passing “apiClass”, the class which apiClass1 and apiClass2 inherit from. But then got stuck there on what to do…and I don’t think that really work anyways. So I’m not sure if I just don’t know how in C# to do this, or if it is even possible, …. or perhaps I’m missing something in the API (or the API is missing something to facilitate this). Thanks FKC
Okay, I'm going to take a stab at this, although I'd like the question to be clarified. I suspect you just need to make the method generic: ``` private void MyMethod<TItem>() where TItem : ApiClass { IEnumerable<TItem> enumX = ObjectGetEnum<TItem>(); } private static void Main() { MyMethod<ApiClass1>(); MyMethod<ApiClass2>(); } ```
Are you trying to access the type parameter of the closed constructed type inside a method? Maybe something like this will work: ``` using System; class Foo<T> { } class Program { static void Main() { myMethod(new Foo<String>()); } private static void myMethod<T>(Foo<T> foo) { // use the T parameter in here } } ```
Passing in <T> to a method where GetEnum<T> is called
[ "", "c#", "ienumerable", "" ]
I'm developing an app for windows mobile (Compact Framework 2.0). It has a WinForms with a PictureBox. I want to move the image of the PictureBox but I don't know how to do it so I choose to move the hole PictureBox. To do it I use this event: ``` private void imagenMapa_MouseMove(object sender, MouseEventArgs e) { imagenMapa.Left = e.X; imagenMapa.Top = e.Y; this.Refresh(); } ``` But when I move the PictureBox it blinks and moves every where. What I'm doing wrong?
The `e.X` and `e.Y` are relative to the picture box (e.g. if the mouse is in the upper left of the picture box, that's 0,0) . The values for `imagenMapa.Left` and `imagenMapa.Top` are relative to the form (or whatever control contains `imagenMapa`) If you try to mix values from these two systems without conversion, you're going to get jumps (like you're seeing). You're probably better off converting the mouse position to the same coordinate system used by the thing that contains the picture box. You could use [`imagenMapa.PointToScreen`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoscreen.aspx) to get the mouse coordinates in screen coordinates (or [`Cursor.Position`](http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx) to get the position directly), and [`yourForm.PointToClient`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoclient.aspx) to get them back in the form coordinates. Note that depending on your needs, you could accomplish "moving an image within a control" by overriding/handling the [`Paint` event](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.paint.aspx) of a control and drawing the image yourself. If you did this, you could keep everything in the picturebox coordinates, since those are likely what you would use when you called [`graphicsObject.DrawImage`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawimage.aspx).
Actual Code (Requires .NET Framework 3.5 and beyond, not sure if this is available in the Compact Framework)... ``` // Global Variables private int _xPos; private int _yPos; private bool _dragging; // Register mouse events pictureBox.MouseUp += (sender, args) => { var c = sender as PictureBox; if (null == c) return; _dragging = false; }; pictureBox.MouseDown += (sender, args) => { if (args.Button != MouseButtons.Left) return; _dragging = true; _xPos = args.X; _yPos = args.Y; }; pictureBox.MouseMove += (sender, args) => { var c = sender as PictureBox; if (!_dragging || null == c) return; c.Top = args.Y + c.Top - _yPos; c.Left = args.X + c.Left - _xPos; }; ```
Move a PictureBox with mouse
[ "", "c#", "winforms", "picturebox", "onmousemove", "" ]
My C# is a bit rusty and I've never written XML with it before. I'm having trouble getting the XML to write to a file if I attempt to write anything other than elements. Here is the test code that I have: ``` var guiPath = txtGuiPath.Text; MessageBox.Show("Dumping File: " + guiPath); try { var writer = new XmlTextWriter("client_settings.xml", null); writer.WriteStartDocument(); writer.WriteComment("Config generated on 01/01/01"); writer.WriteStartElement("Config"); writer.WriteStartElement("GuiPath"); writer.WriteString(guiPath); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MessageBox.Show("Finished Dumping"); ``` If guiPath is blank I get the following XML: ``` <?xml version="1.0"?> <!--Config generated on 01/01/01--> <Config> <GuiPath /> </Config> ``` but if there is any text inside guiPath then nothing gets written to the file. I can even delete the client\_settings.xml file and fire this code off over and over and the XML file never gets generated unless guiPath is empty. Passing something like "This is a test" to WriteString() works as well. **Update** Since I'm trying to write out a system path, that seems to be the problem. If I strip out all the backslashes it will write the resulting string correctly, but if I pass it to WriteString or WriteCData the XML will not write at all. **Update 2** Turns out that the reason I was having so many problems is because the XML file was being generated in whatever path guiPath was set to, not into the directory that the app was running from (so to me it looked like it wasn't being generated at all). So, if I had guiPath set to 'C:\Program Files\externalApp\appName.exe', it was saving the XML file as 'C:\ProgramFiles\externalApp\client\_settings.xml' instead of in the startup folder for the app. Why, I don't know. I started passing Application.StartupPath and appended the filename to that and it works great now. Thanks for all the help!
You might want to examine the API in System.Xml.Linq. It's a bit of a more flexible approach to generating and writing XML. Writing your document might go roughly like this: ``` XDocument document = new XDocument(); document.Add(new XComment("Config generated on 01/01/01")); document.Add(new XElement("Config", new XElement("GuiPath", guiPath))); // var xmlWriter = new XmlTextWriter("client_settings.xml", null); // document.WriteTo(xmlWriter); // thanks to Barry Kelly for pointing out XDocument.Save() document.Save("client_settings.xml"); ```
Why not create a simple class to hold all the data you need and then serialize it using XmlSerializer, rather than manually generating it line by line? You can even use the attributes in System.Xml.Serialization to control the output if you need: ``` using System; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; namespace Foo { [XmlRoot(ElementName = "Config")] public class Config { public String GuiPath { get; set; } public Boolean Save(String path) { using (var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { try { var serializer = new XmlSerializer(typeof(Config)); serializer.Serialize(fileStream, this); return true; } catch(Exception ex) { MessageBox.Show(ex.Message); // Other exception handling here return false; } } } public static Config Load(String path) { using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read)) { try { var serializer = new XmlSerializer(typeof(Config)); return (Config)serializer.Deserialize(fileStream); } catch(Exception ex) { MessageBox.Show(ex.Message); // Other exception handling here return null; } } } } } ``` This way you don't have to worry about manually encoding strings if they have odd characters - the serializer will do that for you. This also has the added benefit of being able to be serialized back into the class so you can have strongly typed access to the structure, if you ever need to do that.
Writing XML with C#
[ "", "c#", "xml", "file-io", "" ]
I have two Microsoft SQL Server 2000 databases, and a stored procedure on one tries to read data from the other. This used to work fine, but since I became security-conscious and changed the login (SQL user) from "db owner" to "denydatareader" the call fails. I can get things working if I use the group "datareader", but since I do not want this login to have read access to user tables (the ASPs use only procs), I thought this unwise. It also works if I take the user out of all groups!!! Is this OK? --- One database is called 'Internal' and has a table called 'Stuff'. The other is called 'WebFacing' and has a stored procedure called 'Get\_Some\_Data' which SELECTs from 'Internal..Stuff'. I ran this command on the Internal database: `GRANT SELECT ON Stuff TO magnus` I ran this one on the WebFacing database: `GRANT EXECUTE ON Get_Some_Data TO magnus` My ASP uses the SQL login 'magnus' and connects to the 'WebFacing' database. When it tries to EXEC the procedure, it errors with: `SELECT permission denied on object 'Stuff', database 'Internal', owner 'dbo'.` --- (Apologies if this is a dumb question, but I've been shoved in the deep end and only learnt about GRANT and DENY yesterday. I have tried Googling...)
Associating SQL logins with groups/roles (or not) is more a function of convenience for the person who has to keep track of permissions for the database(s). Since you're new to all this, I would first focus on getting the permissions of the particular login correct prior to worrying about managing permissions via groups/roles. One of the things that gave me fits when I first started working with SQL Server permissions was understanding whether the permissions used for the execution of a stored procedure were those of the SQL login used to call the proc, or the SQL login associated with the creation of the proc itself. The term for that (which set of credentials and associated permissions is used for the execution of proc code) is called the "security context" under which the stored proc runs. I've been working with MySQL recently, but if I remember correctly, the default security context used to execute a stored procedure on SQL Server is that of the CALLER rather than the proc owner. This always struck me as counterintuitive, because it seemed to me that one of the key advantages to using stored procedures should be the ability to grant only EXEC permissions on specific procs to CALLER logins. But when I tried to do it that way, I'd inevitably get permissions errors because the credentials I was using to call the proc wouldn't have the permissions needed to complete one or more of the operations contained within the stored procedure. If you're using SQL Server 2005 and want to be able to grant only EXEC permissions to CALLER credentials, then [this](http://www.mssqltips.com/tip.asp?tip=1579) article may help shed some light on how to do so. In my opinion, that's the "correct" way to do things, though I'm sure there are probably others who might disagree (though I'd probably stick to my argument on this point). Anyway, I'm not sure how much I've clarified the issue for you with this post. SQL Server permissions management is indeed a bit of a deep end when you first delve into the whole issue. It's not making it any easier that you're having to deal with setting them up accross multiple databases.
You can enable Croos-Database ownership, without having to give select permissions on the table that your sproc is calling. But use at your own risk. I use it for the scenraio you are describing: alter database dbname set db\_chaining on
Why can't a stored procedure read a table from another database (I must be using GRANT and DENY wrongly)
[ "", "sql", "stored-procedures", "database-permissions", "" ]
When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible. Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate **all** objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists?
Here's four variants: * an incremental list creation * "pre-allocated" list * array.array() * numpy.zeros() ``` python -mtimeit -s"N=10**6" "a = []; app = a.append;"\ "for i in xrange(N): app(i);" 10 loops, best of 3: 390 msec per loop python -mtimeit -s"N=10**6" "a = [None]*N; app = a.append;"\ "for i in xrange(N): a[i] = i" 10 loops, best of 3: 245 msec per loop python -mtimeit -s"from array import array; N=10**6" "a = array('i', [0]*N)"\ "for i in xrange(N):" " a[i] = i" 10 loops, best of 3: 541 msec per loop python -mtimeit -s"from numpy import zeros; N=10**6" "a = zeros(N,dtype='i')"\ "for i in xrange(N):" " a[i] = i" 10 loops, best of 3: 353 msec per loop ``` It shows that `[None]*N` is the fastest and `array.array` is the slowest in this case.
you can create list of the known length like this: ``` >>> [None] * known_number ```
Reserve memory for list in Python?
[ "", "python", "performance", "arrays", "memory-management", "list", "" ]
Using .net MVC and I am doing some server side validation in my Action that handles the form post. What is a good technique to pass the errors back to the view? I am thinking of creating an error collection, then adding that collection to my ViewData and then somehow weave some javascript (using jQuery) to display the error. It would be nice it jQuery had some automagic way of display an error since this is a common pattern. What do you do?
You want to add the errors to the ModelState as @Mehrdad indicates. ``` ... catch (ArgumentOutOfRangeException e) { ModelState.AddModelError( e.ParamName, e.Message ); result = View( "New" ); } ``` And include the ValidationSummary in your View ``` <%= Html.ValidationSummary() %> ```
`ViewData.ModelState` is designed to pass state information (errors) from the controller to the view.
server side validation, how to pass errors to view in MVC?
[ "", "javascript", "asp.net-mvc", "error-handling", "" ]
Is there a way in Java to programmatically import a class given its full name as a String (i.e. like `"com.mydummypackage.MyClass"`)?
If by "import" you mean "load a `Class` object so you can run reflection methods," then use: ``` Class<?> clazz = Class.forName( "com.mypackage.MyClass" ); ``` (The reason we readers were confused by your word "import" is that typically this refers to the `import` keyword used near the top of Java class files to tell the compiler how to expand class names, e.g. `import java.util.*;`).
The Java Documentation is a great source of knowledge for stuff like this, I suggest you read up on the Class Object Documentation which can be found here: <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html> As mentioned in Jason Cohen's answer you can load a Class object using the following line of code and then to create an instance of that class you would execute the newInstance method of the Class object like so: ``` Class<?> clazz = Class.forName( "com.mypackage.MyClass" ); Object o = clazz.newInstance(); ```
How to programmatically import Java class
[ "", "java", "reflection", "" ]
As part of my Personal Improvement Program (PIP™), I'm trying to learn the basics of Windows Workflow Foundation. I decided to write a fairly simple blogging engine. I know there are tonnes out there, but this is just a playground project I can use for learning some cool stuff. One of the main features I wanted to implement is the moderation of blog entries using WF. The rest of the project is going to be an ASP.NET MVC app, possibly sprinkled with a little WCF. From what I've read about WF, I should be using a sequential workflow that should look something like this: 1. Author adds/ edits blog entry. 2. Entry gets sent to moderator for approval. 3. Moderator approves post -- or -- back to item 1. for author to correct, along with moderator notes. 4. Finish Every step should also e-mail the receiptiant of the action. Because of the human interaction factor, I'm guessing the WF runtime would need to serialise itself somewhere so it doesn't loose state (as each activity could be interrupted by AppPool resets, server crashes etc). Does anyone know of any good examples or places that implement a similar workflow? Thanks all.
I would hold off on delving into WW for the time being. .NET 4.0 is going to introduce changes to the model of WW to address current pain points. These changes will introduce a model that is fundamentally different from WW today, and learning the current methodologies for WW will not be as helpful if you don't already have a WW solution in place. More information can be found here: <http://blogs.msdn.com/endpoint/archive/2009/01/20/the-road-to-wf-4-0-part-1.aspx>
You're on the right track. Windows Workflow provides a persistence model that allows you to save the state of a running workflow instance to a SQL Server. When a running instance is paused (usually while waiting for input from outside the workflow) the state is automatically serialized to the database. [Here](http://www.microsoft.com/downloads/details.aspx?FamilyID=a438a9b9-9f15-42ec-866f-2ea58e10db36&DisplayLang=en) is a starter kit from Microsoft for web-based approval workflows.
Windows Workflow Foundation example - moderation
[ "", "c#", "workflow", "workflow-foundation", "" ]
I'm writing a photo gallery script in PHP and have a single directory where the user will store their pictures. I'm attempting to set up page caching and have the cache refresh only if the contents of the directory has changed. I thought I could do this by caching the last modified time of the directory using the filemtime() function and compare it to the current modified time of the directory. However, as I've come to realize, the directory modified time does not change as files are added or removed from that directory (at least on Windows, not sure about Linux machines yet). So my questions is, what is the simplest way to check if the contents of a directory have been modified?
Uh. I'd simply store the md5 of a directory listing. If the contents change, the md5(directory-listing) will change. You *might* get the very occasional md5 clash, but I think that chance is tiny enough.. Alternatively, you could store a little file in that directory that contains the "last modified" date. But I'd go with md5. --- PS. on second thought, seeing as how you're looking at performance (caching) requesting and hashing the directory listing might not be entirely optimal..
As already mentioned by others, a better way to solve this would be to trigger a function when particular events happen, that changes the folder. However, if your server is a unix, you can use `inotifywait` to watch the directory, and then invoke a PHP script. Here's a simple example: ``` #!/bin/sh inotifywait --recursive --monitor --quiet --event modify,create,delete,move --format '%f' /path/to/directory/to/watch | while read FILE ; do php /path/to/trigger.php $FILE done ``` See also: <http://linux.die.net/man/1/inotifywait>
How to check if directory contents has changed with PHP?
[ "", "php", "directory", "last-modified", "filemtime", "" ]
One of the first things I've learned about Java EE development is that I shouldn't spawn my own threads inside a Java EE container. But when I come to think about it, I don't know the reason. Can you clearly explain why it is discouraged? I am sure most enterprise applications need some kind of asynchronous jobs like mail daemons, idle sessions, cleanup jobs, etc. So, if indeed one shouldn't spawn threads, what is the correct way to do it when needed?
It is discouraged because all resources within the environment are meant to be managed, and potentially monitored, by the server. Also, much of the context in which a thread is being used is typically attached to the thread of execution itself. If you simply start your own thread (which I believe some servers will not even allow), it cannot access other resources. What this means, is that you cannot get an InitialContext and do JNDI lookups to access other system resources such as JMS Connection Factories and Datasources. There are ways to do this "correctly", but it is dependent on the platform being used. [The commonj WorkManager is common for WebSphere and WebLogic as well as others](http://web.archive.org/web/20120510185357/http://www.ibm.com/developerworks/library/specification/j-commonj-sdowmt/index.html) [More info here](http://www.theserverside.com/discussions/thread.tss?thread_id=44353) [And here](http://docs.oracle.com/middleware/1212/wls/WLPRG/topics.htm#sthref219) Also somewhat duplicates [this one](https://stackoverflow.com/questions/532360/thread-in-app-server/532440#532440) from this morning UPDATE: Please note that this question and answer relate to the state of Java EE in 2009, things have improved since then!
For EJBs, it's not only discouraged, it's expressly forbidden by the [specification](http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html): > An enterprise bean must not use thread > synchronization primitives to > synchronize execution of multiple > instances. and > The enterprise bean must not attempt > to manage threads. The enterprise > bean must not attempt to start, stop, > suspend, or resume a thread, or to > change a thread’s priority or name. > The enterprise bean must not attempt > to manage thread groups. The reason is that EJBs are meant to operate in a distributed environment. An EJB might be moved from one machine in a cluster to another. Threads (and sockets and other restricted facilities) are a significant barrier to this portability.
Why is spawning threads in Java EE container discouraged?
[ "", "java", "multithreading", "jakarta-ee", "" ]
I'm new to Dojo, so I need a little help. Some of my links takes a while (when the user clicks, it takes several seconds before the page starts loading), and I'd like to add a "loading"-message. I can do it the "old fashion way", but I want to learn the new, easier, smarter Dojo-way. Exactly how it works is not important right now, but I imagine something like this: A rectangle appears in the middle of the browser-windows. (Not the middle of the document.) It has an animated gif, and a message like "Please wait...". All other elements are disabled, maybe "faded out" a bit. Maybe a big white 50% transparent rectangle, which sits between the "loading"-message and the rest of the document.
What you are describing assumes that dojo itself has already been loaded by the time that the modal `dijit.Dialog` appears with the loading message. Now, normally, dojo starts executing once your page is fully loaded, and you would normally put your dojo code inside an anonymous function passed as parameter of `dojo.addOnLoad()`. That entails that the remaining part of your page (what you call your "links") will have to be loaded through ajax (using, for instance, `dijit.layout.ContentPane`). That way, dojo can execute before the content is downloaded, and your "waiting" message can appear earlier. It might look like this: ``` <html> <head> <link rel="stylesheet" href="/dojo/dijit/themes/tundra/tundra.css" type="text/css" media="screen" /> <script type="text/javascript" src="/dojo/dojo.js" djConfig="parseOnLoad:true"></script> /* make sure that you shrinksafe together your libraries and dojo's for faster loading... */ <script type="text/javascript" src="/dojo/yourOwnDojoCompressedScripts.js"></script> <script type="text/javascript"> var dialog; dojo.addOnLoad(function(){ dojo.require("dijit.layout.ContentPane"); dojo.require("dijit.Dialog"); dialog = new dijit.Dialog(); dialog.setContent("<p>This page will be available in a tick!</p>"); dialog.show(); }); </script> </head> <body class="tundra"> <div id="delayedContent" dojoType="dijit.layout.ContentPane" href="/myContentUrl" onLoad="dialog.hide()"> </div> </body> </html> ``` The only flaw in that plan is dojo itself: expect your *shrinksafed* library to weigh over 90K (possibly up to 300K, depending on how much stuff you put in there). On a slow connection, that still takes a noticeable amount of time to download. That said, we're talking of a *static* 90K --- the same user will download it only once per session, and even less often than that if you take the time to set appropriate cache/expire headers when those static files are served.
Dojo has one such a component already: [Dojox Busy Button](http://download.dojotoolkit.org/release-1.2.3/dojo-release-1.2.3/dojox/form/tests/test_BusyButton.html). You might be also interested in the following articles by Sitepen: [Dojo: Building Blocks of the Web](http://www.sitepen.com/blog/2008/10/17/dojo-building-blocks-of-the-web/) (demonstrates blocking the page content) and [Implementing a Web Application Preloading Overlay](http://www.sitepen.com/blog/2008/10/06/implementing-a-web-application-preloading-overlay/).
Dojo "loading"-message
[ "", "javascript", "ajax", "modal-dialog", "dojo", "" ]
I have some functions here that for example are defined as ``` private int WriteLogikParameterTyp(FileStream filestream) ``` which i can not change. I want them to write into a MemoryStream Object. Is this possible?
No. FileStream is a concrete implementation. But it's a private method so should be easy enough to change since you can find all internal uses? Suggest replacing method signature with Stream rather than FileStream. Well... unless you create a tempory file, write to it then read it into memory.
Since you can't change the function signature to accept a more generic type.. I'd suggest writing out to a temporary file and then reading the contents into a MemoryStream instance.
Use a MemoryStream with a function that expects a Filestream
[ "", "c#", ".net", "filestream", "memorystream", "" ]
I have to know what key is pressed, but not need the code of the Character, i want to know when someone press the 'A' key even if the key obtained is 'a' or 'A', and so with all other keys. I can't use PyGame or any other library (including Tkinter). Only Python Standard Library. And this have to be done in a terminal, not a graphical interface. NOT NEED THE CHARACTER CODE. I NEED TO KNOW THE KEY CODE. Ex: ``` ord('a') != ord('A') # 97 != 65 someFunction('a') == someFunction('A') # a_code == A_code ```
See [tty](http://docs.python.org/library/tty.html) standard module. It allows switching from default line-oriented (cooked) mode into char-oriented (cbreak) mode with [tty.setcbreak(sys.stdin)](http://docs.python.org/library/tty.html#tty.setcbreak). Reading single char from sys.stdin will result into next pressed keyboard key (if it generates code): ``` import sys import tty tty.setcbreak(sys.stdin) while True: print ord(sys.stdin.read(1)) ``` *Note: solution is Unix (including Linux) only.* Edit: On Windows try [msvcrt.getche()](http://docs.python.org/library/msvcrt.html#msvcrt.getche)/[getwche()](http://docs.python.org/library/msvcrt.html#msvcrt.getwche). /me has nowhere to try... --- Edit 2: Utilize win32 low-level console API via [ctypes.windll](http://docs.python.org/library/ctypes.html) (see [example at SO](https://stackoverflow.com/questions/239020/how-can-i-call-a-dll-from-a-scripting-language)) with `ReadConsoleInput` function. You should filter out keypresses - `e.EventType==KEY_EVENT` and look for `e.Event.KeyEvent.wVirtualKeyCode` value. Example of application (not in Python, just to get an idea) can be found at <http://www.benryves.com/tutorials/?t=winconsole&c=4>.
Depending on what you are trying to accomplish, perhaps using a library such as [pygame](http://pygame.org) would do what you want. Pygame contains more advanced keypress handling than is normally available with Python's standard libraries.
How to obtain the keycodes in Python
[ "", "python", "input", "keycode", "" ]
So I have a PropertyBag class that is intended to implement INotifyPropertyChanged. In order to make this code work as cleanly as possible and to avoid user error, I am using the stack to get the property name. See, if the property name doesn't match the actual property exactly, then you will have a failure and I am trying to protect from that. So, here is an example usage of the class: ``` public class MyData : PropertyBag { public MyData() { Foo = -1; } public int Foo { get { return GetProperty<int>(); } set { SetProperty(value); } } } ``` The important code for the base PropertyBag is here: ``` public abstract class PropertyBag : INotifyPropertyChanged { protected T GetProperty<T>() { string propertyName = PropertyName((new StackTrace()).GetFrame(1)); if (propertyName == null) throw new ArgumentException("GetProperty must be called from a property"); return GetValue<T>(propertyName); } protected void SetProperty<T>(T value) { string propertyName = PropertyName((new StackTrace()).GetFrame(1)); if (propertyName == null) throw new ArgumentException("SetProperty must be called from a property"); SetValue(propertyName, value); } private static string PropertyName(StackFrame frame) { if (frame == null) return null; if (!frame.GetMethod().Name.StartsWith("get_") && !frame.GetMethod().Name.StartsWith("set_")) return null; return frame.GetMethod().Name.Substring(4); } } ``` So now that you have seen my code, I can tell you the problem... In some cases under release build, the "Foo" setter in the "MyData" constructor appears to be getting optimized to inline as SetProperty(-1). Unfortunately, this inline optimization fails out my SetProperty method because I am no longer calling it from a property! FAIL. It appears that I cannot rely on the StackTrace in this way. Can anyone A: Figure out a better way to do this but still avoid passing in "Foo" to GetProperty and SetProperty? B: Figure out a way to tell the compiler to not optimize in this case?
Using the stack here is slow and unnecessary; I would simply use: ``` get { return GetProperty<int>("Foo"); } set { SetProperty("Foo", value); } ``` (hint: I've done a lot of work with custom property models; I know that this works well...) Another alternative is an object key (use reference equality to compare) - a lot of `ComponentModel` works this way, as do some of the properties in WF/WPF: ``` static readonly object FooKey = new object(); ... get { return GetProperty<int>(FooKey); } set { SetProperty(FooKey, value); } ``` Of course, you could declare a type for the keys (with a `Name` property), and use that: ``` static readonly PropertyKey FooKey = new PropertyKey("Foo"); ``` etc; however, to answer the question: mark it (but **don't** do this) with: ``` [MethodImpl(MethodImplOptions.NoInlining)] ``` or ``` [MethodImpl(MethodImplOptions.NoOptimization)] ``` ~~or~~ ``` [MethodImpl(MethodImplAttributes.NoOptimization | MethodImplAttributes.NoInlining)] ```
Using the stack is not a good idea. You are relying on internal implementation of the compiler to artificially tie in your property bag to the language properties. 1. having a requirement to add the `MethodImpl` attribute makes the use of your property bag non-transparent for other developers. 2. even if the property bag has the `MethodImpl` attribute, nothing guarantees you it will be the first frame on the call stack. It is possible that the assembly was instrumented or modified to inject calls between the actual property and the call to your property bag. (Think aspect programming) 3. New languages or even a future version of the C# compiler might decorate the property accessors in a different way then `'_get'` and `'_set'` 4. Constructing the call stack is relatively slow operation, as it requires the internal compressed stack to be decompressed and the name of each type and method to be obtained using reflection. You should really just implement your property bag accessors to take a parameter to identify the property - either a string name (like Hastable) or an object (like the WPF dependency property bag)
Any way to avoid Property inline optimization in C#?
[ "", "c#", "stack-trace", "" ]
I'm running a cronjob which needs to write data to a cache. I wanted to put this cronjob in my private folder, however, even after CHMODding the cache folder in the private folder, it's not getting writing rights. This seems to be somekind of plesk feature. So, now I've placed the cronjob in the public folder. However, I need to make sure that only the server can execute the script. What about the following at the top of the cronjob? ``` if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) die(); ``` This seems to work. Is it not exploitable however, eg. can a user manipulate his remote\_addr to my server's? Or is there a better way to check this? Another issue I have is that the above code is returning 2 warnings, even though it does seem to work: ``` PHP Notice: Undefined index: SERVER_ADDR in ... on line 2 PHP Notice: Undefined index: REMOTE_ADDR in ... on line 2 ``` Any idea what's the cause of that?
Execute the script via the console, not the web server. The cron could look like this: ``` */5 * * * * php -f /path/to/cron.php ``` Then the file could do this: ``` cron.php: <?php if ( array_key_exists('REMOTE_ADDR', $_SERVER) ) die("Can only be run from the command line!"); ``` That will guarantee it's only run by the server. **Edit in response to comments** You can't get to a public folder inside a private folder, in general, and if you can't add new directories outside the web root, your cache dir will have to be protected another way. I'm going to assume all your files are in the web root, ie: `/home/site/publichtml`. Replace that with whatever your directory is. Create a new directory `/home/site/publichtml/.cache`. Add the following as a .htaccess file: ``` Deny from all ``` Now your scripts should be able to access the folder from the file system, but it's inaccessible via the web server. If you can set up a cron job on the server (via the web admin or another way, it sounds like you can) do it as above, ie: Use `php -f /home/site/publichtml/cron.php` as the command, and include the check for the array key. Alternatively, you can check like this: ``` if ( !isset($_SERVER['argc']) ) die("Must be run from the command line!\n"); ``` `$_SERVER['argc']` is only set when the script is executed from the command line. If you can keep the cron script out of the web root, good. If not, that should be secure. Finally, to get rid of the E\_NOTICES, add this to the top of the cron.php: ``` error_reporting(E_ALL ^ E_NOTICE); // Turn off notices ``` or ``` error_reporting(0); // Hide all error reporting ```
First, I would keep the executable PHP script in a private directory that can only be executed by the privileged user - and schedule it in the cron for that user. You should have no problems executing the script. Second, you can change where you are writing the cache data to a public directory. It would be preferable to keep this in a non-public directory, but if you cannot figure out how to do it otherwise, and the data is okay to be public, then it is probably okay. Finally, using $\_SERVER['SERVER\_ADDR'] and $\_SERVER['REMOTE\_ADDR'] is probably not the best way to check to see if the server is running the script. For one, I believe that $\_SERVER['REMOTE\_ADDR'] will not be set when running a command-line PHP script. This is taken from the HTTP headers, and since there are none, it will be empty. In fact, this is why you are getting the warnings - these are not set. (edit: looking at the PHP docs, it is likely that the 'SERVER\_ADDR' variable will not be set for non-browser scripts)
How do you check if the server is executing the PHP script?
[ "", "php", "" ]
I'm using JScript.NET to write scripts in a C# WinForms application I wrote. It works really well, but I just tried putting some exception handling in a script, and I can't figure out how to tell what type of exception was thrown from my C# code. Here's some example JScript code that throws two different types of CLR exception, and then tries to catch them and tell them apart. ``` function ErrorTest(name) { try { if (name.length < 5) { throw new ArgumentException(); }else { throw new InvalidOperationException(); } }catch (e) { return e.name + " " + (e.number & 0xFFFF) + ": " + e.message; } } ``` If I call `ErrorTest("foo")`, then I get back `"Error 5022: Value does not fall within the expected range."`, and if I call `ErrorTest("foobar")`, then I get back `"Error 5022: Operation is not valid due to the current state of the object."` The name and number properties are identical, the only difference is the message. I don't want to start writing error handling logic based on the error messages, so is there some way to get at the original exception instead of the JScript `Error` object?
Use JScript .NET's type annotation support, like so: ``` try { } catch (e : ArgumentException) { // ... } ```
You can get the original exception using the [ErrorObject.ToException method](http://msdn.microsoft.com/en-us/library/microsoft.jscript.errorobject.toexception.aspx), and then use `instanceof` to decide how to handle it. This works, but I haven't decided whether to use it. I think it's abusing the framework, because the documentation says: > This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. Also, you'll have to add a reference to the Microsoft.JScript assembly and import the Microsoft.JScript namespace. Here's the new code: ``` function ErrorTest(name) { try { if (name.length < 5) { throw new ArgumentException(); }else { throw new InvalidOperationException(); } }catch (e) { var ex = ErrorObject.ToException(e); if (ex instanceof ArgumentException) { return "bad argument"; } return "something bad"; } } ```
Can JScript.NET distinguish different .NET exception types
[ "", ".net", "javascript", "exception", "" ]
Given 2 interfaces: ``` public interface BaseInterface<T> { } public interface ExtendedInterface<T0, T1> extends BaseInterface<T0> {} ``` and a concrete class: ``` public class MyClass implements ExtendedInterface<String, Object> { } ``` How do I find out the type parameter passed to the BaseInterface interface? (I can retrieve the ExtendedInterface type parameters by calling something like ``` MyClass.class.getGenericInterfaces()[0].getActualTypeArguments() ``` but I can't spot an easy way to recurse into any base generic interfaces and get anything meaningful back).
This problem is not easy to fully solve in general. For example, you also have to take type parameters of the containing class into account if it's an inner class,... Because reflection over generic types is so hard using just what Java itself provides, I wrote a library that does the hard work: gentyref. See <http://code.google.com/p/gentyref/> For your example, using gentyref, you can do: ``` Type myType = MyClass.class; // get the parameterized type, recursively resolving type parameters Type baseType = GenericTypeReflector.getExactSuperType(myType, BaseInterface.class); if (baseType instanceof Class<?>) { // raw class, type parameters not known // ... } else { ParameterizedType pBaseType = (ParameterizedType)baseType; assert pBaseType.getRawType() == BaseInterface.class; // always true Type typeParameterForBaseInterface = pBaseType.getActualTypeArguments()[0]; System.out.println(typeParameterForBaseInterface); } ```
I don't know what exactly you are trying to achieve, and what is known and what not, but you can recurse to the superinterface like this: ``` Type[] interfaces = MyClass.class.getGenericInterfaces(); ParameterizedType extInterfaceType = (ParameterizedType)interfaces[0]; Class<?> extInterfaceClass = (Class<?>)extInterfaceType.getRawType(); Type[] baseInterfaces = extInterfaceClass.getGenericInterfaces(); ParameterizedType baseInterfaceType = (ParameterizedType)baseInterfaces[0]; Class<?> baseInterfaceClass = (Class<?>)baseInterfaceType.getRawType(); ``` Of course if you reach the second level that way you get only your names T0 and T1 as generic parameters. If you know the relationship between `ExtendedInterface` and `BaseInterface` you don't really have to go that far since you know which generic parameter of the former is passed to the latter. If not, you probably would have to loop through their parameters and find a match. Something based on this probably: ``` Type[] params = extInterfaceClass.getTypeParameters(); for (Type param : params) { if (param == baseInterfaceType.getActualTypeArguments()[0]) { // ... } } ```
Retrieving type parameters from an instance of a generic base interface
[ "", "java", "generics", "reflection", "" ]
Is there an isnan() function? PS.: I'm in [MinGW](http://en.wikipedia.org/wiki/MinGW) (if that makes a difference). I had this solved by using isnan() from `<math.h>`, which doesn't exist in `<cmath>`, which I was `#include`ing at first.
According to the IEEE standard, NaN values have the odd property that comparisons involving them are *always* false. That is, for a float f, `f != f` will be true *only* if f is NaN. Note that, as some comments below have pointed out, not all compilers respect this when optimizing code. For any compiler which claims to use IEEE floating point, this trick *should* work. But I can't guarantee that it *will* work in practice. Check with your compiler, if in doubt.
# First solution: if you are using C++11 Since this was asked there were a bit of new developments: it is important to know that `std::isnan()` is part of C++11 ## Synopsis Defined in header `<cmath>` ``` bool isnan( float arg ); (since C++11) bool isnan( double arg ); (since C++11) bool isnan( long double arg ); (since C++11) ``` Determines if the given floating point number arg is not-a-number (`NaN`). **Parameters** `arg`: floating point value **Return value** `true` if arg is `NaN`, `false` otherwise **Reference** <http://en.cppreference.com/w/cpp/numeric/math/isnan> Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions. --- # Other solutions: if you using non C++11 compliant tools For C99, in C, this is implemented as a macro `isnan(c)`that returns an int value. The type of `x` shall be float, double or long double. Various vendors may or may not include or not a function `isnan()`. The supposedly portable way to check for `NaN` is to use the IEEE 754 property that `NaN` is not equal to itself: i.e. `x == x` will be false for `x` being `NaN`. However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...
Checking if a double (or float) is NaN in C++
[ "", "c++", "double", "nan", "" ]
I need to watch properties for changes. Which method is better in terms of performance and memory use: implementing `INotifyPropertyChanged` or using a `DependencyProperty`? Note: Yes, I have read the other question [INotifyPropertyChanged vs. DependencyProperty in ViewModel](https://stackoverflow.com/questions/291518/inotifypropertychanged-vs-dependencyproperty-in-viewmodel).
Memory Use: INotifyPropertyChanged is an interface, so close to zero memory overhead. "Close to zero" because I assume you'll be writing an OnPropertyChanged method and maybe some event handlers in other classes (unless you're really just talking about binding to WPF), so there will be a slight code overhead. Performance: DependancyProperties have alot going on under the covers. Unless you write the most non-performant OnPropertyChanged method ever, I would wager that INotifyPropertyChanged will be the perf winner as well. Unless you have a defined reason for wanting/needing the behaviors provided by a DP I would just go with INotifyPropertyChanged. **Update** As the comment mentions binding performance is a bit faster for DPs (15-20% faster, but still only a difference of less than 50ms for 1000 binds) due to the amount of reflection needed to to the lookup/hookup of direct properties. This is technically different than the performance of updating a databound UI element which is what my comment was geared towards. But that doesn't mean my wager is still correct either. So a few examples and alot of .NET Reflector digger later it looks... inconclusive. Both paths do a ton of work under the covers and I wasn't able to get any examples to show a definitive difference in update performance. I still stick with INotifyPropertyChanged unless I have specific need for DPs, but it was at least an interesting exercise to poke around into the WPF core some more. :)
Never mind, I just found the answers I was looking for in the following [question](https://stackoverflow.com/questions/156538/dependence-on-dependencyobject-and-dependencyproperty). I'll repost the answer by "LBugnion" (so all credit goes to him) for your convenience: --- Implementing INotifyPropertyChanged has many advantages over DependencyObjects (I will abbreviate this DO to make it easier) and using DependencyProperties (DPs): * This is more lightweight * Allows you more freedom in modeling your objects * Can be serialized easily * You can raise the event when you want, which can be useful in certain scenarios, for example when you want to bundle multiple changes in only one UI operation, or when you need to raise the event even if the data didn't change (to force redraw...) On the other hand, inheriting DOs in WPF have the following advantages: * Easier to implement especially for beginners. * You get a callback mechanism (almost) for free, allowing you to be notified when the property value changes * You get a coercion mechanism with allows you to define rules for max, min and present value of the property. There are other considerations, but these are the main. I think the general consensus is that DPs are great for controls (and you can implement a CustomControl with custom DPs even in Silverlight), but for data objects you should rather implement INotifyPropertyChanged. HTH, Laurent
INotifyPropertyChanged vs. DependencyProperty
[ "", "c#", ".net", "wpf", "" ]
I have a setup CD to install a visual studio C++ application I made. It has three files: setup.exe, AUTORUN.INF, and app.msi. When I insert the CD the Windows AutoPlay popup shows a generic icon. How do I have my own icon displayed for setup.exe. I also want this for the drive icon after I insert the CD, I think they're related.
I hate autostart. In AUTORUN.INF, you can specify the drive icon just next to the setup program: ``` [AutoRun] open=setup.exe icon=*youricon*.ico ```
in the [autorun] section on AUTORUN.INF, add a line like: ``` icon=filename.ext ``` I believe the file can be an image file or an executable, in which case it will use the first icon resource.
How do I have an icon displayed when a setup CD is autoplayed in Windows
[ "", "c++", "cd", "autoplay", "" ]
Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this: ``` class PairEvaluator(HandEvaluator): def returnArbitrary(self): return ('ace', 'king') pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards)) ``` When I try to run this code, the compiler gives an IndexError: tuple index out of range. How should I structure my return value to pass it as an argument to `.format()`?
``` print('Two pair, {0}s and {1}s'.format(*cards)) ``` You are missing only the star :D
Format is preferred over the % operator, as of its introduction in Python 2.6: <http://docs.python.org/2/library/stdtypes.html#str.format> It's also a lot simpler just to unpack the tuple with \* -- or a dict with \*\* -- rather than modify the format string.
Return a tuple of arguments to be fed to string.format()
[ "", "python", "string-formatting", "tuples", "" ]
I am working on coding a Tetris clone in XNA C# and am unsure of the best way to approach the data structure side of the game on a high level. I am totally fine with the collision detection, rotations, animation etc. What I need to know the best way to do the storing of "dropped blocks" - ie blocks that are no longer under tha player's control. I think that each Tetromino block should be stored in its own class that consists of a 4x4 array so that the block can easily be rotated. The problem is then how to I store the tetromino's final position into the game grid by then cutting the tetromino up into individual blocks(for each cell) and then set the main game grid's corresponding positions to hold these same blocks, then disappearing the tetromino once it has reached its final position. Maybe there is some drawback to my method. Should I create a 10x20 matrix for the main game grid which can then store? or should I use stacks or queues to somehow store the dropped blocks. Or maybe there is some better method/data structure to store things? I am sure my way would work, but I am reaching out to see if anybody knows a better way or if my way is good enough? P.S. Not homework, this will be a project for my portfolio. Thanks.
Once a block is immobile, there's nothing that distinguishes it from any other block that is now immobile. In that regard, I think it makes the most sense to store the entire grid as a matrix, where each square is either filled or not (along with the color of the block if it is). I feel like the matrix has many advantages. It'll make collision detection simple (no having to compare with multiple objects, just locations on a matrix). Storing it as a matrix will also make it easier to determine when a full line has been created. On top of that, you don't have to worry about splicing an immobile Tetromino when a line disappears. And when one does, you can just shift the entire matrix down in one fell swoop.
This smells like homework, but my take on an object-oriented approach to Tetris would be to have each individual square be an object, and both "blocks" (tetrominos) and the grid itself would be collections of the same square objects. Block objects manage the rotation and position of the falling squares, and the grid handles displaying them and detroying completed rows. Each block would have a colour or texture associated with it that would be provided by the original block object it came from, but otherwise squares at the base of the grid would have no other indication that they were ever part of the same original block. To elaborate, when you create a new block object, it creates a set of 4 squares with the same colour/texture on the grid. The grid manages their display. So when the block hits the bottom, you just forget about the block, and the squares remain referenced by the grid. Rotations and dropping are operations only a block need deal with, and only one its four squares (though it will need to be able to query the grid to make sure the rotation can fit).
How To Make a Tetris Clone?
[ "", "c#", "data-structures", "software-design", "" ]
I have an `XDocument` object. I want to query for elements with a particular name at any depth using LINQ. When I use `Descendants("element_name")`, I only get elements that are direct children of the current level. I'm looking for the equivalent of "//element\_name" in XPath...should I just use `XPath`, or is there a way to do it using LINQ methods?
Descendants should work absolutely fine. Here's an example: ``` using System; using System.Xml.Linq; class Test { static void Main() { string xml = @" <root> <child id='1'/> <child id='2'> <grandchild id='3' /> <grandchild id='4' /> </child> </root>"; XDocument doc = XDocument.Parse(xml); foreach (XElement element in doc.Descendants("grandchild")) { Console.WriteLine(element); } } } ``` Results: > `<grandchild id="3" />` > `<grandchild id="4" />`
An example indicating the namespace: ``` String TheDocumentContent = @" <TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' > <TheNamespace:GrandParent> <TheNamespace:Parent> <TheNamespace:Child theName = 'Fred' /> <TheNamespace:Child theName = 'Gabi' /> <TheNamespace:Child theName = 'George'/> <TheNamespace:Child theName = 'Grace' /> <TheNamespace:Child theName = 'Sam' /> </TheNamespace:Parent> </TheNamespace:GrandParent> </TheNamespace:root> "; XDocument TheDocument = XDocument.Parse( TheDocumentContent ); //Example 1: var TheElements1 = from AnyElement in TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" ) select AnyElement; ResultsTxt.AppendText( TheElements1.Count().ToString() ); //Example 2: var TheElements2 = from AnyElement in TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" ) where AnyElement.Attribute( "theName" ).Value.StartsWith( "G" ) select AnyElement; foreach ( XElement CurrentElement in TheElements2 ) { ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value ); } ```
Query an XDocument for elements by name at any depth
[ "", "c#", ".net", "xml", "linq", "linq-to-xml", "" ]
I'm looking for the "best practice" as to where the JSON should be stored if it's just a string array. Should it be stored in a variable in a script block in the HTML page? Should it be stored in a JavaScript file outside of the HTML for separation? Or should it be stored in the plugin itself? If it should be an external js file, what's the "best practice" naming scheme for the file? I know the accepted jQuery plugin name is jquery.plugin.js or jquery.plugin-min.js (for the minified file).
Depends, if you need the JSON right away you can store it anywhere to get it executed: ``` <script> var myJsonObj = { ... }; </script> ``` If it's a lot of Data and you don't need the data right away, you can always make an ajax call to a file named something like "data.json". For naming the plugin name, well it's really up to you, but yeah I believe jquery.pluginname.js is the standard way of doing it.
I'll second sktrdie to add the extension .json for a file like this. A gotcha that I ran across when first playing with JSON is that a JSON string is not a valid JavaScript File. For example, If I call a file with this content: ``` { 'foos': 'whatever', 'bar': false, 'items': [1,2,3] } ``` as the src of a <script> tag, I get this error: ``` Error: invalid label Line: 2, Column: 1 Source Code: 'foos': 'whatever', ``` In the past I've actually hidden JSON strings in <divs> or spans like this: ``` <div id="jsonStorage" style="display:none"> {'foos': 'whatever','bar': false,'items': [1,2,3]} </div> ``` I've also used hidden form fields for this.
Best Practice for Storing JSON Data That Will Be Passed to jQuery Plugin
[ "", "javascript", "jquery", "json", "naming-conventions", "" ]
What is the best connection pooling library available for Java/JDBC? I'm considering the 2 main candidates (free / open-source): * Apache DBCP - <http://commons.apache.org/dbcp/> * C3P0 - <http://sourceforge.net/projects/c3p0> I've read a lot about them in blogs and other forums but could not reach a decision. Are there any relevant alternatives to these two?
DBCP is out of date and not production grade. Some time back we conducted an in-house analysis of the two, creating a test fixture which generated load and concurrency against the two to assess their suitability under real life conditions. DBCP consistently generated exceptions into our test application and struggled to reach levels of performance which C3P0 was more than capable of handling without any exceptions. C3P0 also robustly handled DB disconnects and transparent reconnects on resume whereas DBCP never recovered connections if the link was taken out from beneath it. Worse still DBCP was returning Connection objects to the application for which the underlying transport had broken. Since then we have used C3P0 in 4 major heavy-load consumer web apps and have never looked back. **UPDATE:** It turns out that after many years of sitting on a shelf, the Apache Commons folk have taken [DBCP out of dormancy](http://commons.apache.org/dbcp/) and it is now, once again, an actively developed project. Thus my original post may be out of date. That being said, I haven't yet experienced this new upgraded library's performance, nor heard of it being de-facto in any recent app framework, yet.
I invite you to try out [BoneCP](http://www.jolbox.com/) -- it's free, open source, and faster than the available alternatives (see benchmark section). Disclaimer: I'm the author so you could say I'm biased :-) UPDATE: As of March 2010, still around 35% faster than the new rewritten Apache DBCP ("tomcat jdbc") pool. See dynamic benchmark link in benchmark section. Update #2: (Dec '13) After 4 years at the top, there's now a much faster competitor : <https://github.com/brettwooldridge/HikariCP> Update #3: (Sep '14) Please consider BoneCP to be **deprecated** at this point, recommend switching to [**HikariCP**](http://brettwooldridge.github.io/HikariCP/). Update #4: (April '15) -- I no longer own the domain jolbox.com
Connection pooling options with JDBC: DBCP vs C3P0
[ "", "java", "jdbc", "connection-pooling", "c3p0", "apache-commons-dbcp", "" ]
Good afternoon everyone, I am having an issue with a stored procedure inserting an incorrect value. Below is a summarization of my stored procedure ... ``` set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go CREATE PROCEDURE [dbo].[InsertDifferential] @differential int = null AS BEGIN TRY BEGIN TRANSACTION UPDATE DifferentialTable SET differential = @differential COMMIT END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int, @ErrorState INT SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); RAISERROR(@ErrMsg, @ErrSeverity, @ErrorState); END CATCH ``` Below is the code I use to call the stored procedure ... ``` SqlConnection dbEngine = new SqlConnection(connectionString); SqlCommand dbCmd = new SqlCommand("InsertDifferential", dbEngine); SqlDataAdapter dataAdapter = new SqlDataAdapter(dbCmd); dbCmd.CommandType = CommandType.StoredProcedure; if (myobject.differential.HasValue) { dbCmd.Parameters.AddWithValue("@differential", myobject.differential); } else { dbCmd.Parameters.AddWithValue("@differential", DBNull.Value); } dbCmd.ExecuteNonQuery(); ``` In the database table, the differential column is a nullable int with no default value. The differential property of "myobject" is an int? data type set to null by default. The issue is when I run the stored procedure, the differential column winds up with a 0 in place. Even if "myobject.differential" is null and I pass in the DBNull.Value the column still winds up with a 0 in place. I've tried not passing the @differential into the stored procedure and it still sets the column to 0. I've tried a number of different solutions and nothing has worked. Thank you in advance for any assistance, Scott Vercuski
I believe that when you set the default value on a parameter like ``` @differential int = null ``` You do not need to add it to your SQL Command. Try the code with just this and do not include the else... ``` if (myobject.differential.HasValue) { dbCmd.Parameters.AddWithValue("@differential", myobject.differential); } ```
Are you certian that the differential column does not have a **Default Value Constraint** on it of zero?
Stored Procedure parameter inserting wrong value
[ "", "sql", "stored-procedures", "parameters", "null", "" ]
how to get the application pool name for a specific website IIS 6 programmatic using C# EDIT: I already used the methods of DirectoryServices namespace but the application pool name isn't retrieved correctly unless it was explicitly set by using the same code. Which means if u add a website manually using the iis manager and set an application pool, those codes won't work (it will always return DefaultAppPool) more over when I create an application using sharepoint and set a different appPool those methods dont work.
The classes in the [System.DirectoryServices namespace](http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx) will help you get that information. Check [this article by Rick Strahl](http://www.west-wind.com/weblog/posts/10181.aspx) for an example: ``` /// <summary> /// Returns a list of all the Application Pools configured /// </summary> /// <returns></returns> public ApplicationPool[] GetApplicationPools() { if (ServerType != WebServerTypes.IIS6 && ServerType != WebServerTypes.IIS7) return null; DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools"); if (root == null) return null; List<ApplicationPool> Pools = new List<ApplicationPool>(); foreach (DirectoryEntry Entry in root.Children) { PropertyCollection Properties = Entry.Properties; ApplicationPool Pool = new ApplicationPool(); Pool.Name = Entry.Name; Pools.Add(Pool); } return Pools.ToArray(); } /// <summary> /// Create a new Application Pool and return an instance of the entry /// </summary> /// <param name="AppPoolName"></param> /// <returns></returns> public DirectoryEntry CreateApplicationPool(string AppPoolName) { if (this.ServerType != WebServerTypes.IIS6 && this.ServerType != WebServerTypes.IIS7) return null; DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools"); if (root == null) return null; DirectoryEntry AppPool = root.Invoke("Create", "IIsApplicationPool", AppPoolName) as DirectoryEntry; AppPool.CommitChanges(); return AppPool; } /// <summary> /// Returns an instance of an Application Pool /// </summary> /// <param name="AppPoolName"></param> /// <returns></returns> public DirectoryEntry GetApplicationPool(string AppPoolName) { DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools/" + AppPoolName); return root; } /// <summary> /// Retrieves an Adsi Node by its path. Abstracted for error handling /// </summary> /// <param name="Path">the ADSI path to retrieve: IIS://localhost/w3svc/root</param> /// <returns>node or null</returns> private DirectoryEntry GetDirectoryEntry(string Path) { DirectoryEntry root = null; try { root = new DirectoryEntry(Path); } catch { this.SetError("Couldn't access node"); return null; } if (root == null) { this.SetError("Couldn't access node"); return null; } return root; } ```
I don't agree with you. I coded up a test app and I get the correct AppPool name from it, even if I set the AppPool manually using IIS Manager. To make sure, I have tested once, name name was ok; then, I popep up the IIS Manager, changed the AppPool, executed `iisreset`, and ran the test app again - the AppPool name I got was correct again. I don't how your code looked like, but mine is like this: ``` using System; using System.IO; using System.DirectoryServices; class Class { static void Main(string[] args) { DirectoryEntry entry = FindVirtualDirectory("<Server>", "Default Web Site", "<WantedVirtualDir>"); if (entry != null) { Console.WriteLine(entry.Properties["AppPoolId"].Value); } } static DirectoryEntry FindVirtualDirectory(string server, string website, string virtualdir) { DirectoryEntry siteEntry = null; DirectoryEntry rootEntry = null; try { siteEntry = FindWebSite(server, website); if (siteEntry == null) { return null; } rootEntry = siteEntry.Children.Find("ROOT", "IIsWebVirtualDir"); if (rootEntry == null) { return null; } return rootEntry.Children.Find(virtualdir, "IIsWebVirtualDir"); } catch (DirectoryNotFoundException ex) { return null; } finally { if (siteEntry != null) siteEntry.Dispose(); if (rootEntry != null) rootEntry.Dispose(); } } static DirectoryEntry FindWebSite(string server, string friendlyName) { string path = String.Format("IIS://{0}/W3SVC", server); using (DirectoryEntry w3svc = new DirectoryEntry(path)) { foreach (DirectoryEntry entry in w3svc.Children) { if (entry.SchemaClassName == "IIsWebServer" && entry.Properties["ServerComment"].Value.Equals(friendlyName)) { return entry; } } } return null; } } ``` Sorry for my lousy english. Hope I've helped.
how to get the application pool name for a specific website IIS6 programmatically? C#
[ "", "c#", "iis", "application-pool", "" ]
After switching from C++ to C++ w/boost, do you think your OOD skills improved? Do you notice patterns in "Normal" C++ code that you wouldn't consider that you've switched, or do you find that it enables a more abstract design? I guess I'm really wondering if you just use it as a tool, or if you change your entire approach to OO design to make more efficient use of objects when using boost pointers. Edit:summary This question was kind of strange--I was asking because I've run into so much C++ code that was not at all OO. I'm fairly sure (with that and my work on it before moving to a managed language) that it's harder to think in OO in C++ than a managed language. From looking at these posts, I'm guessing that you learn the value of OO before finding a need for a better way to manage memory, so by the time you start looking for something like Boost, you're already using OO methodologies pretty heavily. I was kind of expecting a bunch of answers saying that it helped them think in OO, but now that I think about it, if you aren't using OO, boost pointers are not very helpful, and you wouldn't see the need for them (so you wouldn't have replied).
In a project in C++ I was doing about six years ago, we implemented our own boost-like automatic pointer scheme. It worked pretty well, except for the various bugs in it. (Sure wish we had used boost...) Nonetheless, it really didn't change how we developed code. Object oriented design, with or without managed pointers, is very similar. There's times when you need to return objects, or times when pointers to objects are more important. The nice thing about smart pointers has only a small amount to do with how you design your application. Instead of passing a potentially dangerous memory leak around, you can pass that same data and be fairly certain that it's not going to leak. In that respect, there are some things you can tend to do more with smart pointers: simplify your code. Instead of returning integers or basic structures every where, you can more freely pass complicated data structures or classes without worry. You can build more complex apps, faster, without having to worry so much. It lets you have the raw power of C and C++ when you need it (why would you be using C or C++ if you didn't need it?) and have the ease of memory management that's such an amazing productivity boost. If automatically managed memory wasn't useful, it wouldn't be in almost every other language on the planet!
STL/Boost is a tool for the job. They help me implement my ideas not the other way around. Clarification: Boost did not boost up my OOD skills.
Does using boost pointers change your OO design methodology?
[ "", "c++", "boost", "oop", "" ]
I'm looking for a simple Java in-memory cache that has good concurrency (so LinkedHashMap isn't good enough), and which can be serialized to disk periodically. One feature I need, but which has proved hard to find, is a way to "peek" at an object. By this I mean retrieve an object from the cache without causing the cache to hold on to the object any longer than it otherwise would have. **Update:** An additional requirement I neglected to mention is that I need to be able to modify the cached objects (they contain float arrays) in-place. Can anyone provide any recommendations?
Since this question was originally asked, [Google's Guava library](https://github.com/google/guava/wiki/CachesExplained) now includes a powerful and flexible cache. I would recommend using this.
[Ehcache](http://ehcache.sourceforge.net/) is a pretty good solution for this and has a way to peek ([getQuiet()](http://ehcache.sourceforge.net/apidocs/net/sf/ehcache/Cache.html#getQuiet(java.lang.Object)) is the method) such that it doesn't update the idle timestamp. Internally, Ehcache is implemented with a set of maps, kind of like ConcurrentHashMap, so it has similar kinds of concurrency benefits.
Looking for simple Java in-memory cache
[ "", "java", "caching", "" ]
I'm not clear about the interaction between database schema changes and differential backups on sql 2005. Lets say I do a Full backup right right now. Then I perform some schema changes. Then I do a diff backup. What happens? Do I need to create another FULL backup? Are my schema changes and any data in those new schema bits included in my diff backup?
Yes, you are correct. All changes, whether structural changes or data modifications, within the database (i.e. any object that resides within the database) since your last full database backup will be recorded by any subsequent differential backup that you execute. I hope this clears things up for you but please feel free to pose further questions. cheers, John
Yes, all changes to the table will be kept in the differential backup. This includes all DDL code that is executed against the database.
Sql 2005 Backups and Schema Changes Interactions
[ "", "sql", "sql-server-2005", "schema", "backup", "" ]
Will it be easy for a C++ developer to read [Refactoring: Improving the Design of Existing Code](https://rads.stackoverflow.com/amzn/click/com/0201485672) Is there any other book that I should read about refactoring? Feel free to add any articles on refactoring.
If you work with legacy code then it may be worth getting [Working Effectively with Legacy Code by Michael Feathers](https://rads.stackoverflow.com/amzn/click/com/0131177052).
As far as I know there is no book about refactoring, that has examples in c++. Mostly it is Java sometimes it is C#. But the basic concepts are the same - so I do not see the problem with language mix.
Suggestion on book to read about refactoring?
[ "", "c++", "refactoring", "" ]
**Question:** * How to **pass** specifically **two** arguments to [CreateThread](http://msdn.microsoft.com/en-us/library/ms682453(VS.85).aspx), **when**: + Argument one, of type `SOCKET` + Argument two, an **interface pointer**: `_COM_SMARTPTR_TYPEDEF(Range, __uuidof(Range));` `RangePtr pRange; //pass pRange` **Suggestions:** * For interface pointer, using [CoMarshalInterThreadInterfaceInStream](http://msdn.microsoft.com/en-us/library/ms693316.aspx), accordingly,
create a structure of these two types and pass a pointer to it. This is the standard way of passing data to threads over single pointer.
Rather than creating struct\_thread\_xyz\_params, I would first use boost::thread if possible. If that wasn't an option, I would create a wrapper template function object that calls CreateThread with itself when it is constructed: ``` template <class Func> class Thread { Func m_Func; static DWORD WINAPI ThreadFunc(void* param) { Thread& pFunc = *(Thread*)param; pFunc(); return S_OK; } public: Thread(Func& func): m_Func(func){ CreateThread(NULL,NULL,Thread::ThreadFunc,this,NULL,NULL); }; void operator()() { m_Func(); } }; ``` then if I had a function that took two args: ``` void printTwoStrings(string a, string b) { cout << a << " " << b << endl; }; ``` I could wrap them in a functor: ``` class StringFunc { string m_a; string m_b; public: StringFunc(string a, string b):m_a(a),m_b(b) { }; void operator()(){ printTwoStrings(m_a,m_b); } }; ``` and initiliaze an instance of that functor on demand: ``` int main() { Thread<StringFunc> myThread(StringFunc("hello","world")); Sleep(500); return 0; } ``` note that I'm sleeping at the end, you didn't say anything at all about waiting for the thread to complete... The difficulty with struct\_xyz\_params is that you will often need later struct\_wxyz\_params and the temptation to duplicate code is always high... boost::thread is good too (but I already said that). -Rick
Pass more than one argument to CreateThread
[ "", "c++", "windows", "visual-studio-2008", "com", "marshalling", "" ]
How do I limit the loop below to 50 so it stops when it reaches the 51st item? ``` foreach (ListViewItem lvi in listView.Items) { } ``` Thanks
``` foreach (ListViewItem lvi in listView.Items) { // do code here if (listView.Items.IndexOf(lvi) == 49) break; } ``` OR since it is a list view item ``` foreach (ListViewItem lvi in listView.Items) { // do code here if (lvi.Index == 49) break; } ``` Using Linq as Per [LukeDuff](https://stackoverflow.com/questions/539075/c-loop-limited-to-50-passes/539152#539152) ``` foreach (ListViewItem lvi in listView.Items.Take(50)) { // do code here } ``` Using For Loop as Per [Atomiton](https://stackoverflow.com/questions/539075/c-loop-limited-to-50-passes/539089#539089) ``` // loop through collection to a max of 50 or the number of items for(int i = 0; i < listView.Items.Count && i < 50; i++){ listView.Items[i]; //access the current item } ```
Easy with Linq ``` foreach (ListViewItem lvi in listView.Items.Take(50)) { } ``` From the MSDN documentation: > Take<(Of <(TSource>)>) enumerates > source and yields elements until count > elements have been yielded or source > contains no more elements. > > If count is less than or equal to > zero, source is not enumerated and an > empty IEnumerable<(Of <(T>)>) is > returned.
C# Loop limited to 50 passes
[ "", "c#", "loops", "" ]
I have a Java GUI that has a number of text fields, the values of which are populated from static variable in another class. I am interested to know what the best way is to make it so that when the variable is changed in another class, the update is instantly reflected on the GUI. If any one could make a suggestion on an efficient way to do this it would be highly appreciated. Many Thanks for your replies in advance Edit: Additional Details * Using Swing * Updates would ideally be real time
In my opinion a wise choice is to implement it following the [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern). you can find plenty of examples on this topic like [this](http://www.javaworld.com/javaworld/javaqa/2001-05/04-qa-0525-observer.html)
You didn't mention what toolkit you were using and what the architecture of your project is. It's also not clear how fast and frequently you want to update the GUI elements, as the cost in flickrers may be too great, and so might be the cost in notifications using a listening mechanism. If it is fairly straightforward to determine change, and if I don't need real-time performance but rather just some feedback to the users, I've been happy enough running a background thread that occasionally makes the check and updates if necessary.
Best Way to Constantly Update GUI Elements
[ "", "java", "multithreading", "user-interface", "performance", "" ]
Is there a way to customize XML serialization in JAXB, in the same way that it's possible using IXmlSerializable in .NET? (i.e. the ability to directly control serialization of an object using the equivalent of an XmlReader/Writer). I've taken a look at XmlAdapter and @XmlJavaTypeAdapter, but they just seem to be used to transform types to and from serializable forms, which isn't quite what I want. Update: In particular, I'd like to customize the deserialization of a root object, that determines, programatically, exactly how to deserialize the inner XML (e.g. create a jaxb unmarshaller with a particular set of known types). Update: I've found a way to solve the problem, but it's such a nasty hack I'll probably go with one of the solutions suggested by the other posters.
I'm not sure I fully understand what your goal is, but maybe you could do what you want to do programatically inside the no-args constructor of your root object, which will be called to instantiate the object when it is unmarshalled.
OK, so I managed to get this working, although it's such a nasty solution that I think I'll find a higher-level way of working around the problem, as Fabian and basszero have mentioned. The idea of the following code is to create a generic serializable reference to the data you want to serialize, which maintains a JAXB java type adapter to perform the serialization programmatically, and a string field that stores the resulting XML. Note: Code has been greatly simplified for display... ``` // Create an instance of this class, to wrap up whatever you want to custom-serialize @XmlRootElement public static class SRef { public SRef() { } public SRef(Object ref) { this.ref = ref; } @XmlJavaTypeAdapter(SRefAdapter.class) public Object ref; } // This is the adapted class that is actually serialized public static class SRefData { // This is a hint field to inform the adapter how to deserialize the xmlData @XmlAttribute public String hint; // This contains the custom-serialized object @XmlElement public String xmlData; } // Converts an object to and from XML using a custom serialization routine public static class SRefAdapter extends XmlAdapter<SRefData, Object> { @Override public SRefData marshal(Object value) throws Exception { if (value instanceof MyType) { SRefData data = new SRefData(); data.xmlData = doSomeSpecificSerialization(value); data.hint = "myType"; return data; } throw new IllegalArgumentException("Can't serialize unknown object type " + value.getClass()); } @Override public Object unmarshal(SRefData refData) throws Exception { if (refData.hint.equals("myType")) { return doSomeSpecificDeserialization(refData.xmlData); } throw new IllegalArgumentException("Unhandled hint value in SRefData: " + refData.hint); } } ```
Custom serialization in JAXB
[ "", "java", "xml", "xml-serialization", "jaxb", "" ]
I am trying to find data within a HTML document. I don't need a full blown parser as it is just the data between one tag. But, I want to detect the 'select' tag and the data in between. ``` return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); /// End right angle bracket left off intentionally: track_pattern_buf.append("<select"); track_pattern_buf.append("(.*?)"); track_pattern_buf.append("</select"); ``` Is this the 'regex' that you would use?
If you really want to stich with regular expressions (which are not the best choice) I’d use: ``` "<select[^>]*>(.+?)</select\s*>" ```
I would use something that looked like: ``` "<select>([^<>]+)</select>" ``` I'm not sure why you left off the '>'s and I wouldn't want to match other tags (here I'm assuming we're looking for textual data and not a document fragment). That being said, I'd really look into getting a DOM and using XPath (or similar) to do your queries as regex's are not [well known for their ability to deal with trees](http://steve.yegge.googlepages.com/the-emacs-problem).
Regex in Java, finding start and end tag
[ "", "java", "html", "regex", "" ]
I have the following dictionary declared: ``` private readonly Dictionary<int, Image> dictionary; ``` And I have a method, which is causing a compiler error: ``` public IQueryable<Image> Find(Func<Image, bool> exp) { return dictionary.Single(exp); } ``` The error i get is: ``` Error 1 The type arguments for method 'System.Linq.Enumerable.Single<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,bool>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. C:\work\MSD-AIDS-Images\MSD-AIDS-Images-Test\TestImageRepository.cs 34 30 MSD-AIDS-Images-Test ``` I have tried googling around, I cant seem to find anything definitive as to what I am doing wrong Edit - This is monday morning at work. I meant to put "where", not single **Edit 2!** Ok, the code is now this: ``` public IQueryable<Image> Find(Func<Image, bool> exp) { return dictionary.Values.Where(exp); } ``` Now I get the following error: ``` Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<MSD_AIDS_Images_Data.Image>' to 'System.Linq.IQueryable<MSD_AIDS_Images_Data.Image>'. An explicit conversion exists (are you missing a cast?) C:\work\MSD-AIDS-Images\MSD-AIDS-Images-Test\TestImageRepository.cs 34 20 MSD-AIDS-Images-Test ``` As an FYI, the method there is for implementing an interface, the declaration for that is: ``` IQueryable<T> Find(Func<T, bool> exp); ``` This has got more complicated than it should be!
What is it you are trying to do? For example, `Single` will return an instance of `T`, not an `IQueryable<T>` (and for objects, you should probably be using `IEnumerable<T>` anyway)... It feels like you want: ``` public Image Find(Func<Image, bool> predicate) { return dictionary.Values.Single(predicate); } ``` Of course, you could do this globally as an extension method via something like: (**edit** includes `Where` from question edit) ``` static class DictionaryExtensions { public static TValue FindSingle<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, Func<TValue, bool> predicate) { return dictionary.Values.Single(predicate); } public static IEnumerable<TValue> Find<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, Func<TValue, bool> predicate) { return dictionary.Values.Where(predicate); } } ``` (I'm not sure it is much harder for the caller to do this themselves, though)
> An explicit conversion exists (are you missing a cast?) There are two `Where` methods, one on [System.Linq.Enumerable](http://msdn.microsoft.com/en-us/library/bb534803.aspx) (which it is using), and one on [System.Linq.Queryable](http://msdn.microsoft.com/en-us/library/bb535040.aspx) (which you think it should be using, according to that return type). You need to do one of the following: * change the return type to `IEnumerable<Image>` - I recommend this! * change the method call to `Queryable.Where(dictionary.Values.AsQueryable(), exp)` * call `AsQueryable()`
Lambda "cannot be inferred from the usage"
[ "", "c#", "linq", "lambda", "" ]
I was wondering if anyone here knows an efficient way to cast an integer to a byte[4]? I'm trying to write an int into MemoryStream, and this thing wants me to give it bytes
You can use [`BitConverter.GetBytes`](http://msdn.microsoft.com/en-us/library/de8fssa4.aspx) if you want to convert a primitive type to its byte representation. Just remember to make sure the endianness is correct for your scenario.
Use a [BinaryWriter](http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx) (constructed with your memory stream); it has a write method that takes an Int32. ``` BinaryWriter bw = new BinaryWriter(someStream); bw.Write(intValue); bw.Write((Int32)1); // ... ```
Cast int to byte[4] in .NET
[ "", "c#", ".net", "" ]
To teach myself Javascript, I'm trying to make a web page that gives users a list of items (e.g. foods), asks them to sort these foods from favorite to least favorite, and submit the data when they're done. Using jQuery sortables seems like a good way to do this. However, I'm not sure how the data submission should happen. Here's what I'm thinking. Each of these food items would be in a div like this: ``` <div id="sortable"> <div id="1" class="foods">Pizza</div> <div id="2" class="foods">Sushi</div> <div id="3" class="foods">Taco</div> </div> ``` When the user clicks a "submit" button, I want the order of these items to be determined, and for this ordering to be sent back to the server (by the way, I'm using Django on the server side). It seems I can determine the order of the items with a function like this: ``` function getOrder() { var foods = $(".foods"); var ids = []; for(var x=0; x<foods.length; x++) { ids.push(foods[x].id); } return ids; } ``` However, I'm stuck on a couple of things: * Where in my code would I call this function? I'm thinking it would be an onclick action when the user presses the submit button, but I'm not sure where the data the function returns would get passed. * What format would be the most appropriate for sending this ordering to the server (e.g JSON)? (I know this is a really basic question, but I have never made a web page with JavaScript before, so this area of programming is all new to me.)
A more semantically relevant way of doing a list is by using an actual `<ul>` element. So if you had something like this: ``` <ul id='foods'> <li id='food_1'>Pizza</li> <li id='food_2'>Sushi</li> <li id='food_3'>Taco</li> </ul> <a href="javascript:saveFoods();">Save Order</a> ``` The following jQuery code would be appropiate: ``` function saveFoods(id) { var data = $("#foods").sortable('serialize'); var action = "/django/view/"; $.post(action, data, function(json, status) { if(status == 'success' && json.status == 'success') { alert('Saved order of the foods!'); } else { alert('Unable to complete the request.'); } }, "json"); } ``` According to the jQuery docs on [sortable](http://docs.jquery.com/UI/Sortable), when you use serialize the elements of a sortable it requires their IDs to be in a `setname_number` format. So by having your list as `food_1`, `food_2`, etc. jQuery recognizes that the ID of Pizza is 1 and its set is food. The `data` variable in `saveFoods` will then contain something like `food[]=1&food[]=2&food[]=3` that you can process in your Django app.
It'd probably be easier to put hidden fields inside the list of items. When the form is submitted, the same order will be send to the server in the post or get. Example: ``` <div id="sortable"> <div id="1" class="foods"><input type="hidden" name="sortable[]" value="1" />Pizza</div> <div id="2" class="foods"><input type="hidden" name="sortable[]" value="2" />Sushi</div> <div id="3" class="foods"><input type="hidden" name="sortable[]" value="3" />Taco</div> </div> ``` The post will then have an array in it, like: ``` array( 0 => 1, 1 => 3, 2 => 2 ) ```
Submitting an ordered list to a server
[ "", "javascript", "" ]
I have written a stupid little game and want to have some kind of leader board website. Usually leaderboards are limited to 10 or 20 top players, but I thought it would be nice if I could record, **for every player, their top score**. Then, I could always display their world-wide rank. A simple schema such as: ``` create table leaderboard ( userid varchar(128) not null, score real not null, when datetime not null ); create index on leaderboard(userid); ``` Would store the minimal amount of information that I need - 1 entry per user with their best score. My question revolves around how to efficiently determine someone's position on the leader board. The general idea is that I would want their position in the list returned by: ``` select userid from leaderboard order by score desc ``` But running this query and then linearly searching the list seems a bit ridiculous to me from a DB performance standpoint. Even so, I am having a hard time imagining a query/schema that would make it a quick operation. Any ideas? (I would prefer to keep the DB schema and query generic (not tied to a vendor). But, if one vendor makes this easy, I am happy to use either MS SQL or MySQL.
How about: ``` select count(*)+1 as rank from leaderboard where score > (select score from leaderboard where userid = ?) ``` You'll also want an index on the score column. Doing `count()+1` with `score > (...)` will give you accurate ranks even when multiple players have the same score; doing `count()` with `score >= (...)` will not.
In SQL Server 2005 onwards, you can use the [`RANK()`](http://msdn.microsoft.com/en-us/library/ms176102(SQL.90).aspx) function to return the rank for each user, based on their score ``` SELECT userid, RANK() OVER (ORDER BY score) AS rank FROM leaderboard ``` If you had more than one type of 'game type', then you could include this in the Leaderboard table and use the `PARTITION BY` clause within the `RANK` function to determine ranking for each game type.
Efficient SQL Query/Schema for a Leader Board
[ "", "sql", "" ]
It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this: ``` <div style="width: 10px"></div> ``` All I need to do is: ``` document.getElementById('id').style.width = value; ``` It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example: ``` <style> #tId { width: 50%; } </style> <div id="tId"></div> ``` Using this Javascript: ``` document.getElementById('tId').style.width = "30%"; ``` I get the following: ``` <style> #tId { width: 50%; } </style> <div id="tId" style="width: 30%";></div> ``` This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have: ``` <div id="tId"></div> ``` The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work. So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?
Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a [Shawn Olson tutorial](http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html). You can directly reference his code [here](http://www.shawnolson.net/scripts/public_smo_scripts.js). Here is the summary: You can retrieve the [stylesheets](https://developer.mozilla.org/En/DOM/Stylesheet) via `document.styleSheets`. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the `document.styleSheets[styleIndex].href` property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what [CSSRule](https://developer.mozilla.org/en/DOM/cssRule#CSSStyleRule) you are on is by the `selectorText` property. The working code looks something like this: ``` var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex]; var selector = rule.selectorText; //maybe '#tId' var value = rule.value; //both selectorText and value are settable. ``` Let me know how this works for ya, and please comment if you see any errors.
Please! Just ask w3 (<http://www.quirksmode.org/dom/w3c_css.html>)! Or actually, it took me five hours... but here it is! ``` function css(selector, property, value) { for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles //Try add rule try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length); } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE } } ``` The function is really easy to use.. example: ``` <div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div> Or: <div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div> Or: <div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div> ``` Oh.. --- **EDIT:** as @user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function. ``` (function (scope) { // Create a new stylesheet in the bottom // of <head>, where the css rules will go var style = document.createElement('style'); document.head.appendChild(style); var stylesheet = style.sheet; scope.css = function (selector, property, value) { // Append the rule (Major browsers) try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length); } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9) } catch(err) {console.log("Couldn't add style");}} // (alien browsers) } })(window); ```
Changing CSS Values with Javascript
[ "", "javascript", "html", "css", "ajax", "dom", "" ]
I am trying to figure out the best way to model a set of "classes" in my system. Note that I'm not talking about OO classes, but classes of responses (in a survey). So the model goes like this: A Class can be defined with three different types of data: * A Class of Coded Responses (where a coded responses consists of a string label and an integer value) * A Class of Numeric Responses (defined as a set of intervals where each interval ranges from a min to a max value) * A Class of String Responses (defined as a set of regular expression patterns) Right now we have: Class table (to define unique classes) and a ClassCoded, ClassNumeric and ClassString table (all with a ClassID as a foreign key to Class table). My problem is that right now a Class could technically be both Coded and Numeric by this system. Is there any way to define the set of tables to be able to handle this situation??
There are two main ways to handle subtypes, either with sparse columns by adding columns for every possible property (preferrably with check constraints to make sure only one type has values) or to create a table for the supertype and then three tables for the sub-types, each with foreign keys back to the supertype table. Then add a check constraint to ensure that only one of the three possible type columns is not null. Personally I decide which of the two implementations to use based on how similar the subtypes are. If 90% of the columns are shared I use the sparse columns approach, if very little information is shared I use the multiple tables approach.
Relational databases don't handle this elegantly. Simplest way is to define columns for all different types of data, and only fill the appropriate ones.
Model Heterogeneous Type in Database
[ "", "sql", "database-design", "" ]
I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice? Is the new functionality in <http://www.python.org/dev/peps/pep-3107/> something I should start using for this?
Function annotations are not for a specific use, they can be used for anything. Tools can be written to extract information from the annotations and do anything you want, including checking types or generating documentation. But python itself does not do anything with the information. You could use to a completely different purpose, i.e. to provide a function that will be called on the parameter or to declare a string of possible return values. Annotations can be any object: ``` def somefunc(param1: "string annotation", param2: 151631, param3: any_object): -> "some information here": ``` and you can retrieve the objects using: ``` print (somefunc.func_annotations) {'param1': "string annotation", 'param2': 151631, 'param3': <object any_object>, 'return': "some information here"} ``` Use case suggestions provided by the PEP: * Providing typing information + Type checking + Let IDEs show what types a function expects and returns + Function overloading / generic functions + Foreign-language bridges + Adaptation + Predicate logic functions + Database query mapping + RPC parameter marshaling * Other information + Documentation for parameters and return values Since function annotation syntax is too new, it is really not used for any production tools. I suggest using other methods to document that. I use epydoc to generate my documentation, and it can read parameter typing information from docstrings: ``` def x_intercept(m, b): """ Return the x intercept of the line M{y=m*x+b}. The X{x intercept} of a line is the point at which it crosses the x axis (M{y=0}). This function can be used in conjuction with L{z_transform} to find an arbitrary function's zeros. @type m: number @param m: The slope of the line. @type b: number @param b: The y intercept of the line. The X{y intercept} of a line is the point at which it crosses the y axis (M{x=0}). @rtype: number @return: the x intercept of the line M{y=m*x+b}. """ return -b/m ``` This example is from [epydoc's website](http://epydoc.sourceforge.net/). It can generate documentation in a variety of formats, and can generate good graphs from your classes and call profiles.
If you use [epydoc](http://epydoc.sourceforge.net/) to produce API documentation, you have three choices. * Epytext. * ReStructuredText, RST. * JavaDoc notation, which looks a bit like epytext. I recommend RST because it works well with [sphinx](http://sphinx.pocoo.org/) for generating overall documentation suite that includes API references. RST markup is defined [here](http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html). The various epydoc fields you can specify are defined [here](http://epydoc.sourceforge.net/manual-fields.html). Example. ``` def someFunction( arg1, arg2 ): """Returns the average of *two* (and only two) arguments. :param arg1: a numeric value :type arg1: **any** numeric type :param arg2: another numeric value :type arg2: **any** numeric type :return: mid-point (or arithmetic mean) between two values :rtype: numeric type compatible with the args. """ return (arg1+arg2)/2 ```
How do I specify input and output data types in python comments?
[ "", "python", "documentation", "comments", "types", "" ]
This question was suggested by [Kyralessa](https://stackoverflow.com/users/5486/kyralessa) in the [What is your most useful sql trick to avoid writing more sql?.](https://stackoverflow.com/questions/488020/what-is-your-most-useful-sql-trick-to-avoid-writing-more-code) I got so many good ideas to try from the last question, that I am interested to see what comes up with this question. Once again, I am not keeping the reputation from this question. I am waiting 7 days, for answers, then marking it wiki. The reputation that the question has earned, goes into a bounty for the question. Ground Rules: * While it is certainly reasonable to write code, to move processing from SQL into the code to address performance issues, that is really not the point of the question. The question is not limited to performance issues. The goal is less simply less sql to get the job done. * Communicate the concept, so that other users say "Oh Wow, I didn't know you could do that." * Example code is very useful, to help people that are primarily visual learners. * Explicitly state what Language you are using, and which dialect of SQL you are using. * Put yourself in your readers shoes. What would they need to see right there on the screen in front of them, that will cause an epiphany. Your answer is there to benefit the reader. Write it for them. * Offsite links are ok, if they appear after the example. Offsite links as a substitute for a real answer are not. There are probably other things to make it nicer for the reader that I haven't thought of. Get Creative. Share knowledge. Have fun showing off. [EDIT] - It looks like there hasen't been any activity in a while. 5 votes = 50, so there is the bounty, and it has been wikified.
Where I work we've done several things to reduce SQL and to reduce the associated overhead of using SQL in Java. (We run Java with MSSQL, MySQL, and Oracle). The most useful trick is to use Java's setObject method for binding parameters. This, combined with Varargs, lets you write a utility method for executing SQL: ``` DBUtil.execSQL(Connection con, String sql, Object... params) ``` Simply iterate over the parameters and use statement.setObject(index, param[index-1]). For nulls you use setNull(). We've extended this concept for queries, with a getResultSet method; the wrapped ResultSet object also closes its statement, making it easier to do resource management. To reduce actual SQL code written, we have a query building framework that lets you specify a bunch of columns and their types, and then use this to automatically specify search criteria and output columns. We can easily specify joins and join criteria and this handles most of the normal cases. The advantage is that you can generate a report in about 10 lines of code, including different query parameters, sorting, grouping, etc. The code is too complex to include here. I've also used Oracle's ALL\_TABLES and ALL\_TAB\_COLUMNS tables to generate SELECT statements; another trick I've used is using the ResultSetMetadata to analyze the table: ``` ResultSet rs = DBUtil.getResultSet(con, "SELECT * FROM " + someTable); ResultSetMetaData rsm = rs.getMetaData(); boolean first = true; for (int i = 1; i <= rsm.getColumnCount(); i++) { String col = rsm.getColumnName(i).toUpperCase(); // do something with the column name } ``` This makes it easy to generate certain kinds of statements; in this case we have an active table and an archive table and we are moving records from one to the other. Without getting into a debate about using an archive table, the Java code I've written lets me modify the two tables without having to modify the archiving script. Another trick we use is to use constants for all our table and column names. This makes typing out SQL a little tedious but it allows us to (among other things) generate SQL easily for tables with similar or identical construction. Since we use constants to define the column names the code actually enforces that the the identical columns have the same name. Using constants also lets you find references to a particular column, thus allowing you to examine other SQL statements that may be related to the work you are doing. This lets us re-use SQL from other modules, instead of blindly re-writing the same statement again.
If you want to avoid writting SQL use an ORM such as nHibernate, or one of the Microsoft offerings Linq to SQL / Entity Framework This is even better then using a generator since you won't need to rerun the generators, and if you use Fluent nHibernate you can enable Configuration via Convention and not even maintain a mapping file / class.
What coding tricks have you used to avoid writing more sql?
[ "", "sql", "reference", "" ]
As an example: ``` SELECT name, address, phone FROM USER; ``` Generates the table ``` name | address | phone ... | ... | ... ``` How can i use this table generated to make another query to it? For example: ``` SELECT count(address) FROM (SELECT name, address, phone, from user); ``` I know it's not the best example, but is there any way to do this?
Use the same syntax but give your derived table an alias ``` SELECT count(subadd.address) FROM (SELECT name, address, phone, from user) as subadd; ```
The best way is to create a view: ``` CREATE VIEW my_view AS SELECT name, address, phone FROM USER; ``` Then you can sue it as a table: ``` SELECT count(address) FROM my_view; ```
How to make a query to a table generated by a select?
[ "", "sql", "mysql", "" ]
*Is there a way to cause an error if every constructor doesn't initialize a given member?* Maybe something with const? I want this because I have a pile of code where I'm getting errors as a result of incorrectly computing member values. What I'd really like to do is strip out the whole mess and follow the compiler's lead while redoing it (write code that uses the end result, fix the errors from using non existent code, fix errors from that, etc.). The one step where this doesn't work is member variables because I'm not forced to initialize them in the constructors like I would be for local variables.
Unfortunately, C# offers no such built-in predicates. The best you can do is write a method that checks the object in question either for nullity or some pre-determined flag value and be disciplined about calling it at the end of each constructor and/or at the top of each method that references the object.
It's supported. For example: ``` class Test { int notAssigned; void method() { // Use it, but don't initialize it int ix = notAssigned; } } ``` Produces: warning CS0649: Field 'ConsoleApplication1.Test.notAssigned' is never assigned to, and will always have its default value 0 To turn it into an error, use Project + Properties, Build tab, Treat warnings as errors.
Force explicit initialization of members in a c# constructor
[ "", "c#", "constructor", "" ]
Is there any performance difference between using something like ``` for(int i = 0; i < 10; i++) { ... } ``` and ``` for(int i = 0; i < 10; ++i) { ... } ``` or is the compiler able to optimize in such a way that they are equally fast in the case where they are functionally equivalent? Edit: This was asked because I had a discussion with a co-worker about it, not because I think its a useful optimization in any practical sense. It is largely academic.
There is no difference in the generated intermediate code for ++i and i++ in this case. Given this program: ``` class Program { const int counter = 1024 * 1024; static void Main(string[] args) { for (int i = 0; i < counter; ++i) { Console.WriteLine(i); } for (int i = 0; i < counter; i++) { Console.WriteLine(i); } } } ``` The generated IL code is the same for both loops: ``` IL_0000: ldc.i4.0 IL_0001: stloc.0 // Start of first loop IL_0002: ldc.i4.0 IL_0003: stloc.0 IL_0004: br.s IL_0010 IL_0006: ldloc.0 IL_0007: call void [mscorlib]System.Console::WriteLine(int32) IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: ldc.i4 0x100000 IL_0016: blt.s IL_0006 // Start of second loop IL_0018: ldc.i4.0 IL_0019: stloc.0 IL_001a: br.s IL_0026 IL_001c: ldloc.0 IL_001d: call void [mscorlib]System.Console::WriteLine(int32) IL_0022: ldloc.0 IL_0023: ldc.i4.1 IL_0024: add IL_0025: stloc.0 IL_0026: ldloc.0 IL_0027: ldc.i4 0x100000 IL_002c: blt.s IL_001c IL_002e: ret ``` That said, it's possible (although highly unlikely) that the JIT compiler can do some optimizations in certain contexts that will favor one version over the other. If there is such an optimization, though, it would likely only affect the final (or perhaps the first) iteration of a loop. In short, there will be no difference in the runtime of simple pre-increment or post-increment of the control variable in the looping construct that you've described.
As Jim Mischel [has shown](https://stackoverflow.com/questions/467322/is-there-any-performance-difference-between-i-and-i-in-c#467944), the compiler will generate identical MSIL for the two ways of writing the for-loop. But that is it then: there is no reason to speculate about the JIT or perform speed-measurements. If the two lines of code generate identical MSIL, not only will they perform identically, they are effectively identical. No possible JIT would be able to distinguish between the loops, so the generated machine code must necessarily be identical, too.
Is there any performance difference between ++i and i++ in C#?
[ "", "c#", "operators", "performance", "" ]
I have an element that already has a class: ``` <div class="someclass"> <img ... id="image1" name="image1" /> </div> ``` Now, I want to create a JavaScript function that will add a class to the `div` (not replace, but add). How can I do that?
# If you're only targeting modern browsers: Use [element.classList.add](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/add) to add a class: ``` element.classList.add("my-class"); ``` And [element.classList.remove](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove) to remove a class: ``` element.classList.remove("my-class"); ``` # If you need to support Internet Explorer 9 or lower: Add a space plus the name of your new class to the `className` property of the element. First, put an `id` on the element so you can easily get a reference. ``` <div id="div1" class="someclass"> <img ... id="image1" name="image1" /> </div> ``` Then ``` var d = document.getElementById("div1"); d.className += " otherclass"; ``` Note the space before `otherclass`. It's important to include the space otherwise it compromises existing classes that come before it in the class list. See also [element.className on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/className).
The easiest way to do this without any framework is to use [element.classList.add](https://developer.mozilla.org/en-US/docs/DOM/element.classList) method. ``` var element = document.getElementById("div1"); element.classList.add("otherclass"); ``` **Edit:** And if you want to remove class from an element - ``` element.classList.remove("otherclass"); ``` I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the `document.className` approach). There are some [browser limitations](http://caniuse.com/#feat=classlist), but you can work around them using [polyfills](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-classlist).
How to add a class to a given element?
[ "", "javascript", "dom-manipulation", "" ]
**"I am using flash as3, php and mysql"** What is the difference between: ``` $username = $_POST['username']; $password = md5( $_POST['password']); ``` and ``` $username = mysql_real_escape_string( $_POST['username']); $password = mysql_real_escape_string(md5( $_POST['password'])); ``` I am sending and retrieving variables from flash AS3 to php and back to AS3 again. The former one (without mysql\_real\_escape\_string) works fine. But the later one gets an error in flash. The error message is: "Parameter text must be non-null." I tried "echo" (display) both result, the results are the same. Very strange.. Anyone have any idea?
Remember that mysql\_real\_escape\_string() needs an open database connection to work properly; if you're calling it before using mysql\_connect, it won't have the desired effect.
You just need the `mysql_real_escape_string` if you want to use a string in a query that is then executed by the `mysql_query` function. And furthermore you just need this function if you cannot ensure that this string doesn’t contain certain characters that can violate the integrity of the query you intended.
Mysql Real Escape String and normal string
[ "", "php", "flash", "actionscript-3", "variables", "" ]
I'm looking for some random crashes in an old c++ application. Using sysinternals process explorer, I noticed the app losing handles, and extracted the exact situation, where the program is losing handles to a very short piece of code. ``` DWORD WINAPI MyTestThread( void* PThread) { _endthreadex(0); return 0; } int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR PParameter, int) { for (int i=0;i<10000;i++) { unsigned int threadID; HANDLE hThread= (HANDLE)_beginthreadex( (void*)NULL, (unsigned int)32768, (unsigned int (__stdcall *)(void *))MyTestThread, (void*)NULL, (unsigned int)0, &threadID); WaitForSingleObject((HANDLE)hThread, 1000); CloseHandle((HANDLE)hThread); } return 0; } ``` My problem: I can't figure out what's wrong with this code. It loses exactly 5 handles on every iteration, but it looks OK to me. Funny thing: it seems not to lose handles on windows vista, but I'd be very surprised if this should be a bug in windows 7. [Update] I tried using \_beginthread/\_endthread and CreateThread/ExitThread instead, those two are losing 5 handles, too, just like \_beginthreadex. [2nd Update] the code does run as expected. All return values are good. It is 'just' losing handles like there is no tomorrow. [3rd Update] **Big new Info** The code only loses handles, if compiled with /clr! And more, if I call GC::Collect() on each iteration the handles will be reclaimed! So, how do I find what clr-objects are being collected there?
Check whether some DLL which is linked to your exe is doing something strange in its DLLMain in response to DLL\_THREAD\_ATTACH notifications.
Have you checked if the functions succeed? The return values and `GetLastError()` could give some hints what's going wrong.
Why is this code losing handles on Windows 7 Beta?
[ "", "c++", "windows", "multithreading", "memory-leaks", "" ]
I have some database table and need to process records from it 5 at a time as long as app is running. So, it looks like this: 1. Get a record that hasn't been processed yet or not processing now by other threads. 2. Process it (this is a long process that depends on internet connection so it could timeout/throw errors). 3. Move to the next record. When reached end of table start from beginning. I don't have much experience with threads, so I see two possible strategies: **Approach A.** 1.Create new ExecutorService: ``` ExecutorService taskExecutor = Executors.newFixedThreadPool(5); ``` 2.Add 5 tasks to it: ``` for (int i = 0; i < 5; i++) { taskExecutor.execute(new MyTask()); } ``` 3.Each task will be infinite loop, that: reads a record from the table, processes it, and then gets another record. The problems with this approach is how to inform other threads about which records are currenly processing. To do this I can either use "status" field in the table or just use some CopyOnWriteArraySet that holds currently processing ID's. **Approach B.** 1.Create the same ExecutorService: ``` ExecutorService taskExecutor = Executors.newFixedThreadPool(5); ``` 2. Have an infinite loop that selects records that need to be processed and passes them to the executor: ``` while (true) { //get next record here taskExecutor.execute(new MyTask(record)); //monitor the queue and wait until some thread is done processing, //so I can add another record } ``` 3.Each task processes a single record. The problem with this approach is that I need to add tasks to the executor's queue slower than they are processed to not let them pile up over time. It means I need to monitor not only which tasks are currently running but also when they are done processing, so I can add new records to the queue. Personally I think first approach is better (easier), but I feel that the second one is more correct. What do you think? Or maybe I should do something completely different? Also I can use Spring or Quartz libraries for this if needed. Thanks.
I think that [CompletionService](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CompletionService.html) (and [ExecutorCompletionService](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html)) can help you. You submit all your tasks via completion service, and it allows you to wait until one of thread (any thread) finishes its task. This way you can submit next task as soon as there is free thread. This would imply that you use approach B. Pseudo code: ``` Create ThreadPoolExecutor and ExecutorCompletionService wrapping it while (true) { int freeThreads = executor.getMaximumPoolSize() - executor.getActiveCount() fetch 'freeThreads' tasks and submit to completion service (which in turn sends it to executor) wait until completion service reports finished task (with timeout) } ``` Timeout in wait helps you to avoid situation when there was no task in the queue, so all threads are idle, and you are waiting until one of them finishes -- which would never happen. You can check for number of free threads via [ThreadPoolExecutor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html) methods: `getActiveCount` (active threads) and `getMaximumPoolSize` (max available configured threads). You will need to create ThreadPoolExecutor directly, or to cast object returned from Executors.newFixedThreadPool(), although I would prefer direct creation... see source of Executors.newFixedThreadPool() method for details.
An alternative is to use an ArrayBlockingQueue of size 5. A single producer thread will go over the table, filling it up initially and putting records in as the consumers handle them. Five consumer threads will each take() a record, process it and go back for another record. This way the producer thread ensures that no record is given to two threads at once, and the consumer threads work on independent records. [Java Concurrency in Practice](http://jcip.net/) will probably give you many more options, and is a great read for this type of problems.
Need help with designing "infinite" threads
[ "", "java", "concurrency", "" ]
I have a stored procedure that returns a valueI call it from other stored procedures that need to retrieve this value. The calling stored procedure is inside a transaction, the stored procedure that returns the value (and actually creates the value and stores it in a table that no other proc touches) is not inside its own transaction, but would be part of the caller's transaction. The question is this, what is the most efficient way of retrieving the return value of the stored procedure and storing it in a variable in the calling proc? Currently I have the following and I'm wondering if its very inefficient? ``` DECLARE @tmpNewValue TABLE (newvalue int) INSERT INTO @tmpNewValue EXEC GetMyValue DECLARE @localVariable int SET @localVariable = (SELECT TOP 1 newvalue FROM @tmpNewValue ) ``` Isn't there a more straight forward way of doing this? Isn't this an expensive (in terms of performance) way? My stored proc doesn't have an output param, it just returns a value. Would using an output param be faster? For what it's worth I'm using MS SQL Server 2005
If your getting a single return variable then yes this is innefficent you can do: ``` declare @localVariable int exec @localVariable =GetMyValue select @localVariable ```
See [How to Share Data Between Stored Procedures](http://www.sommarskog.se/share_data.html) By some reasons 'exec @localVariable =GetMyValue' is not working for me (MS SQL 2005), it's always return 0 value ([They have the same issue](http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=119470)). My opinion is: if you can change stored procedure, add output parameter. else if you can remove procedure, rewrite it as a function. else use table variable, as you do.
What is the best way to assign the returned value of a stored proc to a variable in SQL?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?
``` >>> mydict = {'a':1,'b':3,'c':2} >>> sorted(mydict, key=lambda key: mydict[key]) ['a', 'c', 'b'] ```
I like this one: ``` sorted(d, key=d.get) ```
Sorting dictionary keys in python
[ "", "python", "sorting", "" ]
In the code below. I expected true but i am getting false instead. What am I missing? ``` var text = "Sentence $confirmationlink$ fooo"; alert(placeHolderExists(text,'confirmationlink'); // alerts false function placeHolderExists(text,placeholdername) { var pattern = new RegExp('\$'+placeholdername+'\$'); return pattern.test(text); } ```
The "\" in the RegExp expression builder is treated as an escape character when building the string, just as it is in the actual RegExp. You need to escape twice, try: ``` new RegExp('\\$'+placeholdername+'\\$'); ```
Should be ``` function placeHolderExists(text,placeholdername) { var pattern = new RegExp('\\$'+placeholdername+'\\$'); return pattern.test(text); } ``` You need to double escape your $ signs EDIT: [annakata](https://stackoverflow.com/questions/512363/javascript-regex-object-and-the-dollar-symbol/512418#512418) explains why.
Javascript Regex object and the dollar symbol
[ "", "javascript", "regex", "" ]
In the code below, what is the value of x and why? ``` bool x =true; x &= false; ```
x is false, becase (true & false) == false. &= is to & as += is to +.
``` x &= false; ``` is shorthand for: ``` x = x & false; ``` so in your code: true & false resolves to false.
What is this operator doing &= in this code?? (c#)
[ "", "c#", "" ]
I have a couple of models in django which are connected many-to-many. I want to create instances of these models *in memory*, present them to the user (via custom method-calls inside the view-templates) and if the user is satisfied, save them to the database. However, if I try to do anything on the model-instances (call rendering methods, e.g.), I get an error message that says that I have to save the instances first. The documentation says that this is because the models are in a many-to-many relationship. How do I present objects to the user and allowing him/her to save or discard them without cluttering my database? (I guess I could turn off transactions-handling and do them myself throughout the whole project, but this sounds like a potentially error-prone measure...) Thx!
I think that using django forms may be the answer, as outlined in [this](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/) documentation (search for m2m...). Edited to add some explanation for other people who might have the same problem: say you have a model like this: ``` from django.db import models from django.forms import ModelForm class Foo(models.Model): name = models.CharField(max_length = 30) class Bar(models.Model): foos = models.ManyToManyField(Foo) def __unicode__(self): return " ".join([x.name for x in foos]) ``` then you cannot call unicode() on an unsaved Bar object. If you do want to print things out before they will be saved, you have to do this: ``` class BarForm(ModelForm): class Meta: model = Bar def example(): f1 = Foo(name = 'sue') f1.save() f2 = foo(name = 'wendy') f2.save() bf = BarForm({'foos' : [f1.id, f2.id]}) b = bf.save(commit = false) # unfortunately, unicode(b) doesn't work before it is saved properly, # so we need to do it this way: if(not bf.is_valid()): print bf.errors else: for (key, value) in bf.cleaned_data.items(): print key + " => " + str(value) ``` So, in this case, you have to have saved Foo objects (which you might validate before saving those, using their own form), and before saving the models with many to many keys, you can validate those as well. All without the need to save data too early and mess up the database or dealing with transactions...
I would add a field which indicates whether the objects are "draft" or "live". That way they are persisted across requests, sessions, etc. and django stops complaining. You can then filter your objects to only show "live" objects in public views and only show "draft" objects to the user that created them. This can also be extended to allow "archived" objects (or any other state that makes sense).
How to work with unsaved many-to-many relations in django?
[ "", "python", "django", "django-models", "many-to-many", "" ]
consider this simple servlet sample: ``` protected void doGet(HttpServletRequest request, HttpServletResponse response){ Cookie cookie = request.getCookie(); // do weird stuff with cookie object } ``` I always wonder.. if you modify the object `cookie`, is it by object or by reference?
> if you modify the object `cookie`, is it > by object or by reference? Depends on what you mean by "modify" here. If you change the value of the reference, i.e. `cookie = someOtherObject`, then the original object itself isn't modified; it's just that you lost your reference to it. However, if you change the state of the object, e.g. by calling `cookie.setSomeProperty(otherValue)`, then you are of course modifying the object itself. Take a look at these previous related questions for more information: * [Java, pass-by-value, reference variables](https://stackoverflow.com/questions/498747/java-pass-by-value-reference-variables) * [Is Java pass by reference?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference)
Java methods get passed an **object reference by value**. So if you change the reference itself, e.g. ``` cookie = new MySpecialCookie(); ``` it will not be seen by the method caller. However when you operate on the reference to change the data the object contains: ``` cookie.setValue("foo"); ``` then those changes will be visible to the caller.
Object reference in java
[ "", "java", "object", "" ]
Suppose I have 2 tables, Products and ProductCategories. Both tables have relationship on CategoryId. And this is the query. ``` SELECT p.ProductId, p.Name, c.CategoryId, c.Name AS Category FROM Products p INNER JOIN ProductCategories c ON p.CategoryId = c.CategoryId WHERE c.CategoryId = 1; ``` When I create execution plan, table ProductCategories performs cluster index seek, which is as expectation. But for table Products, it performs cluster index scan, which make me doubt. Why FK does not help improve query performance? So I have to create index on Products.CategoryId. When I create execution plan again, both tables perform index seek. And estimated subtree cost is reduced a lot. My questions are: 1. Beside FK helps on relationship constraint, does it have any other usefulness? Does it improve query performance? 2. Should I create index on all FK columns (liked Products.CategoryId) in all tables?
Foreign Keys are a referential integrity tool, not a performance tool. At least in SQL Server, the creation of an FK does not create an associated index, and you should create indexes on all FK fields to improve look up times.
Foreign Keys can improve (and hurt) performance 1. As stated here: [Foreign keys boost performance](http://www.microsoft.com/technet/abouttn/flash/tips/tips_122104.mspx) 2. You should always create indexes on FK columns to reduce lookups. SQL Server does not do this automatically. **Edit** As the link now seems to be dead *(kudos to Chris for noticing)*, following shows the gist of why foreign keys can improve (and hurt) performance. [Can Foreign key improve performance](http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/A_4293-Can-Foreign-key-improve-performance.html) > Foreign key constraint improve performance at the time of reading > data but at the same time it slows down the performance at the time of > inserting / modifying / deleting data. > > In case of reading the query, the optimizer can use foreign key constraints to > create more efficient query plans as foreign key > constraints are pre declared rules. This usually involves skipping > some part of the query plan because for example the optimizer can see > that because of a foreign key constraint, it is unnecessary to execute > that particular part of the plan.
Does Foreign Key improve query performance?
[ "", "sql", "sql-server", "performance", "indexing", "foreign-keys", "" ]
Update: I'm going to leave it as is: The performance hit of a exception (very rare) is better than the probably performance hit for checking on each operation (common) --- I'm trying to support an "EstimatedRowCount" that in one case would be the product of two sub-cursors that are joined together: ``` estimatedRowCount = left.EstimatedRowCount * right.EstimatedRowCount; return estimatedRowCount; ``` Of course, if left and right are big enough, this will throw an OverflowException. Here, I don't really care if estimatedRowCount is 100% accurate, just big enough to know that this cursor is holding a lot of data. Right now, I'm doing this: ``` // We multiply our rowcount Int64 estimRowCount = 0; try { estimRowCount = leftRowCount * rightRowCount; } catch (OverflowException) { // Ignore overflow exceptions estimRowCount = Int64.MaxValue; } return estimRowCount; ``` Is there a better way to test for overflow operations so I don't have to do the try{}catch to guard?
This sounds like a good use case for the ['unchecked' keyword](http://msdn.microsoft.com/en-us/library/a569z7k8.aspx). To use, simply wrap your assignment in an 'unchecked' block: ``` Int64 estimRowCount = 0; unchecked { estimRowCount = leftRowCount * rightRowCount; } ``` Then test to see if the result is negative - if it is, it overflowed: ``` if (estimRowCount > 0) estimRowCount = Int64.MaxValue; ``` You'll need to ensure in this case that neither leftRowCount nor rightRowCount can be negative, but given the context I don't think that'll occur.
``` if (Int64.MaxValue / leftRowCount <= rightRowCount) { estimRowCount = leftRowCount * rightRowCount } else { estimRowCount = Int64.MaxValue; } ``` Not sure if I could explain myself without an editor. But, I hope you get the idea.
How do I gracefully test for overflow situations in C#?
[ "", "c#", "math", "exception", "" ]
Are there any options other than Janino for on-the-fly compiliation and execution of Java code in v5? I know v6 has the Compiler API, but I need to work with the v5 VM. I essentially need to take a string containing a complete Java class, compile it and load it into memory.
What you want is something like [Janino](http://www.janino.net/). We've used it for years. You give it (near standard) code and it gives you the classes so you can use them. It actually has quite a few different modes and supports the 1.5 syntactic sugar and auto-boxing and such. If you call javac, not only will you have to be ready for anything it does, you'll then have to handle putting the class in the right place or making an additional classloader. Janino is very easy. It should be exactly what you are looking for.
Invoking javac programatically: <http://www.juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/> ``` com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main(); String[] options = new String[] { "-classpath", classpath, "-d", outputDir, filename }; javac.compile(options); ```
Options for dynamic compilation in Java 5
[ "", "java", "compiler-construction", "dynamic-compilation", "janino", "" ]
I'm trying to make a GUI in java, but JMenuBar has been giving me a hard time for two days. Can someone please tell me why it isn't showing up? ``` import java.awt.*; import javax.swing.*; import javax.swing.JPanel; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.util.Arrays; import javax.imageio.ImageIO; public class selectionFrame extends JFrame { Font name; Font title; public void setup() //can't use constructer because this isn't given a size until after it is constructed. { //getContentPane().add(menuBar); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout()); //getContentPane().add(j); setJMenuBar(createMenuBar()); //getContentPane().add(createMenuBar()); } public JMenuBar createMenuBar() { JMenuBar menuBar; JMenu m_file; JMenuItem mi_save; JMenuItem mi_load; JMenu m_edit; JMenuItem mi_tileHeight; JMenuItem mi_tileWidth; menuBar = new JMenuBar(); m_file = new JMenu("File"); m_edit = new JMenu("Edit"); mi_save = new JMenuItem("Save file", KeyEvent.VK_S); mi_load = new JMenuItem("Load file", KeyEvent.VK_L); mi_tileHeight = new JMenuItem("Set tile height", KeyEvent.VK_H); mi_tileWidth = new JMenuItem("Set tile width", KeyEvent.VK_W); menuBar.add(m_file); m_file.add(mi_save); m_file.add(mi_load); menuBar.add(m_edit); m_edit.add(mi_tileHeight); m_edit.add(mi_tileWidth); return menuBar; } public static void main(String[] args) //run { selectionFrame sel = new selectionFrame(); sel.setLocationRelativeTo(null); sel.setSize((int) 400 + (sel.getInsets().left + sel.getInsets().right),(int) 400 + (sel.getInsets().top + sel.getInsets().bottom)); sel.setVisible(true); sel.setTitle("Tiles/Meta"); sel.setResizable(false); sel.setFocusable(true); sel.getContentPane().setSize(sel.getSize()); sel.setLocation((int) sel.getX() - (sel.getWidth()/2),(int) sel.getY() - (sel.getHeight()/2)); sel.setup(); sel.repaint(); } } ```
You have an awful lot of extra code there. > ``` > public class SelectionFrame extends JFrame > { > Font name; > Font title; > > public SelectionFrame() > { > setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); > setJMenuBar(createMenuBar()); > } > > public JMenuBar createMenuBar() > { > JMenuBar menuBar; > JMenu m_file; > JMenuItem mi_save; > JMenuItem mi_load; > > JMenu m_edit; > JMenuItem mi_tileHeight; > JMenuItem mi_tileWidth; > > menuBar = new JMenuBar(); > m_file = new JMenu("File"); > m_edit = new JMenu("Edit"); > > mi_save = new JMenuItem("Save file", KeyEvent.VK_S); > mi_load = new JMenuItem("Load file", KeyEvent.VK_L); > mi_tileHeight = new JMenuItem("Set tile height", > KeyEvent.VK_H); > mi_tileWidth = new JMenuItem("Set tile width", > KeyEvent.VK_W); > > menuBar.add(m_file); > m_file.add(mi_save); > m_file.add(mi_load); > > menuBar.add(m_edit); > m_edit.add(mi_tileHeight); > m_edit.add(mi_tileWidth); > > return menuBar; > } > > public void main( String args[] ) > { > > SelectionFrame sel = new SelectionFrame(); > sel.setLocationRelativeTo(null); > sel.setSize(400 + (sel.getInsets().left + > sel.getInsets().right), 400 > + (sel.getInsets().top + sel.getInsets().bottom)); > > sel.setTitle("Tiles/Meta"); > sel.setResizable(false); > sel.setFocusable(true); > > sel.getContentPane().add( new JLabel( "Content", SwingConstants.CENTER), > BorderLayout.CENTER ); > sel.setLocation(sel.getX() - (sel.getWidth() / 2), sel.getY() - > (sel.getHeight() / 2)); > sel.setVisible(true); > > } > } > ``` That shows up with a menu bar and everything. if you add your content to the CENTER of the content pane (by default a border layout), the center automatically fills the whole content area, you don't have to resize anything. This shows up as a window with a menu bar and everything works fine. What platform are you doing this on? I'm on Vista, i get what i expect to see.
What Java version are you using? Your menu bar shows up fine in 1.6.0\_10 on my system. Try wrapping the body of your main method in an `invokeLater()` call so that it runs on the correct thread, like so: ``` public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { selectionFrame sel = new selectionFrame(); sel.setLocationRelativeTo(null); sel.setSize((int) 400 + (sel.getInsets().left + sel.getInsets().right), (int) 400 + (sel.getInsets().top + sel.getInsets().bottom)); sel.setTitle("Tiles/Meta"); sel.setResizable(false); sel.setFocusable(true); sel.getContentPane().setSize(sel.getSize()); sel.setLocation((int) sel.getX() - (sel.getWidth() / 2), (int) sel.getY() - (sel.getHeight() / 2)); sel.setup(); sel.setVisible(true); // Follow Kendrick's advice too. } }); } ```
Why won't my JMenuBar show up?
[ "", "java", "user-interface", "swing", "" ]
I'm working on a simple hello world TCP/IP client server app in C# and am unable to get my client to connect. Can anyone offer any additional troubleshooting steps? I'm starting to run out of ideas... Here are the relevant sections of code: server: ``` Console.Out.WriteLine("About to bind address"); IPAddress ipAd = IPAddress.Parse("127.0.0.1"); Console.Out.WriteLine("Choose a port to bind..."); String port = Console.In.ReadLine(); int iPort = Int32.Parse(port); TcpListener myList = new TcpListener(ipAd, iPort); myList.Start(); Console.WriteLine("The server is running at: "+myList.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); Socket s = myList.AcceptSocket(); Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); ``` client: ``` Console.Out.WriteLine("enter address: "); string address = Console.In.ReadLine(); Console.Out.WriteLine("enter port: "); int port = Convert.ToInt32(Console.In.ReadLine()); TcpClient tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); Console.Out.WriteLine("Address: " + address + ":" + port); tcpclnt.Connect(address, port); ``` I am able to ping the server from the client machine, however I am unable to telnet to the server using the bound port. I've tried a variety of ports (a few in the low 8000s and a few up around 40000). I have disable windows firewall on both systems. The systems are connected to a router which is not on the internet. I've tried with and without port forwarding set to forward incoming requests on the given port to the server machine with no effect. The only exception that I've been able to trap is thrown by the client: > No connection could be made because > the target machine actively refuses > it. I checked for an `InnerException` but it seems that there are none - that is the base exception. Could that be right? Not sure what else I should be looking at - any additional troubleshooting steps would be helpful. Thanks!
The code above is listening to request coming from the loopback address. This will effectively only listen to connection on that network, and that network only includes your machine. Have you tried listening to the address bound to the network from which the connection should be coming? On a local network it should be something like 192.168.x.x or 10.x.x.x
I've run into this before. The trick is to bind to `0.0.0.0` rather than `127.0.0.1`. When you bind to `127.0.0.1` the server will only accept connections from localhost. Binding to `0.0.0.0` it will accept all requests. You also may want to [nmap](http://nmap.org/download.html) the host machine from the client and see what ports it sees as being open. **EDIT:** If you hard code the IP address of the machine in it the listener will only listen on that network interface. If you use `0.0.0.0` the listener will listen on all available network interfaces. This includes interfaces between your computer and a USB attached hand held device, a second network card or a VPN link.
No connection could be made because the target machine actively refuses it
[ "", "c#", ".net", "tcp", "tcpclient", "tcplistener", "" ]
After doing a quick search I can't find the answer to this seemingly simple thing to do. **How do I Manually Select An Item in an Asp.Net ListView?** I have a SelectedItemTemplate, but I don't want to use an asp:button or asp:LinkButton to select an item. I want it to be done from a URL. Like a QueryString, for example. The way I imagine would be on ItemDataBound, check a condition and then set it to selected if true, but how do I do this? **For example:** ``` protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e) { using (ListViewDataItem dataItem = (ListViewDataItem)e.Item) { if (dataItem != null) { if( /* item select condition */ ) { // What do I do here to Set this Item to be Selected? // edit: Here's the solution I'm using : ((ListView)sender).SelectedIndex = dataItem.DisplayIndex; // Note, I get here and it gets set // but the SelectedItemTemplate isn't applied!!! } } } } ``` I'm sure it's one or two lines of code. **EDIT:** I've updated the code to reflect the solution, and it seems that I can select the ListView's SelectedItemIndex, however, it's not actually rendering the SelectedItemTemplate. I don't know if I should be doing this in the ItemDataBound event **as suggested below**.
I looked at some of what's going on in ListView under the hood and think this is probably the best approach. ``` void listView_ItemCreated(object sender, ListViewItemEventArgs e) { // exit if we have already selected an item; This is mainly helpful for // postbacks, and will also serve to stop processing once we've found our // key; Optionally we could remove the ItemCreated event from the ListView // here instead of just returning. if ( listView.SelectedIndex > -1 ) return; ListViewDataItem item = e.Item as ListViewDataItem; // check to see if the item is the one we want to select (arbitrary) just return true if you want it selected if (DoSelectDataItem(item)==true) { // setting the SelectedIndex is all we really need to do unless // we want to change the template the item will use to render; listView.SelectedIndex = item.DisplayIndex; if ( listView.SelectedItemTemplate != null ) { // Unfortunately ListView has already a selected a template to use; // so clear that out e.Item.Controls.Clear(); // intantiate the SelectedItemTemplate in our item; // ListView will DataBind it for us later after ItemCreated has finished! listView.SelectedItemTemplate.InstantiateIn(e.Item); } } } bool DoSelectDataItem(ListViewDataItem item) { return item.DisplayIndex == 0; // selects the first item in the list (this is just an example after all; keeping it simple :D ) } ``` **NOTES** * ListView selects the template an item will use after it's DataBinding event fires. So if the SelectedIndex is set before then, no more work is necessary * Setting the SelectedIndex anywhere after DataBinding works, you just don't get the SelectedItemTemplate. For that you have either rebind the data; or reinstantiate the SelectedItemTemplate on the ListViewItem. *be sure to clear the ListViewItem.Controls collection first!* **UPDATE** I have removed most of my original solution, since this should work better and for more cases.
You can set the ListViews SelectedIndex ``` list.SelectedIndex = dataItem.DisplayIndex; // don't know which index you need list.SelectedIndex = dataItem.DataItemIndex; ``` ## Update If your loading the data on page load you may have to traverse the data to find the index then set the SelectedIndex value before calling the DataBind() method. ``` public void Page_Load(object sender, EventArgs e) { var myData = MyDataSource.GetPeople(); list.DataSource = myData; list.SelectedIndex = myData.FirstIndexOf(p => p.Name.Equals("Bob", StringComparison.InvariantCultureIgnoreCase)); list.DataBind(); } public static class EnumerableExtensions { public static int FirstIndexOf<T>(this IEnumerable<T> source, Predicate<T> predicate) { int count = 0; foreach(var item in source) { if (predicate(item)) return count; count++; } return -1; } } ```
Programmatically Select Item in Asp.Net ListView
[ "", "c#", "asp.net", "listview", "listviewitem", "selecteditemtemplate", "" ]
I have implemented the "MOD 10" check digit algorithm using SQL, for the US Postal Service Address Change Service Keyline according to the method in their document, but it seems I'm getting the wrong numbers! Our input strings have only numbers in them, making the calculation a little easier. When I compare my results with the results from their testing application, I get different numbers. I don't understand what is going on? Does anyone see anything wrong with my algorithm? It's got to be something obvious... The documentation for the method can be found on page 12-13 of this document: <http://www.usps.com/cpim/ftp/pubs/pub8a.pdf> The sample application can be found at: <http://ribbs.usps.gov/acs/documents/tech_guides/KEYLINE.EXE> **PLEASE NOTE: I fixed the code below, based on the help from forum users. This is so that future readers will be able to use the code in its entirety.** ``` ALTER function [dbo].[udf_create_acs] (@MasterCustomerId varchar(26)) returns varchar(30) as begin --this implements the "mod 10" check digit calculation --for the US Postal Service ACS function, from "Publication 8A" --found at "http://www.usps.com/cpim/ftp/pubs/pub8a.pdf" declare @result varchar(30) declare @current_char int declare @char_positions_odd varchar(10) declare @char_positions_even varchar(10) declare @total_value int declare @check_digit varchar(1) --These strings represent the pre-calculated values of each character --Example: '7' in an odd position in the input becomes 14, which is 1+4=5 -- so the '7' is in position 5 in the string - zero-indexed set @char_positions_odd = '0516273849' set @char_positions_even = '0123456789' set @total_value = 0 set @current_char = 1 --stepping through the string one character at a time while (@current_char <= len(@MasterCustomerId)) begin --this is the calculation for the character's weighted value if (@current_char % 2 = 0) begin --it is an even position, so just add the digit's value set @total_value = @total_value + convert(int, substring(@MasterCustomerId, @current_char, 1)) end else begin --it is an odd position, so add the pre-calculated value for the digit set @total_value = @total_value + (charindex(substring(@MasterCustomerId, @current_char, 1), @char_positions_odd) - 1) end set @current_char = @current_char + 1 end --find the check digit (character) using the formula in the USPS document set @check_digit = convert(varchar,(10 - (@total_value % 10)) % 10) set @result = '#' + @MasterCustomerId + ' ' + @check_digit + '#' return @result end ```
``` set @check_digit = convert(varchar, (10 - (@total_value % 10)) % 10) ```
I'm not sure why you're messing with the whole string representations when you're working in a set-based language. I'd probably do it like below. I ran four tests through and they were all successful. You can expand this easily to handle characters as well and you could even make the table permanent if you really wanted to do that. ``` CREATE FUNCTION dbo.Get_Mod10 ( @original_string VARCHAR(26) ) RETURNS VARCHAR(30) AS BEGIN DECLARE @value_mapping TABLE (original_char CHAR(1) NOT NULL, odd_value TINYINT NOT NULL, even_value TINYINT NOT NULL) INSERT INTO @value_mapping ( original_char, odd_value, even_value ) SELECT '0', 0, 0 UNION SELECT '1', 2, 1 UNION SELECT '2', 4, 2 UNION SELECT '3', 6, 3 UNION SELECT '4', 8, 4 UNION SELECT '5', 1, 5 UNION SELECT '6', 3, 6 UNION SELECT '7', 5, 7 UNION SELECT '8', 7, 8 UNION SELECT '9', 9, 9 DECLARE @i INT, @clean_string VARCHAR(26), @len_string TINYINT, @sum SMALLINT SET @clean_string = REPLACE(@original_string, ' ', '') SET @len_string = LEN(@clean_string) SET @i = 1 SET @sum = 0 WHILE (@i <= @len_string) BEGIN SELECT @sum = @sum + CASE WHEN @i % 2 = 0 THEN even_value ELSE odd_value END FROM @value_mapping WHERE original_char = SUBSTRING(@clean_string, @i, 1) SET @i = @i + 1 END RETURN (10 - (@sum % 10)) % 10 END GO ```
USPS ACS Keyline Check Digit
[ "", "sql", "usps", "check-digit", "" ]
I'm trying to send faxes with a .NET (C#) program using Crystal Reports and Unimessage Pro (or any other fax program). My problem is that Unimessage Pro (and other fax programs) uses printer fonts for the fax commands. Since .NET doesn't support printer fonts the fax commands in the report are converted to Courier New. The result of this is that the fax program doesn't recognize the fax commands but sees them as plain text and the fax isn't sent. How do I send a fax with Crystal Reports and .NET?
I got this answer from WordCraft (company behind Unimessage Pro) > 1. Create a file named WilCapAX.INI in the main Windows folder, e.g. > C:\Windows\WilCapAX.INI The file > should contain the following: > [WilCapAX] > Commands=C:\Commands.DAT Where "C:\Commands.DAT" is the name of > a text file you are going to create > in your .NET application to pass the > embedded commands to Unimessage Pro. > You can edit the path if necessary, > but keep to short form file and > folder names. > 2. In your .NET application when you have something to send via > Unimessage Pro you then need to: > > 2.1 Create a text file named, depending on the name defined > in WilCapAX.INI, C:\Commands.DAT containing: > > ``` > BLANK LINE > [[TO=Fax Number or Email address]] > [[SUBJECT=Whatever you want the subject to be]] > ``` > > The first line of the file must either be blank or contain > something other than an embedded command - it will be > skipped. The other lines in the C:\Commands.DAT file > should each contain an embedded command. > > 2.2 Print ONE message to the Unimessage Pro printer - the > Unimessage Pro printer accept the print job and will > look for the file specified in WilCapAX.INI. If the > file specified in WilCapAX.INI (C:\Commands.DAT) is > found, embedded commands are extracted from it and > then the "C:\Commands.DAT" file is deleted and the > print capture processed together with the command > extracted from the C:\Commands.DAT file. > > 2.3 Wait for the C:\Commands.DAT file to disappear > (indicating that it has been processed by the > Unimessage Pro printer) and then repeat as necessary. This solved the problem! :)
Joyfax Client Console 1.0 (beta) Note: Please lanuch Joyfax Client v5.2 or above before runnig this application. JoyfaxConsole [Options] -f [;...][;FileN] -r "" ``` -f file or folder Files or files in sub folders to be faxed. i.e: C:\Test\;C:\MyPDFs\*.pdf -r Recipients Recipient list. For more see Fax Recipients. Must begin and end with double quotation marks("). ``` Options: ``` -a Synchronous Wait until fax sent completed; -s Subject Subject of fax, i.e.: "Joyfax Sell Sheet"; -m Meno Memo of fax, i.e.: "Joyfax Server 5-user license"; -c CoverPage Cover Page profile to be used; -d Header Header & footer profile to be used, 0 = None; 1 = General; 2 = Compact; 3 = Detailed -k Kill Delete input files if fax sent successfully. ``` Retrun: ``` 0 - Success; 1 - Initialize failed; 2 - Invalid parameter; 3 - Unknown erorr (may unsupported file type). ``` Example: > JoyfaxClientConsole -d 2 -f "C:\My PDFs\D90.PDF" -r "Samm > Kivin<866-6554-564>;Mr. Green<(846)6554-564>" > > JoyfaxClientConsole -f C:\MyPDFs\*.pdf;D:\Sell.xls -r "Samm > Kivin<866-6554-564>" > > JoyfaxClientConsole -s "Joyfax Sell Sheet" -m "Joyfax Server 5-user > license" -f D:\Sell.xls -r "Kivin<866-6554-564>"
Sending fax with .NET
[ "", "c#", "crystal-reports", "fonts", "printing", "fax", "" ]
I want to use a Java file `SaveProp` which is written in a package `user`. The class file has been placed in `WEBINF/classes`. Below are the two lines which cause the issue. ``` jsp:useBean id="user" class="user.SaveProp" scope="session" jsp:setProperty name="user" property="*" ``` It throws: ``` The value for the useBean class attribute user.SaveProp is invalid ``` I'm using Tomcat 6.0.
You should put the file under WEBINF/classes/user
3 things 1. Make sure the class file is under WEBINF/classes/user 2. Make sure there is a public default constructor without arguments 3. You can also use type= instead of class= if the bean already exists in the scope
The value for the useBean class attribute ... is invalid
[ "", "java", "jsp", "tomcat", "properties", "" ]
I'm developing a Swing application and I need to flash the Windows taskbar. I can't use `frame.requestFocus()` because I don't want to steal focus from any other application.
I don't know if it applies to newer versions of Windows, but the .toFront() method used to flash the window if none of the current VM's windows were in the foreground. This means that calling frame.toFront() on a minimized frame would always make it flash...
[JNIWrapper with its winpack extension](http://www.teamdev.com/jniwrapper/winpack/) can do what you want. The Demo on the site shows it in action.
How can I flash the Windows taskbar using Swing?
[ "", "java", "swing", "taskbar", "" ]
I am playing with LINQ to learn about it, but I can't figure out how to use [`Distinct`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct) when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use `Distinct` on a `List<TElement>` on *one* or *more* properties of the `TElement`? Example: If an object is `Person`, with property `Id`. How can I get all `Person` and use `Distinct` on them with the property `Id` of the object? ``` Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1" Person3: Id=2, Name="Test2" ``` How can I get just `Person1` and `Person3`? Is that possible? If it's not possible with LINQ, what would be the best way to have a list of `Person` depending on some of its properties?
**EDIT**: This is now part of [MoreLINQ](https://github.com/morelinq/MoreLINQ). What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write: ``` public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } ``` So to find the distinct values using just the `Id` property, you could use: ``` var query = people.DistinctBy(p => p.Id); ``` And to use multiple properties, you can use anonymous types, which implement equality appropriately: ``` var query = people.DistinctBy(p => new { p.Id, p.Name }); ``` Untested, but it should work (and it now at least compiles). It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the `HashSet` constructor.
> What if I want to obtain a distinct list based on *one* or *more* properties? Simple! You want to group them and pick a winner out of the group. ``` List<Person> distinctPeople = allPeople .GroupBy(p => p.PersonId) .Select(g => g.First()) .ToList(); ``` If you want to define groups on multiple properties, here's how: ``` List<Person> distinctPeople = allPeople .GroupBy(p => new {p.PersonId, p.FavoriteColor} ) .Select(g => g.First()) .ToList(); ``` Note: Certain query providers are unable to resolve that each group must have at least one element, and that First is the appropriate method to call in that situation. If you find yourself working with such a query provider, FirstOrDefault may help get your query through the query provider. Note2: Consider this answer for an EF Core (prior to EF Core 6) compatible approach. <https://stackoverflow.com/a/66529949/8155>
LINQ's Distinct() on a particular property
[ "", "c#", "linq", "duplicates", "unique", "distinct", "" ]
Can an HTML canvas tag be positioned over other html content on a page? For example, will something the following CSS declaration make a canvas tag do what I expect it to? ``` canvas.mycanvas { position: absolute; background: transparent; z-index: 10; top: 10px; left: 10px; } ```
Yes, this works fine in canvas-supporting browsers, and furthermore works equally as well in IE6 and IE7 using the exCanvas project which translate canvas commands into Microsoft's XML-based vector language, VML. One thing I noticed when attempting to overlay canvas elements across-browsers is that you have to be especially careful with the order in which you append and subsequently access any canvas child DOM nodes. IE needs the item to be appended before you can work with it.
That should work perfectly. There's no need to set the background to 'transparent' though. Overlaying a canvas is how [this bookmarklet](http://www.westciv.com/mri/) works.
Can canvas tag be used to draw on top of other items on a page?
[ "", "javascript", "html", "canvas", "" ]
I'm currently investigating how to use the RMI distribution option in ehcache. I've configured properly ehcache.xml and replication seems to work fine. However I've 2 questions: -> It seems ehcache/ hibernate creates 1 cache per Entity. This is fine, however when replication is in place it create 1 thread / cache to replicate. Is this the intended behavious ? As our domain is big, it creates about 300 threads, which seems to me really big -> Another nasty consequence is that the heartbeat messagre seems to aggregate all of those cache names. From what I saw the message should fit in 1500 bytes, which it does not, which leads to this message in my logs: Heartbeat is not working. Configure fewer caches for replication. Size is 1747 but should be no greater than1500. Any idea on how this could be changed ? Thanks a lot for your help
We already have one hack where we have our own custom copy of the hibernate EhCacheProvider that overrides buildCache() to create our own Cache objects with shortened names (the hash of the name). This gets around the 1500 limit. We keep a hashmap of the original names with the hash names for reverse lookup. We did this a while ago and have been using it in production. We also looked at your other issue to have a single replicator thread. First we copied RMICacheReplicatorFactory and changed createCacheEventListener() to return our copy of RMIAsynchronousCacheReplicator that we modified by making the replicationThread field static and then making the necassary fixes for that. We didn't get around to testing it thoroughly or putting it in production, but are looking at it again which is how I found this post :)
Did you consider JBossCache as an alternative to EHcache? JBossCache has distributed transactions and is well-tested for high-loads. It has lower-level replication mechanisms which can allow you to use UDP or TCP multicasting/broadcasting replication.
Ehcache / Hibernate and RMI replication with large number of entities
[ "", "java", "hibernate", "replication", "ehcache", "" ]
Microsoft make this piece of software called "Visual Studio 2008 Professional". I have found that there doesn't appear to be an application performance profiler or something similar in it, making it seem not so "professional" to me. If Microsoft don't include a profiler, what are your third party options for time profiling for Visual Studio 2008? Free would be preferable, as this is for uni student purposes :P
Personally, I use the Red Gate profiler. Others swear by the JetBrains one. Those seem to be the options, and there isn't much between them.
There are a couple of free profilers, not as complete or polished as the commercial ones, but they can definately help a lot: [Eqatec](http://www.eqatec.com/tools/profiler?gclid=CM_xvqDx7ZgCFRxNagod_Xic1Q) - This was designed for Windows CE, but works just fine for normal applications. [Soft Prodigy Profile Sharp](http://www.softprodigy.net/products) - This is actually an open source project written in c#, so you can tinker with it if you want.
How To Do Performance Profiling in Visual Studio 2008 "Pro"
[ "", "c#", "visual-studio", "visual-studio-2008", "performance", "profiling", "" ]
I have a JEditorPane created by this way: ``` JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>"); ``` I put this pane on a JFrame. Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)
You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps: ``` import java.io.IOException; import javax.swing.JEditorPane; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) throws Exception { Test.createAndShowGUI(); } private static void createAndShowGUI() throws IOException { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String imgsrc = Test.class.getClassLoader().getSystemResource("a.jpg").toString(); frame.getContentPane().add(new JEditorPane("text/html", "<html><img src='"+imgsrc+"' width=200height=200></img>")); frame.pack(); frame.setVisible(true); } } ```
The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory. Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.
showing images on jeditorpane (java swing)
[ "", "java", "image", "swing", "jeditorpane", "" ]
I'm trying to send a POST request to a simple WCF service I wrote, but I keep getting a 400 Bad Request. I'm trying to send JSON data to the service. Can anyone spot what I'm doing wrong? :-) This is my service interface: ``` public interface Itestservice { [OperationContract] [WebInvoke( Method = "POST", UriTemplate = "/create", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] String Create(TestData testData); } ``` The implementation: ``` public class testservice: Itestservice { public String Create(TestData testData) { return "Hello, your test data is " + testData.SomeData; } } ``` The DataContract: ``` [DataContract] public class TestData { [DataMember] public String SomeData { get; set; } } ``` And finally my client code: ``` private static void TestCreatePost() { Console.WriteLine("testservice.svc/create POST:"); Console.WriteLine("-----------------------"); Uri address = new Uri("http://localhost:" + PORT + "/testweb/testservice.svc/create"); // Create the web request HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; // Set type to POST request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //request.ContentType = "text/x-json"; // Create the data we want to send string data = "{\"SomeData\":\"someTestData\"}"; // Create a byte array of the data we want to send byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); // Set the content length in the request headers request.ContentLength = byteData.Length; // Write data using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output Console.WriteLine(reader.ReadToEnd()); } Console.WriteLine(); Console.WriteLine(); } ``` Can anyone think of what I might be doing wrong? As you can see in the C# client I've tried both application/x-www-form-urlencoded and text/x-json for ContentType, thinking that might have something to do with it, but it doesn't seem to. I've tried a GET version of this same service and it works fine, and returns a JSON version of TestData with no problem. But for POST, well, I'm pretty stuck at the moment on this :-(
Have you tried "application/json" instead of "text/x-json". According to [this](https://stackoverflow.com/questions/477816/the-right-json-content-type) Stack Overflow question application/json is the only valid json media type.
The only problem here is the ContentType. try ( recommended ) ``` request.ContentType = "application/json; charset=utf-8"; ``` or ( this will work too ) ``` request.ContentType = "text/json; charset=utf-8"; ``` Both of above solve the problem. However, the first one is recommended, for details of JSON-RPC 1.1 Specification check out [http://json-rpc.org](http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html#ResponseHeaders)
Why does my C# client, POSTing to my WCF REST service, return (400) Bad Request?
[ "", "c#", "wcf", "rest", "post", "" ]
Please share your favorite application design / design patterns for use in PHP with me. Some things I'd like to know: * How your folders are designed * How you use object oritentation in your PHP applications * Do you have a standard way of dealing with CRUD, pagination, or any other common tasks? * How do you avoid using repetitive code? What's your approach to libraries/sharing common code, etc? * What are ways in which you can make your code more elegant? You don't have to answer all of these, answering any or a few of these will be helpful. The reason I'm asking this,is because I'm very tired of writing repetitive, ugly code in PHP and I want to make a small framework for my freelancing projects which will make programming easier and let me focus on the challenging/business tasks rather than form validation, pagination, and the other mundane activities which make up 80% of programming work in PHP All opinions appreciated!
I might get voted down for this, but if you really do want to write your own framework, I say go for it because you will learn a lot from the experience. The other frameworks mentioned here are great and tested and you wouldn't be making a bad decision using them, but it's your choice. Before starting to write your framework, look at the other frameworks (at their syntax, directory structure, naming schema, design patterns, etc) and try to figure out why they did what they did and what, if anything, you would do differently. Try out a few tutorials and play with their code, make a few sample apps. If, after doing that, you don't like using them, then go ahead and start planning your framework, keeping what worked and improving what didn't. If you do decide to roll your own, here are a few things I would recommend from my own experience: * **Make Security Your Top Priority** - If you write a data access layer, use bound parameters. If you write a form class, guard against CSRF and XSS. Catch your exceptions and handle your errors. Make sure that your PHP environment is secure. Don't try coming up with your own encryption algorithm. If you don't concentrate on security, it's not worth writing your own framework. * **Comment Your Code** - You will need comments to help you remember how your code works after a while. I usually find that docblock comments are more than enough. Beyond that, comment why you did something, not what you did. If you need to explain what, you may want to refactor. * **Single Responsibility Classes and Methods** - Most of your classes and methods should do one thing and only one thing. Especially watch out for this with the database - Your pagination class shouldn't rely on your data access object, nor should almost any other (low-level) class. * **Unit Test** - If each of your methods does only one thing, it should be far easier to test them and it will result in better code. Write the test first, then the code to pass the test. This will also give you greater freedom to refactor later on without breaking something. * **Abstract Similar Classes** - If you have more than one class that does similar things, create a parent class that uses the similarities between the classes and extend it. * **Delegate and Modularize** - If you're writing a validation system (and chances are you probably would), don't include each validator as a method in some super validation class. Separate them into individual classes and call them as needed. This can be applied in many areas: filters, languages, algorithms, validators, and so on. * **Protect and Privatize** - In most cases, it's better to use getter and setter methods rather than allowing direct access to class variables. * **Consistent API** - If you have a render() method and a draw() method that do the same things in different classes, pick one and go with it across all classes. Keep the order of the parameters the same for methods that use the same parameters. A consistent API is an easier API. * **Remember Autoloading** - The class names can get a little clunky and long, but the way Zend names the classes and organizes the directories makes autoloading a lot easier. **Update**: As of PHP 5.3, you should begin using namespaces. * **Never echo or print anything** - Give it as a return value and let the user decide if it should be echoed. A lot of times you'll use the return value as a parameter for another method. * **Don't Try to Solve the World's Problems** - Solve your own first. If you don't need a feature right now, like a class for localizing numbers or dates or currency, don't write it. Wait until you need it. * **Don't Preoptimize** - Build a few simple applications with your framework before fine tuning it. Otherwise, you can spend a lot of time on nothing productive. * **Use Source Control** - If you spend countless hours creating a masterpiece, don't risk it getting lost.
I have to agree with the above posters. If you're not using a framework when programming in PHP you're really programming with your hands tied behind your back. I personally recommend [CodeIgniter](http://codeigniter.com). It's the fastest framework around, it's very easy to learn, and has a very active community. All of your questions will be answered by the framework: ``` * How your folders are designed ``` CodeIgniter (or any framework for that matter) separates your logic into views, models, and controllers, each with their own folder. ``` * Do you have a standard way of dealing with CRUD, pagination, or any other common tasks? ``` CI has a pagination library, and it has 3rd party libraries like DataMapper for wrapping your CRUD calls in an object oriented way (ORM). ``` * What are ways in which you can make your code more elegant? ``` The seperation of the model, view, and controller make for very elegant code. (The 2 questions I didn't answer are pretty much implied when using the framework)
What PHP application design/design patterns do you use?
[ "", "php", "oop", "software-design", "" ]
Having this table ``` Table "Items" itemID itemTitle itemContent ``` and this ``` Table "MyList" userID itemID deleted ``` how can I select all rows from table "Items" and showing the field "deleted", even if the itemID do not exist in "MyList", given an userID? Example of the query result: ``` itemID | itemTitle | deleted | userID ------------------------------------- 1 | Title1 | 1 | 2 2 | Title2 | 0 | 2 3 | Title3 | (null) | (null) 4 | Title4 | (null) | (null) ``` What would be the query, so that I can get that result? Thanks
I'm not sure if this is the best way of doing this, but it returns what I was looking for: ``` select itemID, itemTitle, deleted, userID FROM( SELECT i.id_itemID, i.itemTitle, M.deleted, M.userID FROM MyList M right OUTER JOIN Items I ON I.itemID= M.itemID ) as MyTableItems where itemID = 3 or itemID is null ```
``` SELECT I.itemID, I.itemTitle, M.deleted FROM Items I LEFT OUTER JOIN MyList M ON M.itemID = I.itemID WHERE M.userID = 9 ``` **Edit:** Based on OP's comment: ``` SELECT I.itemID, I.itemTitle, M.deleted, M.userID FROM MyList M LEFT OUTER JOIN Items I ON I.itemID = M.itemID WHERE M.userID = 9 ```
SQL - Select rows from two different tables
[ "", "sql", "mysql", "" ]
I remember looking at a couple information visualizations tool a while back. One was written in flash and the other in Javascript. They both allowed you put notes in "bubbles" and then link them to other "bubbles". Clicking on an existing bubble brought it to the front and rearranged others around it. The JS one was particularly interesting as it worked as a standalone app on your local file system. Now i cant remember the magical google words to find them. Does any know of the tools i am talking about or know what this form of information diagramming is called? Thanks Simon
I know [Flare](http://flare.prefuse.org/) for data visualization in Flash. It's adapted from [Prefuse](http://prefuse.org/), a data visualization toolkit for Java.
This sounds like it <http://phasetwo.org/post/a-better-tag-cloud.html>
Suggestions for information visualization using flash or javascript
[ "", "javascript", "flash", "visualization", "diagram", "" ]
I have a problematic situation with some quite advanced unit tests (using PowerMock for mocking and JUnit 4.5). Without going into too much detail, the first test case of a test class will always succeed, but any following test cases in the same test class fails. However, if I select to only run test case 5 out of 10, for example, it will pass. So all tests pass when being run individually. Is there any way to force JUnit to run one test case at a time? I call JUnit from an ant-script. I am aware of the problem of dependant test cases, but I can't pinpoint why this is. There are no saved variables across the test cases, so nothing to do at @Before annotation. That's why I'm looking for an emergency solution like forcing JUnit to run tests individually.
Your problem is not that JUnit runs all the tests at once, you problem is that you don't see *why* a test fails. Solutions: 1. Add more asserts to the tests to make sure that every variable actually contains what you think 2. Download an IDE from the Internet and use the built-in debugger to look at the various variables 3. Dump the state of your objects just before the point where the test fails. 4. Use the "message" part of the asserts to output more information why it fails (see below) 5. Disable all but a handful of tests (in JUnit 3: replace all strings "void test" with "void dtest" in your source; in JUnit 4: Replace "@Test" with "//D@TEST"). Example: ``` assertEquals(list.toString(), 5, list.size()); ```
I am aware of all the recommendations, but to finally answer your question here is a simple way to achieve what you want. Just put this code inside your test case: ``` Lock sequential = new ReentrantLock(); @Override protected void setUp() throws Exception { super.setUp(); sequential.lock(); } @Override protected void tearDown() throws Exception { sequential.unlock(); super.tearDown(); } ``` With this, no test can start until the lock is acquired, and only one lock can be acquired at a time.
Force JUnit to run one test case at a time
[ "", "java", "unit-testing", "testing", "ant", "junit", "" ]
For some of the apps I've developed (then proceeded to forget about), I've been writing plain SQL, primarily for MySQL. Though I have used ORMs in python like [SQLAlchemy](http://www.sqlalchemy.org/), I didn't stick with them for long. Usually it was either the documentation or complexity (from my point of view) holding me back. I see it like this: use an ORM for portability, plain SQL if it's just going to be using one type of database. I'm really looking for advice on when to use an ORM or SQL when developing an app that needs database support. Thinking about it, it would be far better to just use a lightweight wrapper to handle database inconsistencies vs. using an ORM.
ORMs have some nice features. They can handle much of the dog-work of copying database columns to object fields. They usually handle converting the language's date and time types to the appropriate database type. They generally handle one-to-many relationships pretty elegantly as well by instantiating nested objects. I've found if you design your database with the strengths and weaknesses of the ORM in mind, it saves a lot of work in getting data in and out of the database. (You'll want to know how it handles polymorphism and many-to-many relationships if you need to map those. It's these two domains that provide most of the 'impedance mismatch' that makes some call ORM the 'vietnam of computer science'.) For applications that are transactional, i.e. you make a request, get some objects, traverse them to get some data and render it on a Web page, the performance tax is small, and in many cases ORM can be faster because it will cache objects it's seen before, that otherwise would have queried the database multiple times. For applications that are reporting-heavy, or deal with a large number of database rows per request, the ORM tax is much heavier, and the caching that they do turns into a big, useless memory-hogging burden. In that case, simple SQL mapping (LinQ or iBatis) or hand-coded SQL queries in a thin DAL is the way to go. I've found for any large-scale application you'll find yourself using both approaches. (ORM for straightforward CRUD and SQL/thin DAL for reporting).
Speaking as someone who spent quite a bit of time working with JPA (Java Persistence API, basically the standardized ORM API for Java/J2EE/EJB), which includes Hibernate, EclipseLink, Toplink, OpenJPA and others, I'll share some of my observations. 1. ORMs are not fast. They can be adequate and most of the time adequate is OK but in a high-volume low-latency environment they're a no-no; 2. In general purpose programming languages like Java and C# you need an awful lot of magic to make them work (eg load-time weaving in Java, instrumentation, etc); 3. When using an ORM, rather than getting further from SQL (which seems to be the intent), you'll be amazed how much time you spend tweaking XML and/or annotations/attributes to get your ORM to generate performant SQL; 4. For complex queries, there really is no substitute. Like in JPA there are some queries that simply aren't possible that are in raw SQL and when you have to use raw SQL in JPA it's not pretty (C#/.Net at least has dynamic types--var--which is a lot nicer than an Object array); 5. There are an awful lot of "gotchas" when using ORMs. This includes unintended or unexpected behavior, the fact that you have to build in the capability to do SQL updates to your database (by using refresh() in JPA or similar methods because JPA by default caches everything so it won't catch a direct database update--running direct SQL updates is a common production support activity); 6. The object-relational mismatch is always going to cause problems. With any such problem there is a tradeoff between complexity and completeness of the abstraction. At times I felt JPA went too far and hit a real law of diminishing returns where the complexity hit wasn't justified by the abstraction. There's another problem which takes a bit more explanation. The traditional model for a Web application is to have a persistence layer and a presentation layer (possibly with a services or other layers in between but these are the important two for this discussion). ORMs force a rigid view from your persistence layer up to the presentation layer (ie your entities). One of the criticisms of more raw SQL methods is that you end up with all these VOs (value objects) or DTOs (data transfer objects) that are used by simply one query. This is touted as an advantage of ORMs because you get rid of that. Thing is those problems don't go away with ORMs, they simply move up to the presentation layer. Instead of creating VOs/DTOs for queries, you create custom presentation objects, typically one for every view. How is this better? IMHO it isn't. I've written about this in [ORM or SQL: Are we there yet?](https://web.archive.org/web/20090528082618/http://www.cforcoding.com/2009/05/orm-or-sql.html). My persistence technology of choice (in Java) these days is ibatis. It's a pretty thin wrapper around SQL that does 90%+ of what JPA can do (it can even do lazy-loading of relationships although its not well-documented) but with far less overhead (in terms of complexity and actual code). This came up last year in a GWT application I was writing. Lots of translation from EclipseLink to presentation objects in the service implementation. If we were using ibatis it would've been far simpler to create the appropriate objects with ibatis and then pass them all the way up and down the stack. Some purists might argue this is Bad™. Maybe so (in theory) but I tell you what: it would've led to simpler code, a simpler stack and more productivity.
Using an ORM or plain SQL?
[ "", "sql", "language-agnostic", "orm", "" ]
I've been using this pattern when I need to control how long various async operations take. I don't mean specifically for WebRequest (I know you can set the timeout property), I just used this as an example for the pattern. ``` var request = WebRequest.Create(someUri); WebResponse response = null; request.BeginGetResponse(result => { var asyncRequest = (WebRequest)result.AsyncState; response = asyncRequest.EndGetResponse(result); }, request); DateTime timeout = DateTime.Now.AddSeconds(10); while (response == null && DateTime.Now <= timeout) { Thread.Sleep(0); } if (response == null) throw new Exception("Timeout!"); ``` Anywhere I read about Thread.Sleep(), I heard it's a baaaad thing to do, but I don't really think this use case abuses it. I know it is possible that it could be a little bit more than exactly 10 seconds, but that isn't important to me. So, is this *truly* a bad way to accomplish what I'm accomplishing, and if so, what is a better way to do it? EDIT: Perhaps I should clarify what I"m trying to accomplish. The purpose is to control the maximum amount of time spent waiting on a call. I'm aware that this defeats the purpose of an async call, but the intention was never to be asynchronous, I'm just using it as a means to control when I exit a call.
The WaitHandles wait methods supports time out, use that. Something like: ``` var asyncResult = request.BeginGetResponse(... asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10)) ```
Code looks perfectly fine too me. It's just a way to support `timeout` property on sync call if there's none in the api. Although I should say you'd better replace this waiting loop with some kind of `WaitHandle` class, it'll use less resources and I'm sure will look better. Sorry, can't provide the solution since I don't know C# and it's API that well.
How bad is this pattern?
[ "", "c#", "design-patterns", "asynchronous", "" ]
I realize this is kind of a goofy question, for lack of a better term. I'm just kind of looking for any outside idea on increasing the efficiency of this code, as it's bogging down the system very badly (it has to perform this function a lot) and I'm running low on ideas. What it's doing it loading two image containers (imgRGB for a full color img and imgBW for a b&w image) pixel-by-individual-pixel of an image that's stored in "unsigned char \*pImage". Both imgRGB and imgBW are containers for accessing individual pixels as necessary. ``` // input is in the form of an unsigned char // unsigned char *pImage for (int y=0; y < 640; y++) { for (int x=0; x < 480; x++) { imgRGB[y][x].blue = *pImage; pImage++; imgRGB[y][x].green = *pImage; imgBW[y][x] = *pImage; pImage++; imgRGB[y][x].red = *pImage; pImage++; } } ``` Like I said, I was just kind of looking for fresh input and ideas on better memory management and/or copy than this. Sometimes I look at my own code so much I get tunnel vision... a bit of a mental block. If anyone wants/needs more information, by all means let me know.
I think the array accesses (are they real array accesses or operator []?) are going to kill you. Each one represents a multiply. Basically, you want something like this: ``` for (int y=0; y < height; y++) { unsigned char *destBgr = imgRgb.GetScanline(y); // inline methods are better unsigned char *destBW = imgBW.GetScanline(y); for (int x=0; x < width; x++) { *destBgr++ = *pImage++; *destBW++ = *destBgr++ = *pImage++; // do this in one shot - don't double deref *destBgr++ = *pImage++; } } ``` This will do two multiplies per scanline. You code was doing 4 multiplies per PIXEL.
The obvious question is, do you need to copy the data in the first place? Can't you just define accessor functions to extract the R, G and B values for any given pixel from the original input array? If the image data is transient so you have to keep a copy of it, you could just make a raw copy of it without any reformatting, and again define accessors to index into each pixel/channel on that. Assuming the copy you outlined is necessary, unrolling the loop a few times may prove to help. I think the best approach will be to unroll the loop enough times to ensure that each iteration processes a chunk of data divisible by 4 bytes (so in each iteration, the loop can simply read a small number of ints, rather than a large number of chars) Of course this requires you to mask out bits of these ints when writing, but that's a fast operation, and most importantly, it is done in registers, without burdening the memory subsystem or the CPU cache: ``` // First, we need to treat the input image as an array of ints. This is a bit nasty and technically unportable, but you get the idea) unsigned int* img = reinterpret_cast<unsigned int*>(pImage); for (int y = 0; y < 640; ++y) { for (int x = 0; x < 480; x += 4) { // At the start of each iteration, read 3 ints. That's 12 bytes, enough to write exactly 4 pixels. unsigned int i0 = *img; unsigned int i1 = *(img+1); unsigned int i2 = *(img+2); img += 3; // This probably won't make a difference, but keeping a reference to the found pixel saves some typing, and it may assist the compiler in avoiding aliasing. ImgRGB& pix0 = imgRGB[y][x]; pix0.blue = i0 & 0xff; pix0.green = (i0 >> 8) & 0xff; pix0.red = (i0 >> 16) & 0xff; imgBW[y][x] = (i0 >> 8) & 0xff; ImgRGB& pix1 = imgRGB[y][x+1]; pix1.blue = (i0 >> 24) & 0xff; pix1.green = i1 & 0xff; pix1.red = (i0 >> 8) & 0xff; imgBW[y][x+1] = i1 & 0xff; ImgRGB& pix2 = imgRGB[y][x+2]; pix2.blue = (i1 >> 16) & 0xff; pix2.green = (i1 >> 24) & 0xff; pix2.red = i2 & 0xff; imgBW[y][x+2] = (i1 >> 24) & 0xff; ImgRGB& pix3 = imgRGB[y][x+3]; pix3.blue = (i2 >> 8) & 0xff; pix3.green = (i2 >> 16) & 0xff; pix3.red = (i2 >> 24) & 0xff; imgBW[y][x+3] = (i2 >> 16) & 0xff; } } ``` it is also very likely that you're better off filling a temporary ImgRGB value, and then writing that entire struct to memory at once, meaning that the first block would look like this instead: (the following blocks would be similar, of course) ``` ImgRGB& pix0 = imgRGB[y][x]; ImgRGB tmpPix0; tmpPix0.blue = i0 & 0xff; tmpPix0.green = (i0 >> 8) & 0xff; tmpPix0.red = (i0 >> 16) & 0xff; imgBW[y][x] = (i0 >> 8) & 0xff; pix0 = tmpPix0; ``` Depending on how clever the compiler is, this may cut down dramatically on the required number of reads. Assuming the original code is naively compiled (which is probably unlikely, but will serve as an example), this will get you from 3 reads and 4 writes per pixel (read RGB channel, and write RGB + BW) to 3/4 reads per pixel and 2 writes. (one write for the RGB struct, and one for the BW value) You could also accumulate the 4 writes to the BW image in a single int, and then write that in one go too, something like this: ``` bw |= (i0 >> 8) & 0xff; bw |= (i1 & 0xff) << 8; bw |= ((i1 >> 24) & 0xff) << 16; bw |= ((i2 >> 16) & 0xff) << 24; *(imgBW + y*480+x/4) = bw; // Assuming you can treat imgBW as an array of integers ``` This would cut down on the number of writes to 1.25 per pixel (1 per RGB struct, and 1 for every 4 BW values) Again, the benefit will probably be a lot smaller (or even nonexistent), but it may be worth a shot. Taking this a step further, the same could be done without too much trouble using the SSE instructions, allowing you to process 4 times as many values per iteration. (Assuming you're running on x86) Of course, an important disclaimer here is that the above *is* nonportable. The reinterpret\_cast is probably an academic point (it'll most likely work no matter what, especially if you can ensure that the original array is aligned on a 32-bit boundary, which will typically be the case for large allocations on all platforms) A bigger issue is that the bit-twiddling depends on the CPU's endianness. But in practice, this should work on x86. and with small changes, it should work on big-endian machines too. (modulo any bugs in my code, of course. I haven't tested or even compiled any of it ;)) But no matter how you solve it, you're going to see the biggest speed improvements from minimizing the number of reads and writes, and trying to accumulate as much data in the CPU's registers as possible. Read all you can in large chunks, like ints, reorder it in the registers (accumulate it into a number of ints, or write it into temporary instances of the RGB struct), and then write those combined value out to memory. Depending on how much you know about low-level optimizations, it may be surprising to you, but temporary variables are fine, while direct memory to memory access can be slow (for example your pointer dereferencing assigned directly into the array). The problem with this is that you may get more memory accesses than necessary, and it's harder for the compiler to guarantee that no aliasing will occur, and so it may be unable to reorder or combine the memory accesses. You're generally better off writing as much as you can early on (top of the loop), doing as much as possible in temporaries (because the compiler can keep everything in registers), and then write everything out at the end. That also gives the compiler as much leeway as possible to wait for the initially slow reads. Finally, adding a 4th dummy value to the RGB struct (so it has a total size of 32bit) will most likely help a lot too (because then writing such a struct is a single 32-bit write, which is simpler and more efficient than the current 24-bit) When deciding how much to unroll the loop (you could do the above twice or more in each iteration), keep in mind how many registers your CPU has. Spilling out into the cache will probably hurt you as there are plenty of memory accesses already, but on the other hand, unroll as much as you can afford given the number of registers available (the above uses 3 registers for keeping the input data, and one to accumulate the BW values. It may need one or two more to compute the necessary addresses, so on x86, doubling the above might be pushing it a bit (you have 8 registers total, and some of them have special meanings). On the other hand, modern CPU's do a lot to compensate for register pressure, by using a much larger number of registers behind the scenes, so further unrolling might still be a total performance win. As always, measure measure measure. It's impossible to say what's fast and what isn't until you've tested it. Another general point to keep in mind is that data dependencies are bad. This won't be a big deal as long as you're only dealing with integral values, but it still inhibits instruction reordering, and superscalar execution. In the above, I've tried to keep dependency chains as short as possible. Rather than continually incrementing the same pointer (which means that each increment is dependant on the previous one), adding a different offset to the same base address means that every address can be computed independently, again giving more freedom to the compiler to reorder and reschedule instructions.
Any way to make this relatively simple (nested for memory copy) C++ code more efficient?
[ "", "c++", "optimization", "image-processing", "memory-management", "" ]
I'm planning to work on some hobby Java projects. I've done some small-scale projects, so I'm familiar with the language itself and building a GUI with Swing. I'd like to make my work a little less ad-hoc and perhaps find some tools that might be useful out in the real world. NetBeans now comes bundled with the [Swing Application Framework](https://appframework.dev.java.net/servlets/ProjectMailingListList), which seems to be a very useful tool. It helps bridge the gulf between knowing how to create a JFrame and how to use one effectively in the context of a larger application. The problem being that there are large chunks of the API completely undocumented and there's virtually no documentation on how to use it. There are only two questions in the FAQ, the mailing lists are all but dead, and I can't even tell if the project is being actively developed or if it's been abandoned. I've managed to get up and running with it based largely on the [two-year-old JavaOne presentation](http://weblogs.java.net/blog/hansmuller/archive/ts-3492-final.pdf) posted on the project's home page. **Is there a better alternative?** Is another tool/library/API out there that does the same sort of thing in a slightly more newbie-friendly way? Note that I'm planning to develop desktop applications at the moment, and am not looking for J2EE frameworks like Spring and Hibernate.
The [basic principles](http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod) for creating a good desktop are the same for creating web or enterprise applications. So the core of Spring or other frameworks such as [OSGi](http://felix.apache.org/site/index.html) or [PicoContainer](http://www.picocontainer.org/) can easily be used outside of J2EE. For example, [Eclipse uses OSGi](http://wiki.eclipse.org/index.php/Rich_Client_Platform) as its internal framework. The original use of the Model-View-Presenter (MVC) pattern was for Smalltalk GUI widgets. In fact, for myself, I first found and worked with "IoC" frameworks (long before Spring) precisely because I was looking for a framework and organizing principles for desktop application development. *Update on RCP* I see some people are recommending Eclipse RCP or Netbeans. I've done quite a bit of Eclipse RCP development and for certain classes of applications, it's great. However, the learning curve is *very* steep and the feature set may be way more than you need. Keep that in mind for any framework you investigate.
For more complete frameworks: The NetBeans platform perhaps <http://www.netbeans.org/kb/trails/platform.html> Or the Eclipse RCP <http://www.eclipse.org/articles/Article-RCP-1/tutorial1.html>
Is there a better Java application framework than Swing?
[ "", "java", "saf", "" ]
Is c# compiled to machine code, or is it compiled into a platform independent intermediate code? I am looking at an app that needs to be ported to a single language, and we would like to port it to a portable/fast platform.
From what I understand, Java tends to be a little faster than C#, but not enough for it to really matter for most applications, while C# tends to require less memory. They tend to be good at similar types of applications when compared to other languages. They usually perform slower than C++, but in some applications they can be faster because of optimizations that the JIT compiler can make. They generally are an order of magnitude faster than languages that are normally purely interpreted, like Perl or Python. You specifically mentioned C#, but I bring up Java because it is better supported cross-platform, which you also specifically mention. Thanks to Mono, you can do C# developement cross-platform, which now apparently has support for windows forms. However, you may need to be careful if some of the team uses .Net and some of it uses Mono because Mono only supports up to C# 2.0 and Microsoft is currently working on version 4.0 and is fairly aggressive about pushing new features. Java has the exact opposite problem where Sun is very conservative about pushing new features, causing it to lack some of the nice features that C# has, like properties and closures.
It's both: it's compiled to intermediate code, deployed, and then compiled to machine code on the machine on which it's installed and/or run.
How fast is c#?
[ "", "c#", "performance", "" ]
As I understand it, an interface is Java is intended to enforce a design by laying out methods for classes implementing the interface to fill in. Is this the idea with a Ruby module also? I see that just like with Interfaces in Java, you can't instantiate a module in Ruby.
I think I'd equate a module to something more akin to an extension method in C#. You're adding functionality to an existing class that is actually defined elsewhere. There isn't an exact analog in either C# or Java, but I definitely wouldn't think of it as an interface because the implementation is derived as well as the interface.
The short answer is no. Here's the reasoning, a Java/C# interface defines the method signatures an implementing class will provide at minimum. Additionally: * With ruby modules there is no such contract because of the duck-typing. * Modules are just a way to extract out common functionality for easy re-use. The closest relation is C# extension methods, but those aren't an exact match since they exist in a static context. * Modules can add state to an existing class. * Modules can have static methods * Modules can act as namespaces Example: ``` module SimpleConversation class NamespacedExample def poke puts "ouch" end end attr_accessor :partner_name def converse partner_name ||= "Slowpoke" speak + "\n#{partner_name}: Yes they are" end def self.yay puts "yay" end end class Foo include SimpleConversation attr_accessor :name def speak name ||= "Speedy" "#{name}: tacos are yummy" end end x = Foo.new x.name = "Joe" x.partner_name = "Max" puts x.speak puts x.converse y = SimpleConversation::NamespacedExample.new y.poke SimpleConversation.yay ```
Is a Ruby module equivalent to a Java Interface?
[ "", "java", "ruby", "interface", "module", "" ]
Why can't you create a generic indexer in .NET? the following code throws a compiler error: ``` public T this<T>[string key] { get => /* Return generic type T. */ } ``` Does this mean you can't create a generic indexer for a generic member collection?
The only thing I can think of this can be used is something along these lines: ``` var settings = ConfigurationSection.AppSettings; var connectionString = settings<string>["connectionString"]; var timeout = settings<int>["timeout"]; ``` But this doesn't actually buy you anything. You've just replaced round parentheses (as in `(int)settings["timeout"]`) with angle brackets, but received no additional type safety as you can freely do ``` var timeout = settings<int>["connectionString"]; ``` If you have something that's strongly but not statically typed, you might want to wait until C# 4.0 with its *dynamic* keyword.
Here's a place where this would be useful. Say you have a strongly-typed `OptionKey<T>` for declaring options. ``` public static class DefaultOptions { public static OptionKey<bool> SomeBooleanOption { get; } public static OptionKey<int> SomeIntegerOption { get; } } ``` Where options are exposed through the `IOptions` interface: ``` public interface IOptions { /* since options have a default value that can be returned if nothing's * been set for the key, it'd be nice to use the property instead of the * pair of methods. */ T this<T>[OptionKey<T> key] { get; set; } T GetOptionValue<T>(OptionKey<T> key); void SetOptionValue<T>(OptionKey<T> key, T value); } ``` Code could then use the generic indexer as a nice strongly-typed options store: ``` void Foo() { IOptions o = ...; o[DefaultOptions.SomeBooleanOption] = true; int integerValue = o[DefaultOptions.SomeIntegerOption]; } ```
Why it is not possible to define generic indexers in .NET?
[ "", "c#", ".net", "generics", "" ]
I'm looking into converting a Flash application I have into JavaScript but was told that it probably wouldn't be possible due to the number of objects I would have to have on the go. Is this is true and, if it is, what are the limits?
*[JavaScript memory limit](http://blog.votanweb.com/2007/2/24/javascript_memory_limit)* shows that you can allocate at least 20 MB of memory in Firefox. There is definitely a limit though, but I doubt you'll meet the limit on memory. It is more likely that your performance will be too bad if you are converting a very dynamic Flash application.
Flash is very efficient at moving objects around since that's its primary function. Using JavaScript to move objects around in HTML is going to way, way slower. Nevertheless quite amazing things can be acheived with JavaScript. See [Lemmings](http://www.elizium.nu/scripts/lemmings/).
Is there a limit to the number of JavaScript objects you can have on the go at any one time?
[ "", "javascript", "object", "browser", "" ]
I have absolutely no idea about version control. Only that it can be very useful in many ways. I have found a few related questions but none that start from the absolute beginning. I am the only developer at my work using Mac OS X and traditionally just been using FTP. Can anyone help me with version control in relation to PHP projects (does it matter)?
Yes, try it out, it's worth it. And the language you are using doesn't matter. It's working great with PHP for me and it will for you too. **Benefits** If you are the only developer, it is indeed easier to go without version control. However, you will find great benefits to using a version control system. Some of the easiest benefits will be: 1. Never wondering what is your latest version once you go back to a project (no more myproject090201-archive2-final6.zip) 2. Never fear to start off some major refactoring, if you make a mistake on your file, you'll just rollback to the latest version 3. If something stops working in your project and you have the feeling it worked at one point, you can test some of the prior versions easily and look at the difference between the working version and the non-working version to find what broke the code 4. Additional backup of your current project, and even better if it's not on your machine... of course, additional points for backing up your version control system, we're never too cautious, you don't want to have to restart that month-long project do you? **Choices** As some have said, you have a few choices for your version control system and I guess you'll want a free one to begin. There are a few excellent commercial products but the free ones have nothing to be ashamed of. So here are some very popular free version control systems: * [Subversion](http://subversion.tigris.org/) (also called SVN) * [Git](http://git-scm.com/) * [Mercurial](http://www.selenic.com/mercurial/wiki/) * [Bazaar](http://bazaar-vcs.org/) **Centralized versus distributed** Subversion has been there for a while and it's one classified as 'centralized'. Meaning everyone will always go fetch the latest version and commit their latest work to one central system, often on another system although it can easily be on your own machine. It's a process easy to understand. The three others are called 'distributed'. There's a lot of different possible processes as it's a more flexible system and that's why those three newcomers are getting a lot of traction these days in open source projects where a lot of people are interacting with one another. Basically you are working with your own revisions on your own machine, making as many copies as you need and deciding which versions you share with other people on other computers. The trend definitely seems go towards distributed system but as those systems are more recent, they are still missing the GUI tools that makes it really user friendly to use and you might sometimes find the documentation to be a bit lighter. On the other hand, this all seems to be getting corrected quickly. In your case, as you are working alone, it probably won't make a big difference, and although you'll hear very good points for centralized and distributed systems, you'll be able to work with one or the other without any problems. **Tools** If you absolutely need a GUI tool for your Mac, I'd then choose SVN to get initiated to source control. There are two very good products for that (commercial): * [Versions](http://versionsapp.com/) * [Cornerstone](http://www.zennaware.com/cornerstone/) And a few [other ones](http://osx.iusethis.com/tag/subversion) (such as the free [svnX](http://www.lachoseinteractive.net/en/community/subversion/svnx/features/)) that are becoming a little bit old and unfriendly in my opinion but that might be interesting trying anyway. If you don't mind not using the GUI tools, with the help of Terminal you'll be able to do all the same things with a few simple command lines with any of the aforementioned systems. **Starting points** In any cases, you'll want some starting points. * For Subversion, your first stop must be their free book, [Version Control with Subversion](http://svnbook.red-bean.com/). Take a few hours of your day to go through the chapters, it'll be time well invested. The introduction chapters are a good read even you don't want to use Subversion specifically because it'll get you to understand version control a little bit better. * For a distributed system, I've had fun with Mercurial but it's an easily flammable subject so I'll let you make your own choice there. But if you end up looking at Mercurial, have a look at [this blog post](http://blog.medallia.com/2007/02/a_guided_tour_of_mercurial.html), it was an excellent starter for me that'll get you up and running with the basics in a few minutes if you're already a bit accustomed to version control in general. Anyway, drop by [Mercurial's homepage](http://www.selenic.com/mercurial/wiki/) and have a look at the Getting Started section of the page. **Conclusion** Give it a go, invest a day trying it out with a few bogus files. Try out renaming files and directory, erasing, moving things around, committing binary files versus text files, resolving conflicts and reverting to older versions to get a hang of it. These are often the first few hurdles you'll encounter when playing with version control and it'll be painless if it's on a non-production project. In any cases, it's something well-worth learning that'll be helpful with your solo projects as well as if you end up working with other developers at your current job or your next one. Good luck!
The type of code is irrelevant. One open-source and popular version control system is Subversion and there is a very good overview/manual [here](http://svnbook.red-bean.com/).
How to get started with version control and PHP
[ "", "php", "version-control", "" ]
I'm building this report in a system for a Billboard company. They have a table that stores all their billboards, and among other data, billboards have a Start Date and a Finish Date (both can be null). If for some reason a billboard has to stop beeing used, they set a finish date and it will become unnavaiable to be used after that date. Same with Start date (in case they just set up a new board and it will be avaiable for use after a set Start Date). In this report I have to get the sum of all possible advertising spots in a given period of time. So, lets say that for the period I chose (4 weeks, for exemple) \* In week 1 there are 500 avaiable boards \* In week 2 one board became unavaiable (making 498 boards avaiable) \* In week 3 two boards became avaiable (making 501 boards avaiable) \* In week 4 one board became avaiable and one other became unavaiable (making 501 boards avaiable) So then I should have a total of 1990 avaiable boards in this period, that's the result I'm after. How can I get this in a single query? The weeks will come from a HTML form and I have to convert them to dates before the query, so I'll just have the dates I want to know how many boards are avaiable at. The query to get the amount of boards for ONE specific date is like this: ``` SELECT COUNT(IdBillboard) FROM tBillboards WHERE (StartDate IS NULL OR StartDate <= '2009-01-05 00:00:00') AND (FinishDate IS NULL OR FinishDate >= '2009-01-05 00:00:00') ``` I can't just add `AND` and `OR` conditionals for each date because I kinda need a new recount for the separate dates. I thought about using a `WHILE` but couldn't figure out exactly how to do it for this case. So that's where I'm stuck... I'll post more details if anyone needs them. Thanks, Gabe
Don't know if this is what you're looking for, but could be a step in the right direction. ``` SELECT SUM(CASE WHEN (StartDate IS NULL OR StartDate <= '2009-01-05 00:00:00') AND (FinishDate IS NULL OR FinishDate >= '2009-01-05 00:00:00') THEN 1 ELSE 0 END)) Week1Count, SUM(CASE WHEN (StartDate IS NULL OR StartDate <= '2009-01-12 00:00:00') AND (FinishDate IS NULL OR FinishDate >= '2009-01-12 00:00:00') THEN 1 ELSE 0 END)) Week2Count FROM tBillboards ```
It's not an answer to your question, but you should consider using `BETWEEN` instead of the `AND`s. ``` WHERE (StartDate IS NULL) OR StartDate BETWEEN '2009-01-05' AND '2009-01-05' ``` IMO this is much more readable.
SQL Looping
[ "", "sql", "sql-server", "loops", "" ]
Environment: .NET Framework 2.0, VS 2008. I am trying to create a subclass of certain .NET controls (label, panel) that will pass through certain mouse events (`MouseDown`, `MouseMove`, `MouseUp`) to its parent control (or alternatively to the top-level form). I can do this by creating handlers for these events in instances of the standard controls, e.g.: ``` public class TheForm : Form { private Label theLabel; private void InitializeComponent() { theLabel = new Label(); theLabel.MouseDown += new MouseEventHandler(theLabel_MouseDown); } private void theLabel_MouseDown(object sender, MouseEventArgs e) { int xTrans = e.X + this.Location.X; int yTrans = e.Y + this.Location.Y; MouseEventArgs eTrans = new MouseEventArgs(e.Button, e.Clicks, xTrans, yTrans, e.Delta); this.OnMouseDown(eTrans); } } ``` I cannot move the event handler into a subclass of the control, because the methods that raise the events in the parent control are protected and I don't have a qualifier for the parent control: > *Cannot access protected member `System.Windows.Forms.Control.OnMouseDown(System.Windows.Forms.MouseEventArgs)` via a qualifier of type `System.Windows.Forms.Control`; the qualifier must be of type `TheProject.NoCaptureLabel` (or derived from it).* I am looking into overriding the `WndProc` method of the control in my sub-class, but hopefully someone can give me a cleaner solution.
Yes. After a lot of searching, I found the article ["Floating Controls, tooltip-style"](http://www.vbaccelerator.com/home/NET/Code/Controls/Popup_Windows/Floating_Controls/article.asp), which uses `WndProc` to change the message from `WM_NCHITTEST` to `HTTRANSPARENT`, making the `Control` transparent to mouse events. To achieve that, create a control inherited from `Label` and simply add the following code. ``` protected override void WndProc(ref Message m) { const int WM_NCHITTEST = 0x0084; const int HTTRANSPARENT = (-1); if (m.Msg == WM_NCHITTEST) { m.Result = (IntPtr)HTTRANSPARENT; } else { base.WndProc(ref m); } } ``` I have tested this in Visual Studio 2010 with .NET Framework 4 Client Profile.
The `WS_EX_TRANSPARENT` extended window style actually does this (it's what in-place tooltips use). You might want to consider applying this style rather than coding lots of handlers to do it for you. To do this, override the `CreateParams` method: ``` protected override CreateParams CreateParams { get { CreateParams cp=base.CreateParams; cp.ExStyle|=0x00000020; //WS_EX_TRANSPARENT return cp; } } ``` For further reading: * <http://support.microsoft.com/kb/92526> * <http://msdn.microsoft.com/en-us/library/ms632680.aspx>
Pass-through mouse events to parent control
[ "", "c#", "winforms", "mouseevent", "" ]