Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have 3 classes in different files: ``` X | ------- | | Y Z ``` I will be creating several objects of inherited classes Y and Z. A specific function in class Z should be executed only if some **flag** variable is set by class Y. Where should I create this flag variable (which class) and what should be the declaration be like (static/extern)?
Consider [template method](http://en.wikipedia.org/wiki/Template_method) as a replacement for the infamous flags.
The flag should be in Z, if it's only Z that's effected by it. But the whole thing smells - flags being set by classes rather than instances. Use polymorphism rather than flags where practical.
Communication between inherited classes
[ "", "c++", "inheritance", "class", "object", "communication", "" ]
I have a simple use for RadGrid that involves binding it to a list of strings ``` i.e. using: list<string> ``` The bind works OK and the data displays in the grid. However, the header says "Item", and there are other aspects of the column I'd like to be able to customize. I've tried to set the "DataField" property of the column on the ascx page: ``` <telerik:GridTemplateColumn UniqueName="column" DataField="" HeaderText="Omniture Codes"> ``` however, it seems to want the name of a data field, as in what you would get with a datatable object, but not with a list. Does anyone know a way to bind the column to the list, or have another idea for a work-around?
I think you should use a GridBoundColumn instead of the GridTemplateColumn and disable AutoGenerateColumns. E.g. the following works for me: ASPX: ``` <telerik:RadGrid ID="grid" runat="server" AutoGenerateColumns="false"> <MasterTableView> <Columns> <telerik:GridBoundColumn DataField="" HeaderText="MyHeaderText"> </telerik:GridBoundColumn> </Columns> </MasterTableView> </telerik:RadGrid> ``` Code-behind: ``` protected void Page_Load(object sender, EventArgs e) { List<string> data = new List<string> {"a", "b", "c"}; grid.DataSource = data; } ```
You have to try something like this with the RadGrid: ``` <Columns> <telerik:GridBoundColumn DataField="AddrLine1" HeaderText="Address Line 1" SortExpression="AddrLine1" UniqueName="AddrLine1"> <HeaderStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Left" Wrap="True" /> <ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"Font-Underline="False" HorizontalAlign="Left" Wrap="True" /> </telerik:GridBoundColumn> </Columns> ```
Binding Telerik RadGRID to a list<string> object
[ "", "c#", "xaml", "telerik", "radgrid", "" ]
I'm running in to a lot of inconsistencies with regards to what will compile and execute correctly in a Visual Web Developer 2008 Express environment and what fails on my web server. In particular, I've got an aspx and aspx.cs codebehind, plus a number of additional .cs files in my Web Developer project. It builds fine and executes okay under the Development Server. Once I upload the files to my server, the codebehind doesn't seem to be aware of the other .cs files. What's the correct way to make my aspx app inherit additional .cs files? --- Update --- Since I'm not really finding the answer I need, let me be a little more explicit with what I'm doing: I have three files: Default.aspx ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Import Namespace="UtilClasses" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` Default.aspx.cs ``` public partial class _Default : Page { } ``` App\_Code/UtilClasses.cs ``` namespace UtilClasses { public class AClass { public const int A = 1; } } ``` In this example, if I attempt to do any of the following, I'll get a compilation error on my web server: * Reference the App\_Code with a @Import * Call the code contained in it from the aspx.cs codebehind or * Call the code from the aspx page. It compiles fine in Web Developer 2008. The soltuion is a Web Site which is auto published to my web server via FTP. The exact list of files being published are: * Default.aspx * Default.aspx.cs * App\_Code/UtilClasses.cs * web.config
It seems like you have a deployment problem. Just **publish** (in build menu there is a publish item) your web application/site to a folder and then move the files in that folder to your server. I think you have old assembly files and new classes in your directory. hope this helps
You can use partial classes. Add a file ( \*.cs) and define your class as partial. So that, you can distribute your methods,properties anaother files
How do I place codebehind in multiple files?
[ "", "c#", "asp.net", "code-behind", "" ]
Short of parsing the output of `ipconfig`, does anyone have a 100% pure java way of doing this?
This is pretty easy: ``` try { InetAddress localhost = InetAddress.getLocalHost(); LOG.info(" IP Addr: " + localhost.getHostAddress()); // Just in case this host has multiple IP addresses.... InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null && allMyIps.length > 1) { LOG.info(" Full list of IP addresses:"); for (int i = 0; i < allMyIps.length; i++) { LOG.info(" " + allMyIps[i]); } } } catch (UnknownHostException e) { LOG.info(" (error retrieving server host name)"); } try { LOG.info("Full list of Network Interfaces:"); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); LOG.info(" " + intf.getName() + " " + intf.getDisplayName()); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { LOG.info(" " + enumIpAddr.nextElement().toString()); } } } catch (SocketException e) { LOG.info(" (error retrieving network interface list)"); } ```
Some of this will only work in JDK 1.6 and above (one of the methods was added in that release.) ``` List<InetAddress> addrList = new ArrayList<InetAddress>(); for(Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces(); eni.hasMoreElements(); ) { final NetworkInterface ifc = eni.nextElement(); if(ifc.isUp()) { for(Enumeration<InetAddress> ena = ifc.getInetAddresses(); ena.hasMoreElements(); ) { addrList.add(ena.nextElement()); } } } ``` Prior to 1.6, it's a bit more difficult - isUp() isn't supported until then. FWIW: The [Javadocs](http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getNetworkInterfaces()) note that this is the correct approach for getting all of the IP addresses for a node: > NOTE: can use > getNetworkInterfaces()+getInetAddresses() > to obtain all IP addresses for this > node
How to enumerate IP addresses of all enabled NIC cards from Java?
[ "", "java", "networking", "ip-address", "" ]
In SQL/Transact SQL, I am trying to update a temp table to take the latest date from 3 different date columns (in that temp table), and put that MAX date into a "latest date" column. What is the best way to do this, using an update statement?
With only three it's not so hard... This is definitely not extensible to an arbitrary number of datetime columns ! ``` Select Case When DT1 > DT2 And DT1 > DT3 Then DT1 When DT2 > Dt3 Then Dt2 Else DT3 End From TableName ```
I think you need to normalize your database from RecordID, Column1, Column2, Column3 to RecordID, ColumnID, Value Then you'll be able to find the max value in the three columns easily...
SQL/T-SQL - how to get the MAX value from 1 of N columns?
[ "", "sql", "t-sql", "" ]
I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python. What I've come up with is the following code, include throwaway code to test. ``` import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x ```
``` lines = open(filename).read().splitlines() ```
Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip. ``` lines = (line.rstrip('\n') for line in open(filename)) ``` However, you'll most likely want to use this to get rid of trailing whitespaces too. ``` lines = (line.rstrip() for line in open(filename)) ```
Best method for reading newline delimited files and discarding the newlines?
[ "", "python", "file", "readline", "" ]
I know this question has been asked before, but there was no clear answer. How do I change the printer tray programmatically? I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?
Ok, I figured this out. The answer is: 1. you need a local printer (if you need to print to a network printer, download the drivers and add it as a local printer) 2. use win32print to get and set default printer 3. also using win32print, use the following code: ``` import win32print PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter('RICOH-LOCAL', PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) #get the properties pDevModeObj = properties["pDevMode"] #get the devmode automaticTray = 7 tray_one = 1 tray_two = 3 tray_three = 2 printer_tray = [] pDevModeObj.DefaultSource = tray_three #set the tray properties["pDevMode"]=pDevModeObj #write the devmode back to properties win32print.SetPrinter(pHandle,2,properties,0) #save the properties to the printer ``` 4. that's it, the tray has been changed 5. printing is accomplished using internet explorer (from Graham King's blog) ``` from win32com import client import time ie = client.Dispatch("InternetExplorer.Application") def printPDFDocument(filename): ie.Navigate(filename) if ie.Busy: time.sleep(1) ie.Document.printAll() ie.Quit() ``` Done
There is no easy way to do this, since you indicate you want to choose specific pages from the pdf and print them to specific bins using Acrobat Reader Example: Print page 1 on letterhead bin 1, page 2 on stock bin 2 Acrobat Reader only allows printing of the whole document from the command line: You could alter the freeware [Ghostscript](http://pages.cs.wisc.edu/~ghost/doc/GPL/index.htm) and do what you want. or this commercial product should do the job. [PDFPrint](http://www.globalpdf.com/pdfprint/pdf-print-cmd.html) --- See the Acrobat Reader [developer FAQ](http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf) on page 24 for more details **AcroRd32.exe /t path "printername" "drivername" "portname"** — Start Adobe Reader and print a file while suppressing the Print dialog box. The path must be fully specified. The four parameters of the /t option evaluate to path, printername, drivername, and portname (all strings). **printername** — The name of your printer. **drivername** — Your printer driver’s name, as it appears in your printer’s properties. **portname** — The printer’s port. portname cannot contain — Your printer driver’s name, as it appears in your printer’s properties. **portname** — The printer’s port. portname cannot contain
Switching Printer Trays
[ "", "python", "winapi", "" ]
In Java, how would you set up a socket listener that listened to a socket for a series of bytes that represented a command and on recieving called a method which parsed the incoming data and invoked the appropriate command? **Clarification:** My issue is not with handling the commands (Which might also be error codes or responses to commands from the server) but with creating the socket and listening to it. **More Clarification:** What I want to do is mimic the following line of .Net (C#) code: ``` _stream.BeginRead(_data,0, _data.Length, new AsyncCallback(this.StreamEventHandler), _stream); ``` Where: * \_stream is a network stream created from a socket * \_data is an array of Byte of length 9 * this.StreamHandler is a delegate (function pointer) which get executed when data is read. I am rewriting a library from C# into Java and the component I am currently writing passes commands to a server over TCPIP but also has to be able to bubble up events/responses to the layer above it. In C# this seems to be trivial and it's looking less and less so in Java.
[Starting from my other answer](https://stackoverflow.com/questions/479595/forwarding-incoming-tcp-commands-to-a-function#479898): The specific part you request is the one that goes into the section: "Magic goes here". It can be done in ohh so many ways, but one is: ``` final InputStream in = socket.getInputStream(); // This creates a new thread to service the request. new Thread(new Runnable(){ public void run(){ byte[] retrievedData= new byte[ITEM_LENGTH]; in.read(retrievedData, 0, ITEM_LENGTH); in.close(); // Here call your delegate or something to process the data callSomethingWithTheData(retrievedData); } }).start(); ```
Have a small main method which sets up the socket and listens for incoming connections. Pass each connection to a worker object (possibly in its own thread). The worker object should have two APIs: The server and the client. The client API gets a connection and reads data from it, the server API takes a connection and writes data to it. I like to keep these two in a single class because that makes it much more simple to keep the two in sync. Use a helper class to encode/decode the data for transmission, so you have single point to decide how to transmit integers, commands, options, etc. If you want to go further, define a command class and write code to serialize that to a socket connection and read it from it. This way, you worker objects just need to declare which command class they handle and the server/client API gets even more simple (at the expense of the command class).
Forwarding incoming TCP "Commands" to a function?
[ "", "java", "sockets", "" ]
After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like `long x=(long)y;` or it's still considered bad and dangerous?
I would not, for the following reasons: * Casts are ugly and should be ugly and stand out in your code, and be findable using grep and similar tools. * "Always use C++ casts" is a simple rule that is much more likely to be remembered and followed than, "Use C++ casts on user-defined types, but it's OK to use C-style casts on built-in types." * C++ style casts provide more information to other developers about why the cast is necessary. * C-style casts may let you do conversions you didn't intend -- if you have an interface that takes in (int\*) and you were using c-style casts to pass it a const int\*, and the interface changes to take in a long\*, your code using c-style casts will continue to work, even if it's not what you wanted.
> Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous? Don't use them, ever. The reasons against using them applies here as well. Basically, once you use them, all bets are off because the compiler won't help you any more. While this is more dangerous for pointers than for other types, it's potentially *still* dangerous and gives poor compiler diagnostics in the case of errors, whereas new style casts offer richer error messages since their usage is more constrained: Meyers cites the example of casting away `const`ness: using any cast other than `const_cast` won't compile, thus making it clear *what* happens here. Also, some other disadvantages apply regardless of the types, namely syntactic considerations: A C-style cast is very unobtrusive. This isn't good: C++ casts stand out clearly in the code and point to potentially dangerous code. They can also easily be searched for in IDEs and text editors. Try searching for a C-style cast in a large code and you'll see how hard this is. On the other hand, C-style casts offer no advantages over C++ casts so there's not even a trade-off to consider. More generally, Scott Meyers advises to “Minimize casts” in Effective C++ (item 27), because “casts subvert the type system.”
Is it OK to use C-style cast for built-in types?
[ "", "c++", "casting", "" ]
I'm getting a strange warning: > The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll' There is no line number given, so it's hard to figure out what it's on about. The compiler error code is [CS1685](http://msdn.microsoft.com/en-us/library/8xys0hxk.aspx)
Are you using someone's dll (or your own) which had implemented this attribute (with exactly the same name) itself as a means of using some c# 3.0 features on pre .Net 3.5 runtimes? (A common trick) This is the probable cause. Since it is using the correct one (the MS one in the GAC) this is not a problem though you should hunt down the other and remove it.
Expanding on ShuggyCoUk's (correct) answer Truthfully it doesn't matter which version of the attribute is used (GAC, 3rd part, etc ...). All that matters is the C#/VB compiler can find some attribute with the correct name. The attribute serves no functional purpose in code. It exists purely to tell the Compiler "hey, this is an extension method". You can safely ignore this warning.
strange warning about ExtensionAttribute
[ "", "c#", "compiler-warnings", "" ]
I am developing a simple platform game using Java using BlueJ as the IDE. Right now I have player/enemy sprites, platforms and other items in the game drawn using polygons and simple shapes. Eventually I hope to replace them with actual images. For now I would like to know what is the simplest solution to setting an image (either URL or from local source) as the 'background' of my game window/canvas? I would appreciate it if it isn't something long or complex as my programming skills aren't very good and I want to keep my program as simple as possible. Kindly provide example codes with comments to elaborate on their function, and also if it's in its own class, how to call on relevant methods used by it on other classes. Thank you very much.
The answer will vary slightly depending on whether the application or applet is using [AWT](http://java.sun.com/javase/6/docs/technotes/guides/awt/) or [Swing](http://java.sun.com/docs/books/tutorial/uiswing/index.html). (Basically, classes that start with `J` such as `JApplet` and `JFrame` are Swing, and `Applet` and `Frame` are AWT.) In either case, the basic steps would be: 1. Draw or load an image into a `Image` object. 2. Draw the background image in the painting event of the `Component` you want to draw the background in. **Step 1.** Loading the image can be either by using the [`Toolkit`](http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html) class or by the [`ImageIO`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html) class. The [`Toolkit.createImage`](http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#createImage(java.lang.String)) method can be used to load an `Image` from a location specified in a `String`: ``` Image img = Toolkit.getDefaultToolkit().createImage("background.jpg"); ``` Similarly, `ImageIO` can be used: ``` Image img = ImageIO.read(new File("background.jpg"); ``` **Step 2.** The painting method for the `Component` that should get the background will need to be overridden and paint the `Image` onto the component. For AWT, the method to override is the [`paint`](http://java.sun.com/javase/6/docs/api/java/awt/Component.html#paint(java.awt.Graphics)) method, and use the [`drawImage`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#drawImage(java.awt.Image,%20int,%20int,%20java.awt.image.ImageObserver)) method of the [`Graphics`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html) object that is handed into the `paint` method: ``` public void paint(Graphics g) { // Draw the previously loaded image to Component. g.drawImage(img, 0, 0, null); // Draw sprites, and other things. // .... } ``` For Swing, the method to override is the [`paintComponent`](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)) method of the [`JComponent`](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html), and draw the `Image` as with what was done in AWT. ``` public void paintComponent(Graphics g) {     // Draw the previously loaded image to Component.     g.drawImage(img, 0, 0, null);     // Draw sprites, and other things.     // .... } ``` **Simple Component Example** Here's a `Panel` which loads an image file when instantiated, and draws that image on itself: ``` class BackgroundPanel extends Panel { // The Image to store the background image in. Image img; public BackgroundPanel() { // Loads the background image and stores in img object. img = Toolkit.getDefaultToolkit().createImage("background.jpg"); } public void paint(Graphics g) { // Draws the img to the BackgroundPanel. g.drawImage(img, 0, 0, null); } } ``` For more information on painting: * [Painting in AWT and Swing](http://java.sun.com/products/jfc/tsc/articles/painting/) * [Lesson: Performing Custom Painting](http://java.sun.com/docs/books/tutorial/uiswing/painting/) from [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) may be of help.
Firstly create a new class that extends the `WorldView` class. I called my new class `Background`. So in this new class import all the Java packages you will need in order to override the `paintBackground` method. This should be: ``` import city.soi.platform.*; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.ImageObserver; import javax.swing.ImageIcon; import java.awt.geom.AffineTransform; ``` Next after the class name make sure that it says extends `WorldView`. Something like this: ``` public class Background extends WorldView ``` Then declare the variables game of type `Game` and an image variable of type `Image` something like this: ``` private Game game; private Image image; ``` Then in the constructor of this class make sure the game of type `Game` is in the signature of the constructor and that in the call to `super` you will have to initialise the `WorldView`, initialise the game and initialise the image variables, something like this: ``` super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight()); this.game = game; bg = (new ImageIcon("lol.png")).getImage(); ``` Then you just override the `paintBackground` method in exactly the same way as you did when overriding the `paint` method in the `Player` class. Just like this: ``` public void paintBackground(Graphics2D g) { float x = getX(); float y = getY(); AffineTransform transform = AffineTransform.getTranslateInstance(x,y); g.drawImage(bg, transform, game.getView()); } ``` Now finally you have to declare a class level reference to the new class you just made in the `Game` class and initialise this in the `Game` constructor, something like this: ``` private Background image; And in the Game constructor: image = new Background(this); ``` Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable `frame` has been declared: ``` frame.add(image); ``` Make sure you add this code just before `frame.pack();`. Also make sure you use a background image that isn't too big! Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.
How to set background image in Java?
[ "", "java", "image", "background", "set", "" ]
In java how do I display dates in different locales (for e.g. Russian).
Use SimpleDateFormat constructor which takes locale. You need to first check if JDK supports the locale you are looking for, if not then you need to implement that.
Something like: ``` Locale locale = new Locale("ru","RU"); DateFormat full = DateFormat.getDateInstance(DateFormat.LONG, locale); out.println(full.format(new Date())); ``` Should do the trick. However, there was a problem of [Russian Date formatting in jdk1.5](http://www.freshblurbs.com/incorrect-date-formatting-sun-jdk-1-5-russian-locale-implementation) > The deal with Russian language is that month names have different suffix when they are presented stand-alone (i.e. in a list or something) and yet another one when they are part of a formatted date. So, even though March is "Март" in Russian, correctly formatted today's date would be: "7 Март**а** 2007 г." > > Let's see how JDK formats today's date: 7 Март 2007 г. Clearly wrong.
Date display in different locales in Java?
[ "", "java", "" ]
Im playing around with TryParse() But lets say the parsing fails, then returns false, and ... nothing.. Is there a way to get info back about what failed the parsing? I saw something like that at codeproject, but i didnt really understand it. Thanks :)
No, there's no way of getting that information from the normal .NET routines. You could check for a few things manually: * Try parsing the number as a decimal. If that works, but parsing as an integer doesn't, then it's either out of the range of the integer, or it's not an integer. * Look for non-decimal, non +/-, non-decimal-point characters * Check whether it's an empty string You haven't said what you're trying to parse (integer, double etc) or what options you want (allow hex, thousands separators etc) which makes it harder to give a good list of things to check.
The TryParse() method is there when you want to be shielded from any exceptions. If you want to see the exceptions then why not use the standard Parse() method in a try/catch block which will allow you to view any FormatExceptions etc thrown? As expected, with exception handling, this could impact performance however if the Parse() is expected to succeed then this should be tolerable.
Getting errorInfo back from tryParse()
[ "", "c#", "asp.net", "" ]
So if you have a html List Box, also called a multiple select, and you want to generate a comma delimited string that lists all the values in that List Box you can you can do that with the following example. The list\_to\_string() js function is the only important thing here. You can play with this page at <http://josh.gourneau.com/sandbox/js/list_to_string.html> ``` <html> <head> <script> function list_to_string() { var list = document.getElementById('list'); var chkBox = document.getElementById('chk'); var str = document.getElementById('str'); textstring = ""; for(var i = 0; i < list.options.length; ++i){ comma = ","; if (i == (list.options.length)-1){ comma = ""; } textstring = textstring + list[i].value + comma; str.value = textstring; } } </script> </head> <body> <form> <select name="list" id="list" size="3" multiple="multiple"> <option value="India">India</option> <option value="US">US</option> <option value="Germany">Germany</option> </select> <input type="text" id="str" name="str" /> <br /><br /> <input type="button" id="chk" value="make a string!" name="chk" onclick="list_to_string();"/> </form> </body> </html> ```
String concatenation is very slow on IE, use an array instead: ``` function listBoxToString(listBox,all) { if (typeof listBox === "string") { listBox = document.getElementById(listBox); } if (!(listBox || listBox.options)) { throw Error("No options"); } var options=[],opt; for (var i=0, l=listBox.options.length; i < l; ++i) { opt = listBox.options[i]; if (all || opt.selected ) { options.push(opt.value); } } return options.join(","); } ```
You could use array.join(','); to create a comma separated list from an array. Something like this, only better: ``` var list_to_string = function() { var opts = document.getElementById('list').options; var i = 0, len = opts.length, a = []; for (i; i<len; i++) { a.push(opts[i].value); } document.getElementById('str').value = a.join(','); } ```
Generate a comma delimited string from items in a HTML List Box (multiple select) with Javascript
[ "", "javascript", "html", "string", "textbox", "listbox", "" ]
I have a small piece of code that works as a plugin for a larger graphics application. The development platform is Qt with c++ code. I've managed to build a .so, .dylib and .dll for linux, MacOS and Windows respectively, but to do so I had to have a machine running each operating system (in my case, running linux [ubuntu] gcc natively, and windows MinGW and MacOS XCode gcc in virtual machines). Is there a way to build for all 3 platforms from one? I beat my head against this problem a while back, and research to date suggests that it's not easily (or feasibly) done. The code only needs to link against a single header that defines the plugin API and is built from a fairly basic Makefile (currently with small variations per platform).
Better late than never, I just came across [IMCROSS](http://www.sandroid.org/imcross/) It looks quite promising!
You should have a look at crosscompiling. You basically build a compiler that (on your current plattform) will output binaries for your desired platforms. Try [this link](http://silmor.de/29) about doing it on linux, for windows, with QT
Building a library across platforms without running all of the platforms
[ "", "c++", "build", "cross-platform", "makefile", "" ]
Long time ago, I was creating a mini ORM using reflection. While reading about reflection I got a similar answer like this: [Java Reflection Performance](https://stackoverflow.com/questions/435553/java-reflection-performance) Which makes completely sense and I quit my mini orm and sharpen my CTRL+C, CTRL+V keys ( the lib was intended to avoid having to rewrite again and again the same snippets for different tables in a web app I was working on ) Years later for some reason I don't remember now ( nor want to remeber ) I was reading ( or trying to... ) the Hibernate source code, for I wanted to know if they use AOP to generate code on the fly and avoid the reflection penalty, but for my surprise, all of what I saw was pure reflection. Does it mean the most accepted ORM framework out there, did exactly what years before discourage me from continuing my naive efforts ?? :") My question is: Can someone confirm my understanding of the Hibernate implementation? Do they generate bytecode on the fly to improve performance? Or are we ( when we use it ) always paying the reflection penalty ( which by the way, if the diff is in some ms, none of us have noticed nor complained about ) Are we paying the reflection penalty? If we are, I think it is **worth it!!!** Regards.
Hibernate instruments your models to be hibernate aware. There are varying levels of cost for using Reflection. Constantly looking up a method for a particular class is particularly expensive. Executing a method via reflection using a cached copy is not that much slower. If one thinks of the tasks that the reflection api must complete to invoke the method it all makes sense which each part is slow and consumes cpu cycles. ## Locating a method * Visit each and every method of a particular class * Test each methods visibility, method signature etc. * Generate bytecode for *found* method. One factors in the numbers of methods in a typical class and that some of these operations arent trivial it becomes obvious that this can be costly. ## Invoking the method. Each reflected method amounts to a bit of byte code that invokes the target method with a bit of boilerplate to match the reflection interface. Before it can do that it must perform some sanity checks so it can complain with nice messages rather than letting the runtime throw ClassCastException and similar exceptions. * If an instance method check the instance passed in isnt null and is the right type. * Check the arguments parameter includes the right amount and type of parameters. * Execute the method within a try catch. In the catch throw ITE etc. All these extras add some cost - not a lot but it does make things slower. ## Runtime costs In general caching methods and invoking that isnt cost but is a bit slower. The reflection api itself does attempt to cache methods and classes but finding the right method and so on is still a slow operation.
I think the important thing to remember is the relative cost in the overall application. Is reflection slower then normal object creation? Yes. Has reflection got better and faster? Yes. But really these points aren't very important when comparing the cost of reflection versus going over the wire and doing something with the database, which is what hibernate does - the cost becomes completely negligible and I'd say we are not paying the price.
Hibernate implementation. Are we paying the reflection penalty?
[ "", "java", "hibernate", "reflection", "" ]
Does C# have anything like Python's `__getattr__`? I have a class with many properties, and they all share the same accessor code. I would like to be able to drop the individual accessors entirely, just like in Python. Here's what my code looks like now: ``` class Foo { protected bool Get(string name, bool def) { try { return client.Get(name); } catch { return def; } } public bool Bar { get { return Get("bar", true); } set { client.Set("bar", value); } } public bool Baz { get { return Get("baz", false); } set { client.Set("baz", value); } } } ``` And here's what I'd like: ``` class Foo { public bool Get(string name) { try { return client.Get(name); } catch { // Look-up default value in hash table and return it } } public void Set(string name, object value) { client.Set(name, value) } } ``` Is there any way to achieve this in C# without calling `Get` directly? Thanks,
No. Although C# supports reflection, it is read-only (for loaded assemblies). That means you can't change any methods, properties, or any other metadata. Although you could [create a dynamic property](http://msdn.microsoft.com/en-us/library/h1zby21a.aspx), calling it wouldn't be very convenient - it would be even worse than using your `Get` method. Aside from using a `Dictionary<string, object>` and an indexer for your class, there's not much else you can do. Anyway, isn't doing a dictionary better if you have that many properties? Python doesn't check if an attribute exists at "compile-time" (or at least load-time). C# does. That's a fundamental difference between the two languages. In Python you can do: ``` class my_class: pass my_instance = my_class() my_instance.my_attr = 1 print(my_instance.my_attr) ``` In C# you wouldn't be able to do that because C# actually checks if the name `my_attr` exists at compile-time.
Can I ask: *why* don't you want the individual properties? That is the idiomatic .NET way of expressing the data associated with an object. Personally, assuming the data isn't sparse, I would keep the properties and have the overall method use reflection - this will make your compiled code as fast as possible: ``` protected T Get<T>(string name, T @default) { var prop = GetType().GetProperty(name); if(prop == null) return @default; return (T) prop.GetValue(this, null); } ``` Of course, if you don't care about the properties themselves being defined, then an indexer and lookup (such as dictionary) would be OK. There are also things you might be able to do with postsharp to turn a set of properties into a property-bag - probably not worth it, though. If you want the properties available for data-binding and runtime discovery, but can't define them at compile-time, then you would need to look at dynamic type descriptors; either `ICustomTypeDescriptor` or `TypeDescriptionProvider` - a fair bit of work, but very versatile (let me know if you want more info).
Fallback accessors in C#?
[ "", "c#", "accessor", "" ]
I have to develop a system to monitor sensor information, but many sensors might be added in the future. That said, the idea would be to develop a system that would consist of the application skeleton. The sensors (as each of them has its communication and data presentation characteristics) would be added as plugins to the system. How would I code this on C#? Is it a case of component-driven development? Should I use dynamic libraries?
There are a huge number of ad-hoc plug-in systems for C#. One is described in *[Plugin Architecture using C#](http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx)* (at [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project)). The general approach is that the host application publishes an assembly with interfaces. It enumerates through a folder and finds assemblies that define a class that implement its interfaces and loads them and instantiates the classes. In practice you want to do more. It's best if the host application defines two interfaces, an IHost and an IPlugIn. The IHost interface provides services that a plug-in can subscribe to. The IPlugIn gets constructed taking an IHost. To load a plug-in, you should do more than simply get a plug-in. You should enumerate all plug-ins that are loadable. Construct them each. Ask them if they can run. Ask them to export APIs into the host. Ask them to import APIs from the host. Plug-ins should be able to ask about the existence of other plug-ins. This way, plug-ins can extend the application by offering more APIs. PlugIns should include events. This way plug-ins can monitor the process of plug-ins loading and unloading. At the end of the world, you should warn plug-ins that they're going to go away. Then take them out. This will leave you with an application that can be written in a tiny framework and implemented entirely in plug-ins if you want it to. As an added bonus, you should also make it so that in the plug-ins folder, you resolve shortcuts to plug-ins. This lets you write your application and deliver it to someone else. They can author a plug-in in their development environment, create a shortcut to it in the application's plug-ins folder and not have to worry about deploying after each compile.
[Managed Extensibility Framework](http://en.wikipedia.org/wiki/Managed_Extensibility_Framework) (MEF) is what you need here. You could also use a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container, but that's a bit not what you'd expect, though a perfectly viable solution in itself.
System with plugins in C#
[ "", "c#", "plugins", "" ]
I need to export jar from my Eclipse Java project and I want to include the referenced libraries. I can't use fatjar for this, which is what everyone seems to recommend. There must be another way of doing this. Does anyone know what this is?!
The next version of Eclipse (3.5, due next June) has an option to include all necessary jars. It was introduced in 3.5M5 (thanks, [basszero](https://stackoverflow.com/users/287/basszero)). Or you can try to build your project with [Maven 2](http://maven.apache.org/). Then, you can build a "fat" jar with [`mvn assembly:assembly`](http://maven.apache.org/plugins/maven-assembly-plugin/index.html). Another option is to use [ant](http://ant.apache.org/). Unpack all JAR files into a temp directory and jar them up again.
I think its version 3.3 of Eclipse (ganymede) that has Export as **Runnable JAR file**. Last time I tried it, it did include the referenced libraries and also un-jars all the jars.
Eclipse Java; export jar, include referenced libraries, without fatjar
[ "", "java", "eclipse", "jar", "export", "" ]
I'm using Jetty to test a webservice we have and I am trying to get it to respond with no charset under the content-type header. Does anyone know how to do this? I've tried intercepting the Response and setting the CharacterEncoding to null or "" but that gives Exceptions. I am using Jetty 6.1.6.
I tried it my self now, but I must admit, my jetty is a very old one (4.2., but does everything the way I need it). I compared it to tomcat (4.1.29, old too). I checked the content type with the following code: ``` URL tomcatUrl = new URL("http://localhost:18080/ppi/jobperform/headertest")//tomcat; URLConnection tconnect = tomcatUrl.openConnection(); System.out.println("tomcat: " + tconnect.getContentType()); URL jettyUrl = new URL("http://localhost:13818/ppi/jobperform/headertest")//jetty; URLConnection jconnect = jettyUrl.openConnection(); System.out.println("jetty: " + jconnect.getContentType()); ``` And the result was as follows: Servlet code: ``` response.setContentType(""); response.getWriter().write("Return"); ``` => tomcat: ;charset=ISO-8859-1 jetty: Servlet code: ``` response.setContentType("text/plain"); response.getWriter().write("Return"); ``` => tomcat: text/plain;charset=ISO-8859-1 jetty: text/plain Servlet code: ``` response.setContentType("text/plain;charset=UTF-8"); response.getWriter().write("Return"); ``` => tomcat: text/plain;charset=UTF-8 jetty: text/plain;charset=UTF-8 So it looks as if the older jetty does exactly what you want, while tomcat does what you got from the newer jetty.
I think that this not a matter of which servlet container you use, but what you do with the response inside your servlet. If you set your character encoding by calling ServletResponse's setContentType (2.3) or setCharacterEncoding (2.4, 2.5) with parameter `null` or `""` it should work (didn't try myself). But be sure to call the methods named above *before* calling getWriter, otherwise setting the encoding [will have no effect](http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/ServletResponse.html#getWriter())!
Jetty Response with no Charset
[ "", "java", "jetty", "response", "character-encoding", "" ]
I have two tables in a SQLite DB, INVITEM and SHOPITEM. Their shared attribute is ItemId and I want to perform an INNER JOIN. Here's the query: ``` SELECT INVITEM.CharId AS CharId, INVITEM.ItemId AS ItemId FROM (INVITEM as INVITEM INNER JOIN SHOPITEM AS SHOPITEM ON SHOPITEM.ItemId = INVITEM.ItemId) WHERE ItemId = 3; ``` SQLite doesn't like it : ``` SQL error: ambiguous column name: ItemId ``` The error goes away if I write `WHERE INVITEM.ItemId = 3`, but since the WHERE condition is more or less user-specified, I rather make it work without having to specify the table. NATURAL JOIN seems to solve the issue, but I'm not sure if the solution is general enough (ie I could use in this case, but I'm not sure if I can use in every case) Any alternate SQL syntax that would fix the problem?
I would steer clear of allowing the user to write SQL clauses directly. This is the source of SQL Injection vulnerabilities. If you need the query to be flexible, try parsing the user's input and adding the appropriate where clause. Here is some C# code to show the general idea ``` // from user input string user_column = "ItemID"; string user_value = "3"; string sql = "SELECT INVITEM.CharId AS CharId, INVITEM.ItemId AS ItemId FROM (INVITEM as INVITEM INNER JOIN SHOPITEM AS SHOPITEM ON SHOPITEM.ItemId = INVITEM.ItemId) "; if (user_column == "ItemID") { // using Int32.Parse here to prevent rubbish like "0 OR 1=1; --" being entered. sql += string.Format("WHERE INVITEM.ItemID={0}",Int32.Parse(user_value)); } ``` Obviously if you're dealing with more than one clause, you'd have to substitute AND for WHERE in subsequent clauses.
I would write this query this way: ``` SELECT i.CharId AS CharId, i.ItemId AS ItemId FROM INVITEM as i INNER JOIN SHOPITEM AS s USING (ItemId) WHERE i.ItemId = 3; ``` I'm using the `USING (ItemId)` syntax which is just a matter of taste. It's equivalent to `ON (i.ItemID = s.ItemID)`. But I resolved the ambiguity by qualifying `i.ItemID` in the `WHERE` clause. You would think this is unnecessary, since `i.ItemID = s.ItemID`. They're both equal by commutativity, so there's no semantic ambiguity. But apparently SQLite isn't smart enough to know that. I don't like to use `NATURAL JOIN`. It's equivalent to an equi-join of *every* column that exists in both tables with the same name. I don't like to use this because I don't want it to compare columns that I don't want it to, simply because they have the same name.
"ambiguous column name" in SQLite INNER JOIN
[ "", "sql", "sqlite", "join", "" ]
I have been using jQuery IntelliSense in VS2008 and it has been great. Recently I added a reference to jQuery UI and since then, the jQuery IntelliSense has went away. I found that once you reference another .js file in your document, the IntelliSense goes away. Any way to avoid this?
If there are errors in any refernced files it will break intellisense for all files references from the same document. The next version of Visual Studio is going to be much more robust in this respect. I apologize directly for this fragility. We made some design decisions early on that we prevented us from making VS9 external references more robust. In the meantime, use the following workaround. Install SP1 from the link Slace gave you. If you have a reference a file named .js and there is a file named -vsdoc.js in the same location, then JS intellisense will pick up the -vsdoc version. If that script is empty then it won't generate an error. Identify the jquery plugin that is causing intellisense generation to fail and place a -vsdoc version next to it. You won't get intellisense for UI, but you will still get jquery and other plugins that do work. Anything you put in the vsdoc version will show up in intellisense. You could put spoofed versions of the data structures that you want to display in intellisense if you want to.
It's likely that there's a bug in one of the subsiquiently referenced JavaScript files. Open your JS file and once the "Updaing JavaScript Intellisense" has gone from the status bar of Visual Studio (there is a menu option which will force the JS intellisense to refresh, don't remember where it is, I just created a keyboard shortcut via the Tools -> Options -> Keyboard area) open up your Errors window and under the Warnings you should find the reason why the intellisense has failed to load. It's generally a bug found when parsing one of the files but I have had stack overflows when I had a lot of files referenced. **Edit**: You also should make sure you have this VS patch installed: <http://code.msdn.microsoft.com/KB958502> and VS 2008 SP1 (install SP1 first!). Then you just need to have: ``` /// <reference path="/path/to/jquery-1.3.1.js" /> ``` Ensure that you maintain the `-vsdocs` on the intellisense file and it will be automatically picked up (as long as it's in the same folder as the file you reference)
Adding additional js files breaks jQuery IntelliSense
[ "", "javascript", "jquery", "visual-studio-2008", "intellisense", "" ]
How to add a link stylesheet reference to the head of a document ? I've found this code but it's not working with all browsers, it crashes my IE7 : ``` var ss = document.createElement("link"); ss.type = "text/css"; ss.rel = "stylesheet"; ss.href = "style.css"; document.getElementsByTagName("head")[0].appendChild(ss); ``` Thanks
That was a simple cross reference javascript bug. Have a nice day.
Internet explorer will support innerHTML, though it adds reflow this would work: ``` var headHTML = document.getElementsByTagName('head')[0].innerHTML; headHTML += '<link type="text/css" rel="stylesheet" href="style.css">'; document.getElementsByTagName('head')[0].innerHTML = headHTML; ```
Add a link stylesheet dynamically in the <head>
[ "", "javascript", "internet-explorer", "dom", "crash", "" ]
I have two arrays in PHP as follows: *People:* ``` Array ( [0] => 3 [1] => 20 ) ``` *Wanted Criminals:* ``` Array ( [0] => 2 [1] => 4 [2] => 8 [3] => 11 [4] => 12 [5] => 13 [6] => 14 [7] => 15 [8] => 16 [9] => 17 [10] => 18 [11] => 19 [12] => 20 ) ``` How do I check if **any** of the *People* elements are in the *Wanted Criminals* array? In this example, it should return `true` because `20` is in *Wanted Criminals*.
You can use [`array_intersect()`](http://www.php.net/array_intersect). ``` $peopleContainsCriminal = !empty(array_intersect($people, $criminals)); ```
There's little wrong with using array\_intersect() and count() (instead of empty). For example: ``` $bFound = (count(array_intersect($criminals, $people))) ? true : false; ```
Checking if ANY of an array's elements are in another array
[ "", "php", "arrays", "filtering", "" ]
I'm a freshman in college going for my computer science degree... I've programmed plenty the last several years but just lately I've been getting more into theoretical ideas about organizing code, design patterns, differences in languages, etc. I have a Java class, so I've dropped my C++ research/development and moved into Java and JOGL (Java OpenGL). It's wonderful! But that's beside the point. I want to make a small role-playing game, but this question really applies to any sort of game. How do you organize the game objects in a way that is structured, like the Model-View-Controller pattern? It looks to be an amazing pattern, very widely used and makes a lot of sense, but I'm having trouble figuring out how to implement it. For instance, I need to keep track of a GL object for drawing to the screen. I have to have classes that implement MouseListener, MouseMotionListener, MouseWheelListener, and KeyListener (or one class, an all-in-one input manager). And I have to put my game data somewhere where all these different classes can access and modify it; if someone presses a button on the keyboard, the input managing class needs to somehow perform the action that the key is mapped to; when a frame needs to be drawn, the graphics class needs to find a way to loop through all the different 'things' and draw them all. And my biggest issue, the GUI; where does it tie into it all? It's something like the input, but not quite, and it needs to both set and get pieces of data from the actual game simulation... And complicating it even MORE is if I decide to try and add networking, which (similar to the GUI) also needs to have access to a lot of the data for modifying and reading... Oh, I'm just all confused. I don't know how to make all this work together in an object-oriented fashion... It's easy enough writing things that clearly fit the patterns, but when you have tons of things happening all tied to one game loop, modifying each other and the game data and so on, ... I don't even know any more. Maybe I'm just making this a bigger deal than it actually is. Has anyone else felt this way? Please offer some clarity to my situation so I can spend less time worrying and not knowing where to start! Edit: Found a nice diagram that might help me figure this all out... Source: (beware, PS file!) <http://www.tucs.fi/publications/attachment.php?fname=TR553.ps.gz> Edit2: I also like this guy's explanation of how he planned his MVC game: <http://interactivesection.wordpress.com/2007/11/19/dum-de-dum-drum-my-first-mvc-game-development/> Edit3: Another great article! <http://dewitters.koonsolo.com/gamemvc.html>
It might help you to think of the Model as a kind of game API. What would your game be reduced to if there were no UI at all for the game ordained from the beginning? You mention that what you have in mind is an RPG, so in this case you can imagine having the player character, his/her inventory, spells, abilities, NPCs, and even things like the map and combat rules all being part of the model. It is like the rules and pieces of Monopoly without the specifics of how the final game displays that or how the user is going to interact with it. It is like Quake as an abstract set of 3D objects moving through a level with things like intersection and collision calculated but no rendering, shadows, or sound effects. By putting all of those into the model the game itself is now UI agnostic. It could be hooked to an ASCII text interface like Rogue games have, or a command line UI akin to Zork, or a web based, or 3D UI. Some of those UIs might be a terrible fit depending upon the game mechanics, but they would all be possible. The View layer is the UI dependent layer. It reflects the specific choice of UI you went with and will be very much dedicated to that technology. It might be responsible for reading the state of the model and drawing it in 3D, ASCII, or images and HTML for a web page. It is also responsible for displaying any control mechanisms the player needs to use to interact with the game. The Controller layer is the glue between the two. It should never have any of the actual game logic in it, nor should it be responsible for driving the View layer. Instead it should translate actions taken in the View layer (clicking on buttons, clicking on areas of the screen, joystick actions, whatever) into actions taken on the model. For example, dropping an item, attacking an NPC, whatever. It is also responsible for gathering up data and doing any conversion or processing to make it easier for the View layer to display it. Now, the way I've described it above is as though there is a very distinct event sequence driving the game that is probably only really appropriate for a web game. That's because that's what I've spent my time on lately. In a game which is not driven by a user's request and a server's response like the web (e.g. a game running on the user's machine) you would probably want to make sure that the Model layer implemented the Observer pattern well. For example, if actions take place in the Model because time is passing then you might not want to have the View layer constantly polling the Model for updates. Instead by using the Observer pattern the Model could notify any observers of changes to Model objects as they happen. That could in turn be used to prompt immediate update to the View to reflect the change. Then if 60 seconds passing resulted in some repairs happening for the player's base, the base could effect the repairs and immediately notify any Observers attached to it that the base has updated. The View could be attached as an Observer and note that it needs to re-display the base because its state has changed. The notification itself might have included enough information to update the View or it might have to turn around and consult the model in order to update, but the result will be the same.
You're getting along there. basically, ask yourself the question "which code would change if I had to change some part of the program?" If it would change the way it looks without changing basic data, then it's in the view. If it is data that could be viewed in many ways, it's the model. And if it's how you play, then it's the control. So if it's whether you draw an "axe" with two blades or one, it's view. If it's how many hit points damage you inflict with an axe, it's model. And if it's whether you swing the axe by typing "s" or by right clicking, it's control.
How can you organize the code for a game to fit the MVC pattern?
[ "", "java", "oop", "design-patterns", "model-view-controller", "" ]
I have built myself a generic collection class which is defined like this. ``` public class StatisticItemHits<T>{...} ``` This class can be used with `int` and `string` values only. However this ``` public class StatisticItemHits<T> where T : string, int {...} ``` won't compile. What am I doing wrong?
The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that **inherit from int and string**, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?
You could make `StatisticItemHits<T>` an abstract class and create two subclasses: `StatisticItemHitsInt : StatisticItemHits<int>{}` `StatisticItemHitsString : StatisticItemHits<string>{}` That way there can only be an int and string-representation of StatisticItemHits
Restricting T to string and int?
[ "", "c#", "class", "generics", "types", "" ]
What is the common theory behind thread communication? I have some primitive idea about how it should work but something doesn't settle well with me. Is there a way of doing it with interrupts?
Really, it's just the same as *any* concurrency problem: you've got multiple threads of control, and it's indeterminate which statements on which threads get executed when. That means there are a large number of POTENTIAL execution paths through the program, and your program must be correct under all of them. In general the place where trouble can occur is when state is shared among the threads (aka "lightweight processes" in the old days.) That happens when there are shared memory areas, To ensure correctness, what you need to do is ensure that these data areas get updated in a way that can't cause errors. To do this, you need to identify "critical sections" of the program, where sequential operation must be guaranteed. Those can be as little as a single instruction or line of code; if the language and architecture ensure that these are *atomic*, that is, can't be interrupted, then you're golden. Otherwise, you idnetify that section, and put some kind of guards onto it. The classic way is to use a *semaphore*, which is an atomic statement that only allows one thread of control past at a time. These were invented by Edsgar Dijkstra, and so have names that come from the Dutch, *P* and *V*. When you come to a *P*, only one thread can proceed; all other threads are queued and waiting until the executing thread comes to the associated *V* operation. Because these primitives are a little primitive, and because the Dutch names aren't very intuitive, there have been some ther larger-scale approaches developed. Per Brinch-Hansen invented the *monitor*, which is basically just a data structure that has operations which are guaranteed atomic; they can be implemented with semaphores. Monitors are pretty much what Java `synchronized` statements are based on; they make an object or code block have that particular behavir -- that is, only one thread can be "in" them at a time -- with simpler syntax. There are other modeals possible. Haskell and Erlang solve the problem by being functional languages that never allow a variable to be modified once it's created; this means they naturally don't need to wory about synchronization. Some new languages, like Clojure, instead have a structure called "transactional memory", which basically means that when there *is* an assignment, you're guaranteed the assignment is atomic and reversible. So that's it in a nutshell. To really learn about it, the best places to look at Operating Systems texts, like, eg, [Andy Tannenbaum's text](https://rads.stackoverflow.com/amzn/click/com/0136006639).
The two most common mechanisms for thread communication are shared state and [message passing](http://lambda-the-ultimate.org/node/193).
Thread communication theory
[ "", "c++", "c", "multithreading", "theory", "" ]
I have the following SQL result set (as result of a join FWIW): ``` A,C B,E C,A D,A ``` Every value represents a node. So the total set of nodes involved is A,B,C,D,E. Every row describes a directed edge. ``` A -> C B -> E C -> A D -> A ``` Of course this can be simplified to ``` A <-> C B -> E D -> A ``` Now I would like to filter out the rows that do not have a bi-directional counterpart. So the final result set should be ``` A,C C,A ``` or ``` A,C ``` in this case. I am looking the best way to express this in SQL.
Imagine a table Nodes with columns Node1 and Node2. ``` SELECT node1, node2 FROM nodes n WHERE EXISTS (SELECT 1 FROM nodes WHERE node1 = n.node2 AND node2 = n.node1) ``` Of course you'll want to make sure its appropriate indexed, namely: ``` (node1, node2) ``` and ``` (node2, node1) ``` This will still get you A,C and C,A. To filter those out change the query to: ``` SELECT node1, node2 FROM nodes n WHERE EXISTS (SELECT 1 FROM nodes WHERE node1 = n.node2 AND node2 = n.node1) AND node1 < node2 ``` assuming there is a natural ordering you can take advantage of.
``` -- Temp table creating to insert example rows SELECT 'A' AS Col1, 'C' AS Col2 INTO #TEMP UNION SELECT 'B', 'E' UNION SELECT 'C', 'A' UNION SELECT 'D', 'A' SELECT A.* FROM #TEMP A, #TEMP B WHERE (A.COL1 = B.COL2 AND A.COL2 = B.COL1) ```
finding bi-directional connections in a table
[ "", "sql", "" ]
Is there a way without looping all the IEnumerable to get back the data inside the object (that inherited BindingList)? ``` MyListObject--> Transformed with Linq --> Back the data inside MyListObject ``` I know that I can do .ToList but it doesn't do what I would like. Any idea? Thank :)
I'm not sure exactly what your requirements are, especially the bit about `ToList` not doing what you need. Unfortunately, `BindingList<T>` only accepts an `IList<T>` parameter in its constructor and not an `IEnumerable<T>`. However, if you implement a pass-through constructor on your custom collection (or if it already has a constructor that takes `IList<T>`) then you could do something similar to this: ``` public class MyListObject<T> : BindingList<T> { public MyListObject() : base() { } public MyListObject(IList<T> list) : base(list) { } } // ... MyListObject<int> yourList = new MyListObject<int> { 1, 2, 3, 4, 5 }; yourList = new MyListObject<int>(yourList.Select(s => s * 2).ToList()); // yourList now contains 2, 4, 6, 8, 10 ```
One option is to wrap the returned IEnumerable into your collection type by using/adding constructor that takes IEnumerable as CStick suggest. Perhaps a bit more ellegant way is to add an extension method for the IEnumerable type that would return your collection: ``` static MyListObject ToMyList(this IEnumerable<T> en) { // construct your MyListObject from 'en' somehow } // And then just write: var mylist = (from c in ... ).ToMyList() ``` The last option that's probably too complicated for this simple scenario is to implement all the LINQ query operators for your type (extension methods Where, Select, and many many others). The plus thing is that you could (maybe) do some things more efficiently, but it's really a bit difficult thing to do.
Linq return IEnumerable<MyObject>, how to return MyListObject instead?
[ "", "c#", ".net", "linq", "" ]
I'm writing a program that downloads information from the web and part of that is images. At the moment I'm having a problem as the code to download the images is a different part to the code that displays them (under mvc). If a 404 is issued or the image download fails some way the display code pops a message propmt up which i would like to avoid. Is there an easy way to check to see if an image is valid? I'm only concerned about jpg, gif and png. Note: I dont care about reading the image data, just to check to see if it is valid image format.
Do you want to check whether the download would be successful? Or do you want to check that what is downloaded is, in fact, an image? In the former case, the only way to check is to try to access it and see what kind of HTTP response code you get. You can send an HTTP `HEAD` request to get the response code without actually downloading the image, but if you're just going to go ahead and download the image anyway (if it's successful) then sending a separate `HEAD` request seems like a waste of time (and bandwidth). Alternatively, if you really want to check that what you're downloading is a valid image file, you have to read the whole file to check it for corruption. But if you just want to check that the file extension is accurate, it should be enough to check the first few bytes of the file. All GIF images start with the ASCII text `GIF87` or `GIF89` depending on which GIF specification is used. PNG images start with the ASCII text `PNG`, and JPEG images have some magic number, which appears to be `0xd8ffe0ff` based on the JPEGs I looked at. (You should do some research and check that, try Wikipedia for links) Keep in mind, though, that to get even the first few bytes of the image, you will need to send an HTTP request which could return a 404 (and in that case you don't have any image to check).
Thanks for the answers guys. I have all ready downloaded the file so i went with just checking the magic number as the front end i use (wxWidgets) all ready has image library's and i wanted something very light. ``` uint8 UTIL_isValidImage(const unsigned char h[5]) { //GIF8 if (h[0] == 71 && h[1] == 73 && h[2] == 70 && h[3] == 56) return IMAGE_GIF; //89 PNG if (h[0] == 137 && h[1] == 80 && h[2] == 78 && h[3] == 71) return IMAGE_PNG; //FFD8 if (h[0] == 255 && h[1] == 216) return IMAGE_JPG; return IMAGE_VOID; } ```
Check for valid image
[ "", "c++", "image", "" ]
What is a component class and where would I typically use one? When I add a new item to my project in VS.NET 2008 one of the options is to add a component. I am not even sure I understand what a component is - but I would sure like to find out a bit more about them. Could somebody explain them to me or perhaps point me towards an online tutorial that would help me.
Well, generally speaking, a component is any part of a thing. Specifically in .NET, a component is a class that implements the [`IComponent` interface](http://msdn.microsoft.com/en-us/library/system.componentmodel.icomponent.aspx), which indicates that a class can interact with it's logical container. More often than not, you see this in the form of design support, in that classes interact with their host in the designer, but that's not a strict requirement.
[Component Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx) is for sharing objects between applications. Typically for dropping down object like outlook email to an application.
C# - What is a component and how is it typically used?
[ "", "c#", "components", "" ]
I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. If anyone can help me with this it would be greatly appreciated! Thanks a lot! Jason
The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications. Tip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single function call, but only the places where it makes a difference to survive the error. Tip 2: Use the logging module to report what happened in a way that is configurable independently from how you compose the module with other modules in a larger applications. Start importing the root logger in your module, then, using it in a few different places, you may eventually figure out a more sensible logging hierarchy. ``` import logging logger = logging.getLogger() for item in items: try: process(item) except Exception, exc: logger.warn("error while processing item: %s", exc) ``` Tip 3: define an "application exception", eventually you may want to define a hierarchy of such exception but this is better discovered when the need arise. Use such exception(s) to "bubble out" when the data you are dealing with are not what you expected or to signal inconsistent situations, while separating them from the normal standard exception arising from regular bugs or problems outside the modeled domain (IO errors etc). ``` class DomainException(Exception): """Life is not what I expected""" def process(item): # There is no way that this item can be processed, so bail out quickly. # Here you are assuming that your caller will report this error but probably # it will be able to process the other items. if item.foo > item.bar: raise DomainException("bad news") # Everybody knows that every item has more that 10 wickets, so # the following instruction is assumed always being successful. # But even if luck is not on our side, our caller will be able to # cope with this situation and keep on working item.wickets[10] *= 2 ``` The main function is the outmost checkpoint: finally deal here with the possible ways your task finished. If this was not a shell script (but e.g. the processing beneath a dialog in an UI application or an operation after a POST in a web application) only the way you report the error changes (and the use of the logging method completely separates the implementation of the processing from its interface). ``` def main(): try: do_all_the_processing() return 0 except DomainException, exc: logger.error("I couldn't finish. The reason is: %s", exc) return 1 except Exception, exc: logger.error("Unexpected error: %s - %s", exc.__class__.__name__, exc) # In this case you may want to forward a stacktrace to the developers via e-mail return 1 except BaseException: logger.info("user stop") # this deals with a ctrl-c return 1 if __name__ == '__main__': sys.exit(main()) ```
The ugly error message means that an exception is raised. You need to catch the exception. A good place to start is the [Python tutorial's section on exceptions.](http://docs.python.org/tutorial/errors.html) Basically you need to wrap your code in a `try...except` block like this: ``` try: do_something_dangerous() except SomeException: handle_the_error() ```
How to make python gracefully fail?
[ "", "python", "" ]
I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it. Now I can do this in two ways. One using a simple function and the other using a class. ``` Function: $data = tidy($data); Class: $tidy = new Tidy(); $data = $tidy->clean($tidy); ``` Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so. Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object? I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines? Thank you, Alec
I'd personally make a 'data' object that handles data then have a tidy method under it. This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.
For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object. I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done *as* objects, but were left as functions. Time conversions and string replacements.
Function vs Objects Best Practice
[ "", "php", "function", "object", "" ]
I'm looking for a reliable 3D scenegraph API for Java with good documentation, an active community and a license that allows for commercial use. I ruled out [com.sun.scenegraph](https://scenegraph.dev.java.net/) because it's GPL (and seemingly dead), Java3D because of [this](https://java3d.dev.java.net/servlets/NewsItemView?newsItemID=5689) post and JMonkeyEngine because of [this](http://www.jmonkeyengine.com/jmeforum/index.php?topic=9247.0) post. Any ideas?
Try [Xith3D](http://xith.org); it uses JOGL, not Java3D.
My interpretation of the Java3D post is that they are adding a new scene graph, not replacing their current one, in order to more effectively mesh with JavaFX, which is targeted at webapps. I've used Java3D in the past and liked it, so I would recommend trying to contact the devs and ask what their plans are with respect to whatever app you're building.
3D scene-graph library for Java?
[ "", "java", "3d", "scenegraph", "" ]
I'm working with an ASP.NET app with localization and globalization. I'm having some difficulty understanding how to get the Date() function in javascript to work properly given the user's environment. My user base is split between Mexico (spanish) and the US (english). Since the Mexico date format is dd/mm/yyyy and the english format is mm/dd/yyyy, the standard Date(strDate) javascript constructor does not work for me. Does anyone know the best way to handle globalization/localization of a javascript Date value? I have some business rules to enforce like dateA must be 90 days prior to dateB and dateB cannot exceed today.
Take a look at [datejs](http://code.google.com/p/datejs/), it handles localization very nicely. It comes with [a lot of globalization setups](http://code.google.com/p/datejs/source/browse/#svn/trunk/src/globalization). You just load the globalization setup of your current CultureInfo and datejs takes care of the rest.
[Matt Kruse](http://www.mattkruse.com/) developed a [really interesting date library](http://mattkruse.com/javascript/date/date.js) which should help with your particular case. Here's a snippet of the method you should use for the issue you mentioned: ``` // ------------------------------------------------------------------ // parseDate( date_string [, prefer_euro_format] ) // // This function takes a date string and tries to match it to a // number of possible date formats to get the value. It will try to // match against the following international formats, in this order: // y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d // M/d/y M-d-y M.d.y MMM-d M/d M-d // d/M/y d-M-y d.M.y d-MMM d/M d-M // A second argument may be passed to instruct the method to search // for formats like d/M/y (european format) before M/d/y (American). // Returns a Date object or null if no patterns match. // ------------------------------------------------------------------ function parseDate(val) { var preferEuro=(arguments.length==2)?arguments[1]:false; generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst'); var d=null; for (var i=0; i<checkList.length; i++) { var l=window[checkList[i]]; for (var j=0; j<l.length; j++) { d=getDateFromFormat(val,l[j]); if (d!=0) { return new Date(d); } } } return null; } ```
Javascript Date Localization
[ "", "asp.net", "javascript", "jquery", "localization", "globalization", "" ]
I don't know why this doesn't work: I'm using the [odict](http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py) class from [PEP 372](http://www.python.org/dev/peps/pep-0372/), but I want to use it as a `__dict__` member, i.e.: ``` class Bag(object): def __init__(self): self.__dict__ = odict() ``` But for some reason I'm getting weird results. This works: ``` >>> b = Bag() >>> b.apple = 1 >>> b.apple 1 >>> b.banana = 2 >>> b.banana 2 ``` But trying to access the actual dictionary doesn't work: ``` >>> b.__dict__.items() [] >>> b.__dict__ odict.odict([]) ``` And it gets weirder: ``` >>> b.__dict__['tomato'] = 3 >>> b.tomato 3 >>> b.__dict__ odict.odict([('tomato', 3)]) ``` I'm feeling very stupid. Can you help me out?
The closest answer to your question that I can find is at <http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html>. Basically, if `__dict__` is not an actual `dict()`, then it is ignored, and attribute lookup fails. The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly. ``` >>> class A(object) : ... def __init__(self) : ... self.__dict__['_odict'] = odict() ... def __getattr__(self, value) : ... return self.__dict__['_odict'][value] ... def __setattr__(self, key, value) : ... self.__dict__['_odict'][key] = value ... >>> a = A() >>> a <__main__.A object at 0xb7bce34c> >>> a.x = 1 >>> a.x 1 >>> a.y = 2 >>> a.y 2 >>> a.odict odict.odict([('x', 1), ('y', 2)]) ```
Everything in sykora's answer is correct. Here's an updated solution with the following improvements: 1. works even in the special case of accessing `a.__dict__` directly 2. supports `copy.copy()` 3. supports the `==` and `!=` operators 4. uses [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict) from Python 2.7. ... ``` from collections import OrderedDict class OrderedNamespace(object): def __init__(self): super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() ) def __getattr__(self, key): odict = super(OrderedNamespace, self).__getattribute__('_odict') if key in odict: return odict[key] return super(OrderedNamespace, self).__getattribute__(key) def __setattr__(self, key, val): self._odict[key] = val @property def __dict__(self): return self._odict def __setstate__(self, state): # Support copy.copy super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() ) self._odict.update( state ) def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self.__eq__(other) ```
Using an ordered dict as object dictionary in python
[ "", "python", "ordereddictionary", "" ]
What is the best way to concatenate a list of String objects? I am thinking of doing this way: ``` List<String> sList = new ArrayList<String>(); // add elements if (sList != null) { String listString = sList.toString(); listString = listString.subString(1, listString.length() - 1); } ``` I somehow found this to be neater than using the StringBuilder/StringBuffer approach. Any thoughts/comments?
Your approach is dependent on Java's ArrayList#toString() implementation. While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better). Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.
Use one of the the [StringUtils.join](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join%28java.lang.Iterable,%20char%29) methods in Apache Commons Lang. ``` import org.apache.commons.lang3.StringUtils; String result = StringUtils.join(list, ", "); ``` If you are fortunate enough to be using Java 8, then it's even easier...just use [String.join](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) ``` String result = String.join(", ", list); ```
Best way to concatenate List of String objects?
[ "", "java", "string", "list", "" ]
I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what type it is. Is there an easy way to do this in C++ (as there is in Java)? Just to be clear, I'm looking for methods on converting an object into an array of bytes, then back into an object. I can handle the socket transmission.
Talking about serialization, the [boost serialization API](http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/index.html) comes to my mind. As for transmitting the serialized data over the net, I'd either use Berkeley sockets or the [asio library](http://tenermerx.com/Asio/). If you want to serialize your objects to a byte array, you can use the boost serializer in the following way (taken from the tutorial site): ``` #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> class gps_position { private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & degrees; ar & minutes; ar & seconds; } int degrees; int minutes; float seconds; public: gps_position(){}; gps_position(int d, int m, float s) : degrees(d), minutes(m), seconds(s) {} }; ``` Actual serialization is then pretty easy: ``` #include <fstream> std::ofstream ofs("filename.dat", std::ios::binary); // create class instance const gps_position g(35, 59, 24.567f); // save data to archive { boost::archive::binary_oarchive oa(ofs); // write class instance to archive oa << g; // archive and stream closed when destructors are called } ``` Deserialization works in an analogous manner. There are also mechanisms which let you handle serialization of pointers (complex data structures like tress etc are no problem), derived classes and you can choose between binary and text serialization. Besides all STL containers are supported out of the box.
There is a generic pattern you can use to serialize objects. The fundemental primitive is these two functions you can read and write from iterators: ``` template <class OutputCharIterator> void putByte(char byte, OutputCharIterator &&it) { *it = byte; ++it; } template <class InputCharIterator> char getByte(InputCharIterator &&it, InputCharIterator &&end) { if (it == end) { throw std::runtime_error{"Unexpected end of stream."}; } char byte = *it; ++it; return byte; } ``` Then serialization and deserialization functions follow the pattern: ``` template <class OutputCharIterator> void serialize(const YourType &obj, OutputCharIterator &&it) { // Call putbyte or other serialize overloads. } template <class InputCharIterator> void deserialize(YourType &obj, InputCharIterator &&it, InputCharIterator &&end) { // Call getByte or other deserialize overloads. } ``` For classes you can use the friend function pattern to allow the overload to be found using ADL: ``` class Foo { int internal1, internal2; // So it can be found using ADL and it accesses private parts. template <class OutputCharIterator> friend void serialize(const Foo &obj, OutputCharIterator &&it) { // Call putByte or other serialize overloads. } // Deserialize similar. }; ``` Then in your program you can serialize and object into a file like this: ``` std::ofstream file("savestate.bin"); serialize(yourObject, std::ostreambuf_iterator<char>(file)); ``` Then read: ``` std::ifstream file("savestate.bin"); deserialize(yourObject, std::istreamBuf_iterator<char>(file), std::istreamBuf_iterator<char>()); ``` --- My old answer here: Serialization means turning your object into binary data. While deserialization means recreating an object from the data. When serializing you are pushing bytes into an `uint8_t` vector. When unserializing you are reading bytes from an `uint8_t` vector. There are certainly patterns you can employ when serializing stuff. Each serializable class should have a `serialize(std::vector<uint8_t> &binaryData)` or similar signatured function that will write its binary representation into the provided vector. Then this function may pass this vector down to it's member's serializing functions so they can write their stuff into it too. Since the data representation can be different on different architectures. You need to find out a scheme how to represent the data. Let's start from the basics: ### Serializing integer data Just write the bytes in little endian order. Or use varint representation if size matters. Serialization in little endian order: ``` data.push_back(integer32 & 0xFF); data.push_back((integer32 >> 8) & 0xFF); data.push_back((integer32 >> 16) & 0xFF); data.push_back((integer32 >> 24) & 0xFF); ``` Deserialization from little endian order: ``` integer32 = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); ``` ## Serializing floating point data As far as I know the IEEE 754 has a monopoly here. I don't know of any mainstream architecture that would use something else for floats. The only thing that can be different is the byte order. Some architectures use little endian, others use big endian byte order. This means you need to be careful which order to you loud up the bytes on the receiving end. Another difference can be handling of the denormal and infinity and NAN values. But as long as you avoid these values you should be OK. Serialization: ``` uint8_t mem[8]; memcpy(mem, doubleValue, 8); data.push_back(mem[0]); data.push_back(mem[1]); ... ``` Deserialization is doing it backward. Mind the byte order of your architecture! ## Serializing strings First you need to agree on an encoding. UTF-8 is common. Then store it as a length prefixed manner: first you store the length of the string using a method I mentioned above, then write the string byte-by-byte. ## Serializing arrays. They are the same as a strings. You first serialize an integer representing the size of the array then serialize each object in it. ## Serializing whole objects As I said before they should have a `serialize` method that add content to a vector. To unserialize an object, it should have a constructor that takes byte stream. It can be an `istream` but in the simplest case it can be just a reference `uint8_t` pointer. The constructor reads the bytes it wants from the stream and sets up the fields in the object. If the system is well designed and serialize the fields in object field order, you can just pass the stream to the field's constructors in an initializer list and have them deserialized in the right order. ## Serializing object graphs First you need to make sure if these objects are really something you want to serialize. You don't need to serialize them if instances of these objects present on the destination. Now you found out you need to serialize that object pointed by a pointer. The problem of pointers that they are valid only the in the program that uses them. You cannot serialize pointer, you should stop using them in objects. Instead create object pools. This object pool is basically a dynamic array which contains "boxes". These boxes have a reference count. Non-zero reference count indicates a live object, zero indicates an empty slot. Then you create smart pointer akin to the shared\_ptr that doesn't store the pointer to the object, but the index in the array. You also need to agree on an index that denotes the null pointer, eg. -1. Basically what we did here is replaced the pointers with array indexes. Now when serializing you can serialize this array index as usual. You don't need to worry about where does the object will be in memory on the destination system. Just make sure they have the same object pool too. So we need to serialize the object pools. But which ones? Well when you serialize an object graph you are not serializing just an object, you are serializing an entire system. This means the serialization of the system shouldn't start from parts of the system. Those objects shouldn't worry about the rest of the system, they only need to serialize the array indexes and that's it. You should have a system serializer routine that orchestrates the serialization of the system and walks through the relevant object pools and serialize all of them. On the receiving end all the arrays an the objects within are deserialized, recreating the desired object graph. ## Serializing function pointers Don't store pointers in the object. Have a static array which contains the pointers to these functions and store the index in the object. Since both programs have this table compiled into themshelves, using just the index should work. ## Serializing polymorphic types Since I said you should avoid pointers in serializable types and you should use array indexes instead, polymorphism just cannot work, because it requires pointers. You need to work this around with type tags and unions. ## Versioning On top of all the above. You might want different versions of the software interoperate. In this case each object should write a version number at the beginning of their serialization to indicate version. When loading up the object at the other side the, newer objects maybe able to handle the older representations but the older ones cannot handle the newer so they should throw an exception about this. Each time a something changes, you should bump the version number. --- So to wrap this up, serialization can be complex. But fortunately you don't need to serialize everything in your program, most often only the protocol messages are serialized, which are often plain old structs. So you don't need the complex tricks I mentioned above too often.
How do you serialize an object in C++?
[ "", "c++", "serialization", "marshalling", "c++-faq", "" ]
I've got a game which dumps state information to a database. Eg. Connected, Lost Connection, Grabbed Screen Dump, etc. Each state is defined by a field called `StateTypeId`, which is a foreign key to a simple lookup table `'StateTypes'`. Now, i'm trying to find all the people who are currently '`Connected`' (eg. StateTypeId == 1), and i'm not sure how to do it. When i say *currently connected*, I mean that a user doesn't have a '`LostConnection`' state (ie. StateType == 2) as their most recent entry. I was thinking along the lines of. ``` SELECT UserId FROM UserData WHERE StateType = 1 GROUP BY UserId ``` or ``` SELECT UserId FROM UserData WHERE StateType != 1 GROUP BY UserId ``` but this returns all the results, not just the most recent stuff. Any suggestions? (i'm guessing I'm missing a `TOP(1)` and some rank/order by stuff?) ## EDIT DOH! i forgot to mention, i DO have a DateTime column in the table -> DateEntered. ## EDIT 2 - Clarification of question AND some sample data. I've tried the suggested solutions and i'm not having much luck. As such, i'll provide some sample data to see if this helps clarify my question. ``` ID State UserName DateAdded 1 Connected Foo 1/1/2000 12:00 2 Connected Bar 1/1/2000 12:01 3 ScreenShot Foo 1/1/2000 12:05 4 LostConnection Foo 1/1/2000 12:06 5 Connected Joe 1/1/2000 12:10 6 LostConnection Joe 1/1/2000 12:15 7 Screenshot Bar 1/1/2000 12:16 8 Connected Jane 1/1/2000 12:22 ``` So looking at this, the people who are connected (currently) are Bar and Jane. Foo and Joe are gone. Also note, Bar's last activity a screenshot, meaning, his last activity was not a LostConnection state. HTH.
What you are looking for is the "most recent" entry having a StateType of 1 or 2: Then you are looking to identify the "last" one for each user: ``` select UserName, max(DateAdded) as LastDate from UserData where State IN ('Connected', 'LostConnection') Group by UserName ``` Then you need to check the state of these (which requires a join with the original table): ``` SELECT UserName FROM UserData allData join (select UserName, max(DateAdded) as LastDate from UserData where State IN ('Connected', 'LostConnection') Group by UserName) as lastData on allData.UserName = lastData.UserName and allData.DateAdded = lastData.LastDate WHERE StateType = 'Connected' ``` Another way to join would use the id of the UserData like this: ``` SELECT UserName FROM UserData allData join (select max(id) as id -- if ids are assigned in ascending order from UserData where State IN ('Connected', 'LostConnection') Group by UserName) as lastData on allData.id = lastData.id WHERE StateType = 'Connected' ```
if you have a datetime entry or time stamp you can do it this way: ``` Select UserID From UserData Where StateType = 1 Group by UserID Having Date = Max(Date) ```
Need some help with a simple SQL query
[ "", "sql", "t-sql", "" ]
Can someone explain this OOP javascript structure? I realize it is how you create 'objects' in javascript, just need some explanation on the notation and what it means: ``` var vote = function(){ return { P1: function() { alert('P1'); }, P2: function() { alert('P2'); } }; }(); vote.P1(); vote.P2(); ``` 1. Why are the public methods in the return call? How is this possible? Separated by commas? 2. Why does the end of the 'object' have to be (); ? 3. Naming convention for internal methods and public methods? 4. Are public properties and methods the same structure? What is the difference?
``` var vote = function(){ var privateMember = 3; // lets define a private member, this will only be available inside the function scope, so we can't do "vote.privateMember" because we're not returning it below // It's returning an object, {} // these are considered public because they are returned by the function, making them available outside the function scope using the "dot" operator, "vote.P1()" return { // first value of the object is a function // so we can call this like "vote.P1()" // we're calling a privateMember in here P1: function() { alert('P1'); alert(privateMember); }, // second value of the object is a function // so we can call this like "vote.P2()" P2: function() { alert('P2'); } }; }(); // () means it will execute the function, so "vote" will store the return value of this function, it's a shorthand for `var vote = function(){}; vote = vote(); ``` Naming convention for private methods is usually to put an underscore before the method/property name `_privateMethod: function(){}`.
1. It's returning the object/hash. Notice that right after the return is a { which is the beginning of the object/hash. 2. to run the anonymous function that returns the object. 3. I don't know what you mean. 4. Yes they are the same. A property can be a function because javascript has first class functions. This code is contrived so it's hard to say anything useful about it. I'm not sure what the authors intent was. It looks like he may have been aiming to create a class like thing, as opposed to the way javascript does prototype based OO. This code could have just as easily been written. ``` var vote = { P1: function() { alert('P1'); }, P2: function() { alert('P2'); } }; ```
Can someone explain this OOP javascript structure
[ "", "javascript", "oop", "" ]
How can you raise an exception when you import a module that is less or greater than a given value for its \_\_version\_\_? There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x
Python comes with this inbuilt as part of distutils. The module is called `distutils.version` and is able to compare several different version number formats. ``` from distutils.version import StrictVersion print StrictVersion('1.2.2') > StrictVersion('1.2.1') ``` For way more information than you need, see the documentation: ``` >>> import distutils.version >>> help(distutils.version) ```
If you are talking about modules installed with easy\_install, this is what you need ``` import pkg_resources pkg_resources.require("TurboGears>=1.0.5") ``` this will raise an error if the installed module is of a lower version ``` Traceback (most recent call last): File "tempplg.py", line 2, in <module> pkg_resources.require("TurboGears>=1.0.5") File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 528, in resolve raise VersionConflict(dist,req) # XXX put more info here pkg_resources.VersionConflict: (TurboGears 1.0.4.4 (/usr/lib/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg), Requirement.parse('TurboGears>=1.0.5')) ```
How to raise an exception on the version number of a module
[ "", "python", "versioning", "" ]
Just like the title asks. I've been learning Python for a while now and I'd say I'm pretty decent with it. I'm looking for a medium or large project to keep me busy for quite a while. Your suggestions are greatly appreciated.
What are you interested in doing? You could write a whole host of database programs, for keeping track of recipes, cd's, contacts, self tests, etc.... Basically make code to load/save to a database and enforce some business rules, then expose it by a web service. Then make both a web front end and an application graphical front end (using TK/WxWidgets/Qt (4.5 will be LGPL YAY)) that talk with the web service. That should give you practice with creating/talking with web services (something more and more companies are doing) along with both main ways of creating a GUI.
Find a local charitable orgainzation with a lousy web presence. Solve their problem. Help other people. Learn more Python. Everyone wins.
What's a good medium/large project for a Python programmer?
[ "", "python", "" ]
I'm running windows vista and want to get the appearance to look like regular vista programs. Are there any really good tutorials/articles on how to build Vista Style apps? I would also like to learn how to use the native code and convert it to C# like in [this](http://bartdesmet.net/blogs/bart/archive/2006/09/26/4470.aspx) example.
If you're using WPF you can use Microsoft's [Vista Bridge library](http://code.msdn.microsoft.com/VistaBridge) which has several useful controls. Otherwise, just look at the [Windows UX Guidelines](http://msdn.microsoft.com/en-us/library/aa511258.aspx) and roll your own. From that page: > Some of the features included in the > Vista Bridge Sample Library are - > Vista style Task and File Dialogs, > Common Open and Save dialogs, > Application Recovery and Restart, > Known Folders, Network Lists, Power > Management, User Account Control, > CommandLink control, Aero Wizard > Control, System provided icons etc. Additionally, you can check out **[Aero.Controls](http://factormystic.net/projects/code/aero.controls)** and **[Aero.Wizard](http://factormystic.net/projects/code/aero.wizard)**, two free open source WinForms packs I wrote that set you up with some standard controls and a wizard, respectively.
If you're using WinForms it's *relatively* easy to accomplish it because WinForms is based on the native Win32 controls. Many controls have ways to enhance their rendering by setting additional flags (by sending messages to the native control) or using [SetWindowTheme](http://msdn.microsoft.com/en-us/library/bb759827(VS.85).aspx). This can be achieved through Interop. As an example, take a simple ListView. If you want an explorer-style listview you use SetWindowTheme on the exposed handle of the ListView. We use interop to get access to the native SetWindowTheme() function, hook the window procedure of the ListView and apply the theme when the control is created: ``` static class NativeMethods { public const int WM_CREATE = 0x1; [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)] public extern static int SetWindowTheme( IntPtr hWnd, string pszSubAppName, string pszSubIdList); } class ListView : System.Windows.Forms.ListView { protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_CREATE) { NativeMethods.SetWindowTheme(this.Handle, "Explorer", null); } base.WndProc(ref m); } } ``` The difference between a default ListView and our enhanced version: [ListView difference http://img100.imageshack.us/img100/1027/62586064nt6.png](http://img100.imageshack.us/img100/1027/62586064nt6.png) Unfortunately there isn't one simple way for every control. Some controls don't even have any WinForms wrapper. Recently I stumbled upon a nice compilation [in this CodeProject article](http://www.codeproject.com/KB/vista/themedvistacontrols.aspx) which is worth a look. There may also be managed libraries out there that package this.
Making Vista style apps in C#
[ "", "c#", "visual-studio", "windows-vista", "" ]
I know it's not easy to find a master in GINA, but my question is most near to Interprocess Communication(IPC), I wrote my custom GINA in unmanaged c++, I included it a method that checks for validity of a fingerprint for the user try to login, this function will call some method in a running system windows service written in c#, the code follows: in GINA, unmanaged c++ ``` if(Fingerprint.Validate(userName,finerprintTemplate) { //perform login } ``` in windows service, C# ``` public class Fingerprint { public static bool Validate(string userName, byte[] finerprintTemplate) { //Preform Some code to validate fingerprintTemplate with userName //and retuen result } } ``` Does anyone know how to do such Communication between GINA and the windows service, or simply between c++ written service and C# written service. Thanks
The canonical method for communicating with a service (or most IPC that potentially needs to cross a session/desktop boundary) is a named pipe. You can use mailslots as well, but you have to deal with duplication issues because mailslot messages get duped across all installed protocols, so you need some kind of tagging system... gets kinda messy. See the docs for CreateNamedPipe and work your way out from there. I have talked between C++ and C# using pipes: the interop got a little messy (binary messages), but its do-able. There's some sample code for C# pipes (from both sides) [here](http://www.switchonthecode.com/tutorials/interprocess-communication-using-named-pipes-in-csharp). The nice thing about using a pipe for your specific service to service comms problem is you can expand the design later on to support a UI if you need it.
[NISGINA](ftp://ftp.eng.auburn.edu/pub/cartegw/nisgina/nigel/nigel.html) is an open-source GINA plugin to authenticate against a NIS directory. If you haven't already seen this, it's the only example of an open-source GINA plugin that I'm aware of. If you haven't already, You might find it worth your while to peruse the source code for this. Note that as of Windows Vista, [GINA has been deprecated](http://technet.microsoft.com/en-us/magazine/2007.03.vistakernel.aspx) and replaced with another API called [Credential Provider Architecture.](http://msdn.microsoft.com/en-us/magazine/cc163489.aspx)
Login method Customization using GINA
[ "", "c#", ".net", "windows-services", "authentication", "ipc", "" ]
I know that it's more performant to use single-quoting versus double-quoting when accessing/processing string values, but I was wondering if there's any performance benefits in omitting the quotations entirely. ``` $a = array('table' => 'myTable'); $table = $a['table']; ``` versus ``` $a = array(table => 'myTable'); $table = $a[table]; ```
Yes. In your second example the PHP processor checks if "table" is defined as a constant before defaulting it back to an array key, so it is making one more check than it needs to. This can also create problems. Consider this: ``` const table = 'text'; $a = array( table => 'myTable', order => 'myOrder' ); $table = $a[table] ``` Now PHP interprets your array as $a[text] which is not what you want.
You should always quote your strings. In your second example, PHP does convert `table` and `order` to strings, but if `table` or `order` were [defined](http://php.net/define) as constants, PHP would use the value of the constant instead of the string 'table' or 'order'.
The difference between unquoted, single-quoted, and double-quoted array keys
[ "", "php", "arrays", "key", "" ]
I want to use CURL library but I don't want to install it in a hard way I just want to do something like this ``` require_once('curl.php'); ``` I am not sure if this possible or not? and where can I found this CURL class? thanks
PHP requires that its built with the cURL library, see: <http://www.php.net/manual/en/curl.installation.php> So you would install libcurl-devel for your system and then compile PHP with ``` --with-curl ``` And maybe ``` --with-curl=/path/to ``` If you installed it in a non-standard location.
You're copy of PHP is either going to have to have been built with Curl, or dynamically load it in (because Curl is not originally written in PHP, it's a C library). Create a simple script that calls phpinfo(). If curl was built in, it should show up on this page. phpinfo();
Can I include CURL library in my PHP script as a class
[ "", "php", "curl", "" ]
I'm trying to replace this: ``` void ProcessRequest(object listenerContext) { var context = (HttpListenerContext)listenerContext; Uri URL = new Uri(context.Request.RawUrl); HttpWebRequest.DefaultWebProxy = null; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL); httpWebRequest.Method = context.Request.HttpMethod; httpWebRequest.Headers.Clear(); if (context.Request.UserAgent != null) httpWebRequest.UserAgent = context.Request.UserAgent; foreach (string headerKey in context.Request.Headers.AllKeys) { try { httpWebRequest.Headers.Set(headerKey, context.Request.Headers[headerKey]); } catch (Exception) { } } using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { Stream responseStream = httpWebResponse.GetResponseStream(); if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip")) responseStream = new GZipStream(responseStream, CompressionMode.Decompress); else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate")) responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); MemoryStream memStream = new MemoryStream(); byte[] respBuffer = new byte[4096]; try { int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); while (bytesRead > 0) { memStream.Write(respBuffer, 0, bytesRead); bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); } } finally { responseStream.Close(); } byte[] msg = memStream.ToArray(); context.Response.ContentLength64 = msg.Length; using (Stream strOut = context.Response.OutputStream) { strOut.Write(msg, 0, msg.Length); } } catch (Exception ex) { // Some error handling } } ``` with sockets. This is what I have so far: ``` void ProcessRequest(object listenerContext) { HttpListenerContext context = (HttpListenerContext)listenerContext; Uri URL = new Uri(context.Request.RawUrl); string getString = string.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\nAccept-Encoding: gzip\r\n\r\n", context.Request.Url.PathAndQuery, context.Request.UserHostName); Socket socket = null; string[] hostAndPort; if (context.Request.UserHostName.Contains(":")) { hostAndPort = context.Request.UserHostName.Split(':'); } else { hostAndPort = new string[] { context.Request.UserHostName, "80" }; } IPHostEntry ipAddress = Dns.GetHostEntry(hostAndPort[0]); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddress.AddressList[0].ToString()), int.Parse(hostAndPort[1])); socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ip); ``` **BEGIN NEW CODE** ``` Encoding ASCII = Encoding.ASCII; Byte[] byteGetString = ASCII.GetBytes(getString); Byte[] receiveByte = new Byte[256]; string response = string.Empty; socket.Send(byteGetString, byteGetString.Length, 0); Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0); response += ASCII.GetString(receiveByte, 0, bytes); while (bytes > 0) { bytes = socket.Receive(receiveByte, receiveByte.Length, 0); strPage = strPage + ASCII.GetString(receiveByte, 0, bytes); } socket.Close(); string separator = "\r\n\r\n"; string header = strPage.Substring(0,strPage.IndexOf(separator)); string content = strPage.Remove(0, strPage.IndexOf(separator) + 4); byte[] byteResponse = ASCII.GetBytes(content); context.Response.ContentLength64 = byteResponse .Length; context.Response.OutputStream.Write(byteResponse , 0, byteResponse .Length); context.Response.OutputStream.Close(); ``` **END NEW CODE** After connecting to the socket I don't know how to get the Stream response to decompress, and send back to **context.Response.OutputStream** Any help will be appreciated. Thanks. Cheers. **EDIT 2:** With this edit now seems to be working fine (same as HttpWebRequest at least). Do you find any error here? **EDIT 3:** False alarm... Still can't get this working **EDIT 4:** I needed to add the following lines to Scott's code ... because not always the first to bytes of reponseStream are the gzip magic number. The sequence seems to be: 0x0a (10), 0x1f (31), 0x8b (139). The last two are the gzip magic number. The first number was always before in my tests. ``` if (contentEncoding.Equals("gzip")) { int magicNumber = 0; while (magicNumber != 10) magicNumber = responseStream.ReadByte(); responseStream = new GZipStream(responseStream, CompressionMode.Decompress); } ```
Here's some code that works for me. ``` using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.IO.Compression; namespace HttpUsingSockets { public class Program { private static readonly Encoding DefaultEncoding = Encoding.ASCII; private static readonly byte[] LineTerminator = new byte[] { 13, 10 }; public static void Main(string[] args) { var host = "stackoverflow.com"; var url = "/questions/523930/sockets-in-c-how-to-get-the-response-stream"; IPHostEntry ipAddress = Dns.GetHostEntry(host); var ip = new IPEndPoint(ipAddress.AddressList[0], 80); using (var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(ip); using (var n = new NetworkStream(socket)) { SendRequest(n, new[] {"GET " + url + " HTTP/1.1", "Host: " + host, "Connection: Close", "Accept-Encoding: gzip"}); var headers = new Dictionary<string, string>(); while (true) { var line = ReadLine(n); if (line.Length == 0) { break; } int index = line.IndexOf(':'); headers.Add(line.Substring(0, index), line.Substring(index + 2)); } string contentEncoding; if (headers.TryGetValue("Content-Encoding", out contentEncoding)) { Stream responseStream = n; if (contentEncoding.Equals("gzip")) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); } else if (contentEncoding.Equals("deflate")) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); } var memStream = new MemoryStream(); var respBuffer = new byte[4096]; try { int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); while (bytesRead > 0) { memStream.Write(respBuffer, 0, bytesRead); bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); } } finally { responseStream.Close(); } var body = DefaultEncoding.GetString(memStream.ToArray()); Console.WriteLine(body); } else { while (true) { var line = ReadLine(n); if (line == null) { break; } Console.WriteLine(line); } } } } } static void SendRequest(Stream stream, IEnumerable<string> request) { foreach (var r in request) { var data = DefaultEncoding.GetBytes(r); stream.Write(data, 0, data.Length); stream.Write(LineTerminator, 0, 2); } stream.Write(LineTerminator, 0, 2); // Eat response var response = ReadLine(stream); } static string ReadLine(Stream stream) { var lineBuffer = new List<byte>(); while (true) { int b = stream.ReadByte(); if (b == -1) { return null; } if (b == 10) { break; } if (b != 13) { lineBuffer.Add((byte)b); } } return DefaultEncoding.GetString(lineBuffer.ToArray()); } } } ``` You could substitute this for the Socket/NetworkStream and save a bit of work. ``` using (var client = new TcpClient(host, 80)) { using (var n = client.GetStream()) { } } ```
Socket, by definition, is the low level to access the network. You can even use datagram protocols with a socket. In that case a stream does not make sense at all. While I'm not sure why are you doing what HttpWebRequest easily accomplishes, to read/write data to a socket, you use the Send/Receive methods. If you want to have a stream like access to a TCP socket, you should use the TcpClient/TcpListener classes which wrap a socket and provide a network stream for it.
Sockets in C#: How to get the response stream?
[ "", "c#", "sockets", "httpwebrequest", "httpwebresponse", "" ]
I am coding in C# 1.1. I want a way to find out all the 'If' clause without the its 'else' clause. Is there any easy way? I am asking this question because I got a project source file from my client which has many IF clause that doesnt have a ELSE clause. This is causing a lot of bugs. So, I want to scan my source file to see if there is any IF clause that doesn't have a ELSE clause. thanks
I think you'll probably need to use a stack because an if could be inside another if. Every time you find an if, push onto the stack. Now look for the end of the phrase. That means either a ; or matching curly braces. After that, check for else. Pop the stack.
If no nifty tools are available: 1. Search for single word if in all files. To get a file with filename and line number. 2. Search for single word else in all files. To get a file with filename and line number. 3. In the first file, add "if" to each line, in the second add "else" 4. Merge files 5. Sort on filename, linenumber, (if/else) 6. Remove all ifs followed by an else. You now have a list of almost all ifs without an else. This method will give some false positives because it does not take commented code into account. But if no tools are available, it is a fair alternative.
'if' without 'else' C#
[ "", "c#", "" ]
Why do we need a DB-specific functions like mysql\_real\_escape\_string()? What can it do that addslashes() doesn't? Ignoring for the moment the superior alternative of parameterized queries, is a webapp that uses addslashes() exclusively still vulnerable to SQL injection, and if yes, how?
Addslashes is generally not good enough when dealing with multibyte encoded strings.
It adds slashes to: ``` \x00, \n, \r, \, ', " and \x1a. characters. ``` Where addslashes only adds slashes to ``` ' \ and NUL ``` [Ilias article](http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html) is also pretty detailed on its functionality
What does mysql_real_escape_string() do that addslashes() doesn't?
[ "", "php", "security", "sql-injection", "" ]
I am trying to write a web application using **ASP.NET MVC**. I prefer **C#** as the programming language. Which IDE is better to use for this purpose? **Visual Studio** or **Visual Web Developer**? What are the features of the IDEs? What are the benefits of using one over the other? Thanks in advance.
As far as I understand, [Visual Web Developer](http://www.microsoft.com/express/vwd/) (VWD) is simply a free version of the [Visual Studio](http://www.microsoft.com/visualstudio/en-us/default.mspx) components necessary to develop web based solutions. [Here is a list of features missing from VWD](http://blogs.msdn.com/mikhailarkhipov/archive/2006/06/26/647516.aspx) that you get in a Professional edition of Visual Studio 2008 (VS2008). In short, VWD Express 2005 > 1. is **Not Extensibile** with other add-ons or third party tools > 2. **Only supports Web site projects (2005).** You cannot add a Class > Library project or a Web Controls > Library project to the solution. > > **UPDATED - VWD 2008 SP1 also allows Web Application and Class Library Projects in the solution**. > > 3. **Lacks** the ability to combine **Source Code Control** > 4. has **no Accessibility checker** > 5. **Lacks** ability for **automatic generation of resources for > localization** > 6. **Cannot attach debugger to a process** > 7. has **no Native code debugging** The obvious advantage of VWD over VS2008 is that it is free and if you can work smart with it given the missing features, it may be the more pragmatic option for you. If those are features that you can't live without, VS2008 may be a wise investment - you also get all of the features missing from other Express products (Visual Basic 2008, Visual C# 2008, etc). Take a look at [MSDN's comparison chart for Visual Studio 2005](http://msdn.microsoft.com/en-us/vstudio/aa700921.aspx). I can't find 2008's but would suspect it to be very similar.
Visual Studio will allow you to integerate with Source control and attached debugging to IIS processes. As a lone developer knocking up some pure ASP.NET-MVC application then Web Developer would do, for serious work you really need studio.
Visual Studio Vs Visual Web Developer
[ "", "c#", "asp.net-mvc", "visual-studio", "ide", "visual-web-developer", "" ]
For a school project I'm making a simple Job Listing website in ASP.NET MVC (we got to choose the framework). I've thought about it awhile and this is my initial schema: > **JobPostings** > +---JobPostingID > +---UserID > +---Company > +---JobTitle > +---JobTypeID > +---JobLocationID > +---Description > +---HowToApply > +---CompanyURL > +---LogoURL > > **JobLocations** > +---JobLocationID > +---City > +---State > +---Zip > > **JobTypes** > +---JobTypeID > +---JobTypeName *Note: the UserID will be linked to a Member table generated by a MembershipProvider.* Now, I am *extremely* new to relational databases and SQL so go lightly on me. What about naming? Should it be just "Description" under the JobPostings table, or should it be "JobDescription" (same with other columns in that main table). Should it be "JobPostingID" or just "ID"? General tips are appreciated as well. Edit: The JobTypes are fixed for our project, there will be 15 job categories. I've made this a community wiki to encourage people to post.
[Job Schema http://gfilter.net/junk/JobSchema.png](http://gfilter.net/junk/JobSchema.png) I split Company out of Job Posting, as this makes maintaining the companies easier. I also added a XREF table that can store the relationship between companies and locations. You can setup a row for each company office, and have a very simple way to find "Alternative Job Locations for this Company". This should be a fun project...good luck. EDIT: I would add Created and LastModifiedBy (Referring to a UserID). These are great columns for general housekeeping.
A few thoughts: * Unless you know a priori that there is a limited list of job types, don't split that into a separate table; * Just use "ID" as the primary key on each table (we already know it's a JobLocationID, because it's in the JobLocations table...); * I'd drop the 'Job' prefix from the fields in JobPostings, as it's a bit redundant. There's a load of domain-specific info that you could include, like salary ranges, and applicant details, but I don't know how far you're supposed to be going with this.
Designing a database schema for a Job Listing website?
[ "", "sql", "sql-server", "" ]
How to hide TabPage from TabControl in WinForms 2.0?
No, this doesn't exist. You have to remove the tab and re-add it when you want it. Or use a different (3rd-party) tab control.
Code Snippet for Hiding a TabPage ``` private void HideTab1_Click(object sender, EventArgs e) { tabControl1.TabPages.Remove(tabPage1); } ``` Code Snippet for Showing a TabPage ``` private void ShowTab1_Click(object sender, EventArgs e) { tabControl1.TabPages.Add(tabPage1); } ```
How to hide TabPage from TabControl
[ "", "c#", "winforms", "tabcontrol", "tabpage", "" ]
Normally, when I use Visual Studio to do a build, I see warnings and errors shown in the output pane, e.g. ``` 1>------ Build started: Project: pdcuda, Configuration: Release x64 ------ Compiling... foo.cpp Linking... foo.obj : error LNK2001: unresolved external symbol "foo" ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` I'm doing some GPU programming with [CUDA](http://www.nvidia.com/object/cuda_home.html). Upon upgrading to 2.1, I no longer get any useful output in Visual Studio. For example, all I now see is: ``` 1>------ Build started: Project: pdcuda, Configuration: Release x64 ------ ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` The other details can be found in BuildLog.htm, but it's inconvenient to hunt that file down all the time. Does anyone know how to force Visual Studio to show the output in its output pane? Things that don't help: * *uninstalling CUDA:* the problem persists in all projects * *Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity:* changing this pulldown, even to "Diagnostic" has no discernable effect. **EDIT:** Additional things that don't help: * devenv.exe /resetsettings * devenv.exe /resetuserdata **UPDATE** *(in response to Die in Sente)*: It's now working on one of the two machines (I'm not sure what I did to fix it though). The machine that's still having problems has a [CUDA Visual Studio Wizard](http://sourceforge.net/projects/cudavswizard) installed that has caused similar problems before. The still-broken machine had version 15.00.21022.8 of the compiler. The working machine has 15.00.30729.1. After making a backup, I transferred "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64" from the working to the broken machine. I observe no changes in behavior on the broken machine.
Final solution: reinstall the OS.
I have exactly the same problem, but without CUDA. Today Visual Studio just decided it wasn't going to show any build messages anymore. It was working fine, then one of my builds it just stopped working. The problem persists over all my projects now, and persists over reboots. I also see the correct messages in buildlog.htm. This is ridonkulous! EDIT: Ooh, I used the add/remove programs to do a repair, and now it works again! Yeah!
CUDA + Visual Studio = suppressed output window
[ "", "c++", "visual-studio", "cuda", "" ]
I'm trying to create a function which will add an overlay to a thumbnail image when you hover over it and remove the overlay when you leave it. Here is my HTML... ``` <div class="thumb"><img src="i/testThumb.gif" /></div> ``` And here is my jQuery... ``` $('.thumb').live('mouseover', function(event){ if($(this).find('.overlay').length == 0){ $(this).prepend('<div class="overlay"></div>'); } return false; }); $('#galleryPanel .thumb').live('mouseout', function(event){ $(this).find('.overlay').remove(); return false; }); ``` The trouble is that when the overlay is created the mouse is already over it and that triggers the "mouseout" of the container, which removes the overlay, and it cycles continuously flashing on and off. Is there an easy solution to this?
I you put one more div into the mix, I think you may find what you are looking for. ``` <style> .hover { display:none;} </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script> $(document).ready(function(){ $(".image").hover( function(over) { $(this).find(".hover").animate({opacity: "show", top: "55"}, "slow"); }, function(out) { $(this).find(".hover").animate({opacity: "hide", top: "55"}, "slow"); }); }); </script> <div class='image'> <div class='imageClass'> <img src='img1.jpg' /> <div class='hover'> <img src='img1.jpg' /> </div> </div> </div> ```
Instead of binding mouseout to ".thumb" trying binding it to ".overlay". ``` $('#galleryPanel .overlay').live('mouseout', function(event){ $(this).remove(); return false; }); ```
jQuery mouseout firing when injecting child element
[ "", "javascript", "jquery", "events", "jquery-events", "" ]
Interested in description of your most used ASP.NET httpmodules that solved a specific problem for your webapp. Best practices and in-the-field usages are welcome.
[MBCompression](http://www.codeplex.com/MbCompression): handlers and modules to compress Css files, JavaScript files, pages and WebResource.axd. I use it in environments where I don't have full control of the server and native IIS compression is not possible.
[ELMAH](http://msdn.microsoft.com/en-us/library/aa479332.aspx) is very popular and useful for exception logging in ASP.NET applications.
ASP.NET: Your most used httpmodules
[ "", "c#", "asp.net", ".net", "windows", "httpmodule", "" ]
Is it possible to cast an object to the type returned from `GetType()`? I'd like a generic method that can accept an object (for anonymous types) but then return an object cast as the anonymous type. I've been thinking of using the LCG DynamicMethod to build a method on a container class, but I can't exactly figure out what that would look like. The idea to cast with the `GetType()` method was to be able to get the anonymous type and cast an object to its actual type without actually knowing the type. The overarching goal is to stick anonymous-typed objects into a container, that I could then share and pass between methods.
Your intent is very unclear; however, one option is generics and `MakeGenericMethod` in particular. What do you want to do with this? For example: ``` static class Program { static void Main() { object obj = 123.45; typeof(Program).GetMethod("DoSomething") .MakeGenericMethod(obj.GetType()) .Invoke(null, new object[] { obj }); } public static void DoSomething<T>(T value) { T item = value; // well... now what? } } ``` So now we have the value, typed as `double` via generics - but there still isn't much we can do with it except for calling *other* generic methods... what was it you want to do here?
I can't think of why you'd want to cast as GetType(), because you wouldn't be able to do anything to useful with the result, without knowing the type at compile time anyway. Perhaps what you are looking for, is being able to Convert. If that is the case, the following should work for you: ``` object input = GetSomeInput(); object result = Convert.ChangeType(input, someOtherObject.GetType()); ``` We use this when reading values from the registry which are all stored as strings, and then stuffing them into properties using reflection.
Cast with GetType()
[ "", "c#", "reflection", "casting", "" ]
What is the difference between ``` private void DoSomething(int value) { value++; } ``` and ``` private int DoSomething(int value) { return value++; } ``` when used as either ``` DoSomething(value); ``` versus ``` value = DoSomething(value); ```
You are talking about the difference between **passing by reference** and **passing by value**, which is conceptually similar to the idea of **value types vs reference types**. If you pass a **value type** into the method, you have to use the second example; otherwise you are just incrementing an integer that exists inside the scope of DoSomething(). Try it: if you execute your first example, after DoSomething() has run, the value of your int will be unchanged. However, if you are passing in something other than a value type (say object foo), you are actually **passing a reference** to the original object. Anything you do to it inside DoSomething() will take effect outside the method as well, since you are still referring to the same object. You can accomplish what you're attempting in the first example by writing: ``` void DoSomething(ref int value) ``` That instructs .NET to pass a reference to the item regardless of whether it is a value type. See this writeup on **[Value Types vs Reference Types](http://msdn.microsoft.com/en-us/library/t63sy5hs(VS.80).aspx)** on MSDN for a more detailed look. Additionally, as [zodoz points out](https://stackoverflow.com/questions/555471/modify-method-parameter-within-method-or-return-result/555502#555502) (upvote appropriately), by returning `value++` you are returning and then incrementing. To return the incremented value, use `++value`.
**Return a value.** Why? **Correctness, Readability, and Self-Documentation** Intentional and easy to understand code is better than side-effect code. Consider: ``` float area = pi * Square(r); ``` vs. ``` Square(r); float area = pi * r; // ... intervening code float x = r * 5; // did you mean to use the original r or r-squared here? ``` Also consider the advantages of terseness through composability in the first example. Consider the methods themselves, compare: ``` int DoSomething(int value) { return value+1; } ``` Which is pretty obviously correct. vs. ``` void DoSomething(int value) { value++; } ``` Which seems right and will compile just fine but is actually just a no-op. What you really want is this: ``` void DoSomething(ref int value) { value++; } // client code: DoSomething(ref a); ``` **Variables are Cheap** Many well-named variables is preferable over few reused general purpose variables. Resist the temptation to prematurely optimize, the chance that you will need to cut down on the number of local variables to improve the performance of your system is cosmically tiny. **Again, Variables are Cheap, DON'T REUSE VARIABLES!** **Testability** Consider: ``` Assert.IsTrue(Square(2) == 4); ``` vs. ``` float a = 2; Square(a); Assert.IsTrue(a == 4); ``` There are many other advantages to avoiding mutation in preference to returning a value. It's not merely an accident that mathematics defines a function as a mapping of input values to output values.
Modify method parameter within method or return result
[ "", "c#", ".net", "parameter-passing", "" ]
I'm working with a winForms app that has a listView. That listView has multi-select enabled and I have many, many items in the list (in row view). When I select the last row (i.e. item), then shift-click the 5000th row, SelectedIndexChanged fires 5000 times. If this happens, I end up in a very nasty loop. The last row clicked is not guaranteed to be the last item in the "SelectedItems" list. How do I get the actual item clicked? EDIT: Better clarification: How do I get my hands on the ListViewItem that CAUSED this particular iteration of the SelectedIndexChanged event? ... even if I have to check all 5000 of them. I need to know which one I'm looking at. EventArgs does not have an index property, and sender is the ListView, not the ListViewItem. Any thoughts?
OH, FOR THE LOVE OF PETE... (\* feels dumber than a rock \*) I found my answer. Note that I am using SelectedIndexChanged. There is another event that I *should* have been using: ItemSelectionChange. When using that event, I now have events that can tell me which items changed in the selection and it tells me if the item was Selected or Unselected. It's beautiful. I hope that helps others that are fighting this issue.
Here's the best solution I can think of. Handle the ListView's OnMouseMove event. Whenever the mouse moves, record the location of the mouse. Then when you get a SelectedIndexChangedEvent you can call ListView.FindNearestItem(SearchDirectionHint, Point) and pass in the last mouse coordinates as the Point parameter. This should give you the item that was actually clicked. Note you can't depend on it actually returning an item though. It's perfectly possible to select an item without every using the mouse. A couple of tabs and space bar will do the trick. But for actual clicks, this should do the trick.
C# : How do I get the actual item clicked from SelectedIndexChanged for a ListView control?
[ "", "c#", "winforms", "multithreading", "" ]
I´m using the LinqDataSource to populate a grid. But now I need the SQL query that the LinqDataSource generates, to pass around throught methods (no, I can't modify the methods to not need a SQL query). Is there a way to obtain the generated SQL query from a instantiated and configured LinqDataSource?
Hope this helps. using the function below will return a SqlQueryText you can rebuild the query from that object. * to get the sql text you can use use the .Text Property * to get the passed parameters you can use the .Params property ``` public static SqlQueryText GetFullQueryInfo(DataContext dataContext, IQueryable query) { DbCommand dbCommand = dataContext.GetCommand(query); var result = new SqlQueryText(); result.Text = dbCommand.CommandText; int nParams = dbCommand.Parameters.Count; result.Params = new ParameterText[nParams]; for (int j = 0; j < nParams; j++) { var param = new ParameterText(); DbParameter pInfo = dbCommand.Parameters[j]; param.Name = pInfo.ParameterName; param.SqlType = pInfo.DbType.ToString(); object paramValue = pInfo.Value; if (paramValue == null) { param.Value = null; } else { param.Value = pInfo.Value.ToString(); } result.Params[j] = param; } return result; } ``` here is an example var results = db.Medias.Where(somepredicatehere); ClassThatHasThisMethod.GetFullQueryInfo(yourdatacontexthere, results); EDIT: Sorry forgot to include the SqlQueryText data structures ``` public struct SqlQueryText { public ParameterText[] Params; public string Text; } public struct ParameterText { public string Name; public string SqlType; public string Value; } ```
You can run SQL Profiler while running your application and that should give it to you.
Can I get the T-SQL query generated from a LinqDataSource?
[ "", "sql", "linq", ".net-3.5", "linqdatasource", "" ]
I am working on a C++ program and the compiled object code from a single 1200-line file (which initializes a rather complex state machine) comes out to nearly a megabyte. What could be making the file so large? Is there a way I can find what takes space inside the object file?
There can be several reasons when object files are bigger than they have to be at minimum: * statically including dependent libraries * building with debug information * building with profiling information * creating (extremely) complex data structures using templates (maybe recursive boost-structures) * not turning on optimizing flags while compiling (saves not that much and can cause difficulties if used too extremely) At first I suggest to check if you're building with debug information, this causes the most bloat in my experience.
(I'm assuming you've got optimisations and dead code stripping turned on). Turn on your linker's "generate map file" option and examine the output. Common culprits are macros/templates that produce large amounts of code, and large global objects.
My C++ object file is too big
[ "", "c++", "compiler-optimization", "filesize", "object-files", "" ]
I've just read this [nice piece](http://www.vandevoorde.com/C++Solutions/) from Reddit. They mention `and` and `or` being "Alternative Tokens" to `&&` and `||` I was really unaware of these until now. Of course, everybody knows about the [di-graphs and tri-graphs](http://en.wikipedia.org/wiki/C_trigraph), but `and` and `or`? Since when? Is this a recent addition to the standard? I've just checked it with Visual C++ 2008 and it doesn't seem to recognize these as anything other than a syntax error. What's going on?
MSVC supports them as keywords only if you use the `/Za` option to disable extensions; this is true from at least VC7.1 (VS2003). You can get them supported as macros by including `iso646.h`. My guess is they believe that making them keywords by default would break too much existing code (and I wouldn't be surprised if they are right).
From the *first* ISO C++ standard `C++98`, this is described in `2.5/ Alternative tokens [lex.digraph]`: --- 1. Alternative token representations are provided for some operators and punctuators. 2. In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2. ``` Table 2 - Alternative tokens alternative primary | alternative primary | alternative primary --------------------+---------------------+-------------------- <% { | and && | and_eq &= %> } | bitor | | or_eq |= <: [ | or || | xor_eq ^= :> ] | xor ^ | not ! %: # | compl ~ | not_eq != %:%: ## | bitand & | ``` --- So it's been around since the earliest days of the C++ standardisation process. The reason so few people are aware of it is likely because the main use case was for people operating in environments where the full character set wasn't necessarily available. For example (and this is stretching my memory), the baseline EBCDIC character set on the IBM mainframes did not have the square bracket characters `[` and `]`.
When were the 'and' and 'or' alternative tokens introduced in C++?
[ "", "c++", "syntax", "keyword", "digraphs", "trigraphs", "" ]
I'm trying to implement some kind of caching in a PHP script that will go out to many different clients/sites, which will be deployed by fairly non-technical users, using a variety of web hosts. Due to the non-technical nature of the users, I'd like to avoid asking them to tweak file permissions. The caching needs to be across sessions, so using session variables is out. If I was coding this in ASP I'd use application variables, but they don't exist in PHP (to my knowledge) Does anyone have any suggestions on how to accomplish this? Here are some possibilities I've considered, any comments on these would be useful: * Caching via files in system temp folders - I could use sys\_get\_temp\_dir() (or some home rolled similar function on PHP4) to help find such a folder. The disadvantage here, is it probably wouldn't work on hosts using the openbase\_dir restriction * Some website I looked at mentioned tricking PHP into making all user sessions share the same session state thereby forcing session variables to act like session variables. Of course I can't find that post now... This seems scary anyway. (I'll update this question with the link to this post once I find it again) * Use a third party data store like Amazon's Simple Storage Service - seems like overkill * Cache the data on a server I control, and have the client download new data from there on each hit. Once again, any comments on these ideas or any new ones would be appreciated. **UPDATE:** I tried using session\_id() to use a shared session state, but it doesn't work. Each session is maintaining its own "GlobalCache", any ideas why?: ``` // This code doesn't work, but the similar code in my answer does! function test() { if (!$_SESSION['session_count']) $_SESSION['session_count'] = 0; $_SESSION['session_count']++; $count = get_cache( 'count' ); print "pre application count: $count<br>"; if ( !$count ) $count = 0; $count++; print "session_id: " . session_id() . "<br>"; print "post application count: $count<br>"; print "session_count: " . $_SESSION['session_count'] . "<br>"; set_cache('count', $count); } function set_cache( $name, $value ) { $old_session = session_id(); print "old_session (set): $old_session<br>"; session_id("GlobalCache"); print "new_session (set): " . session_id() . "<br>"; $_SESSION[$name] = $value; session_id( $old_session ); } function get_cache( $name ) { $old_session = session_id(); print "old_session (get): $old_session<br>"; session_id("GlobalCache"); print "new_session (get): " . session_id() . "<br>"; $value = $_SESSION[$name]; session_id( $old_session ); return $value; } session_start(); test(); ``` **UPDATE:** some have suggested using memcached, which is in fact a great solution for some, but since I don't have control over the end server environment it isn't an option. The idea is to have a script that people can just FTP up to a shared hosting account that just works out of the box. **UPDATE:** someone suggested creating my own cache folder with the script, but wouldn't I need to create such a folder inside a folder that already had write permissions? **UPDATE, SOLUTION FOUND:** I ended up figuring out the problems in my global session script and have posted my own answer to that effect. Thanks for the help everyone.
Okay, I figured out how to do this by emulating ASP-style application variables using a shared/global session state. Two key changes from my non-working code in the relevant update: 1. To switch session state, we must end the current session, switch to the new one, then start it. I've encapsulated this process in switch\_session() 2. Since we are switching session ids around we have to buffer the page's output using ob\_start()/ob\_end\_flush() so that the session cookie isn't sent too soon. The full working code follows (cleaned up too!). This can be easily tested by loading the page in an IE and a Firefox window, and reloading each several times to watch the counters rise: ``` <?php function test() { // Do a regular session count print "session_id: " . session_id() . "<br>"; if (!$_SESSION['session_count']) $_SESSION['session_count'] = 0; $_SESSION['session_count']++; print "session count: " . $_SESSION['session_count'] . "<br>"; // Do an application count $count = get_cache( 'count' ); if ( !$count ) $count = 0; $count++; print "application count: $count<br>"; set_cache('count', $count); } function set_cache( $name, $value ) { $old_session = switch_session("GlobalCache"); $_SESSION[$name] = $value; switch_session( $old_session ); } function get_cache( $name ) { $old_session = switch_session("GlobalCache"); $value = $_SESSION[$name]; switch_session( $old_session ); return $value; } function switch_session( $session_id ) { // switch the session and return the original $old_id = session_id(); session_write_close(); session_id($session_id); session_start(); return $old_id; } ob_start(); session_start(); test(); ob_end_flush(); ?> ```
You could use sessions with a fixed session key. <http://de.php.net/manual/en/function.session-id.php>: > session\_id([id]) is used to get or set the session `id` for the current session. > If id is specified, it will replace the current session id. session\_id() needs to be called before session\_start() for that purpose.
PHP Caching without messing with file permissions (Also, How to emulate ASP Application variables in PHP)
[ "", "php", "caching", "file-permissions", "application-variables", "" ]
On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how. I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django). Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application?
Once upon a time Internet Explorer supported NTLM authentication (similar to Basic Auth but it sent cached credentials to the server which could be verified with the domain controller). It was used to enable single-signon within an intranet where everyone was expected to be logged into the domain. I don't recall the details of it and I haven't used it for ages. It may still be an option if it fits your needs. Maybe someone more familiar with it may have more details. See: [NTLM Authentication Scheme for HTTP](http://www.innovation.ch/personal/ronald/ntlm.html) The tricky part of using non-microsoft server framework is going to be talking with the necessary services to verify the credentials.
From [here](http://www.djangosnippets.org/snippets/501/): ``` -- Added to settings.py -- ### ACTIVE DIRECTORY SETTINGS # AD_DNS_NAME should set to the AD DNS name of the domain (ie; example.com) # If you are not using the AD server as your DNS, it can also be set to # FQDN or IP of the AD server. AD_DNS_NAME = 'example.com' AD_LDAP_PORT = 389 AD_SEARCH_DN = 'CN=Users,dc=example,dc=com' # This is the NT4/Samba domain name AD_NT4_DOMAIN = 'EXAMPLE' AD_SEARCH_FIELDS = ['mail','givenName','sn','sAMAccountName'] AD_LDAP_URL = 'ldap://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT) -- In the auth.py file -- from django.contrib.auth.models import User from django.conf import settings import ldap class ActiveDirectoryBackend: def authenticate(self,username=None,password=None): if not self.is_valid(username,password): return None try: user = User.objects.get(username=username) except User.DoesNotExist: l = ldap.initialize(settings.AD_LDAP_URL) l.simple_bind_s(username,password) result = l.search_ext_s(settings.AD_SEARCH_DN,ldap.SCOPE_SUBTREE, "sAMAccountName=%s" % username,settings.AD_SEARCH_FIELDS)[0][1] l.unbind_s() # givenName == First Name if result.has_key('givenName'): first_name = result['givenName'][0] else: first_name = None # sn == Last Name (Surname) if result.has_key('sn'): last_name = result['sn'][0] else: last_name = None # mail == Email Address if result.has_key('mail'): email = result['mail'][0] else: email = None user = User(username=username,first_name=first_name,last_name=last_name,email=email) user.is_staff = False user.is_superuser = False user.set_password(password) user.save() return user def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def is_valid (self,username=None,password=None): ## Disallowing null or blank string as password ## as per comment: http://www.djangosnippets.org/snippets/501/#c868 if password == None or password == '': return False binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN) try: l = ldap.initialize(settings.AD_LDAP_URL) l.simple_bind_s(binddn,password) l.unbind_s() return True except ldap.LDAPError: return False ```
Can I log into a web application automatically using a users windows logon?
[ "", "python", "authentication", "web-applications", "windows-authentication", "" ]
I'd like to call a Stored Procedure from a crystal report and assign retrieved value to a field in report? Any suggestions?
To call Stored Procedure from crystal report, Set data source of report to Stored Procedure (DataBase Expert Wizard). That procedure must met thses requirement 1- You must create a package that defines the REF CURSOR (type of field that will be retrieved). 2- The procedure must have a parameter that is a REF CURSOR type. This is because CR uses this parameter to access and define the result set that the stored procedure returns. 3- The REF CURSOR parameter must be defined as IN OUT (read/write mode). 4- Parameters can only be input (IN) parameters. CR is not designed to work with OUT parameters. 5- The REF CURSOR variable must be opened and assigned its query within the procedure. 6- The stored procedure can only return one record set. The structure of this record set must not change, based on parameters. 7- The stored procedure cannot call another stored procedure.
Try **Database Expert -> (left tree)Current Connections -> Add Command** In **Add Command To Report** screen input something like: ``` EXEC dbo.StoredProcedure (param1, param2 ...) ``` In the same screen you can specify parameters for this query. As a result, new data source, based at the query command, will be created. You can use it as an ordinary data source and place values of fields in the report area.
How to call StoredProcedure from CrystalReport?
[ "", "c#", ".net", "stored-procedures", "crystal-reports", "" ]
My workshop has recently switched to Subversion from SourceSafe, freeing us from automatic locks. This led to concurrent editing of the Forms, which is wonderful. But when multiple developers commit their changes, the code files created by the designer (all the files named `TheFormName.designer.cs`) cause conflicts which are very difficult to resolve. As far as I can tell, this is because the code generated by the designer is heavily re-arranged whenever the user modifies it, no matter how little the actual change really did. * How do I make these conflicts easier to resolve? * Is there some way to tell the designer to modify the code less? * How do you, the experienced C# teams, deal with concurrent modification of a Form?
I'm not familiar with C# or the Windows Form Designer, but looking at some `designer.cs` files I could find online they don't have a particularly complicated structure. What parts of it are being re-arranged? I guess it's mostly the order of the properties in the `InitializeComponent()` method that's jumbled up? If that's the case, you might be able to write a simple script that re-orders those lines alphabetically, say (especially if you never edit these files manually anyway), and use that as a [pre-commit hook script](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.create.html#svn.reposadmin.create.hooks) in Subversion. Um, right... scratch that. The big red box at the bottom of that section says you're not supposed to modify transactions in hook scripts. But you might be able to find another way to run that script somewhere between the `designer.cs` file being changed and it being committed. ### Edit: Actually, given scraimer's comment on this: > Total hack, but in the worst case, just before a merge, I could sort BOTH files, and make the merge simply a line-by-line affair... Can't you let Subversion set an external merge program? I've been using [KDiff3](http://kdiff3.sourceforge.net/), which can [run a preprocessor command before doing diffs or merges](http://kdiff3.sourceforge.net/doc/preprocessors.html), so you could automate that process.
Here are some things to try: * Make things more modular. Use components like User Controls etc. to split forms into multiple, smaller physical files. * Use presentation layer design patterns like MVP to move code out of views and into standard POCO classes. * Recent versions of SVN allow you to take hard locks - use this to avoid complex merge scenarios. Hope that helps.
Why does C# designer-generated code (like Form1.designer.cs) play havoc with Subversion?
[ "", "c#", "visual-studio", "svn", "version-control", "windows-forms-designer", "" ]
I need to encrypt some PHP source that I've released to the public. Is this possible? Can PHP be "compiled" ?
You can buy [Zend Guard](http://www.zend.com/en/products/guard/) to encode your PHP sources, and then use the [Zend Optimizer](http://www.zend.com/en/products/guard/optimizer/) to run it. There is an opensource/free PHP compiler project as well ([bcompiler](https://www.php.net/bcompiler), and also take a look to [this](http://pecl.php.net/package/bcompiler)) but I never used it because at the time I needed it the project was still incomplete.
You can have a look at [phc](http://www.phpcompiler.org/) which can generate executables from PHP. It also has some other options to create C-code, XML, optimized PHP, etc. from the original PHP source.
Can I encrypt PHP source or compile it so others can't see it? and how?
[ "", "php", "obfuscation", "" ]
Is it possible to print the class name from within a static function? e.g ... ``` public class foo { static void printName() { // Print the class name e.g. foo } } ```
You have three options to get the type (and therefore the name) of `YourClass` that work in a static function: 1. `typeof(YourClass)` - fast (0.043 microseconds) 2. `MethodBase.GetCurrentMethod().DeclaringType` - slow (2.3 microseconds) 3. `new StackFrame().GetMethod().DeclaringType` - slowest (17.2 microseconds) If using `typeof(YourClass)` is not desirable, then `MethodBase.GetCurrentMethod().DeclaringType` is definitely the best option.
``` Console.WriteLine(new StackFrame().GetMethod().DeclaringType); ```
c# print the class name from within a static function
[ "", "c#", "static", "" ]
Folks, Assume you receive a disconnected backup of a SQL Server database (2005 or 2008) and you restore that to your SQL Server instance. Is there a way, is there a system catalog or something, to find out when the last write operation occured on that particular database? I'd like to be able to find out what day a particular database backup was from - unfortunately, that's not really being recorded explicitly anywhere, and checking all dozens of data table for the highest date/time stamp isn't really an option either.... Any ideas? Sure - I can look at the date/time stamp of the \*.bak file - but can I find out more precisely from within SQL Server (Management Studio) ?? Thanks! Marc
You can try `RESTORE HEADERONLY` on your backup file, as described [here](http://msdn.microsoft.com/en-us/library/aa238455(SQL.80).aspx) that should give you the information you're looking for.
If you have access to the SQL Server instance where the backup was originally run, you should be able to query `msdb`: ``` SELECT backup_set_id, backup_start_date, backup_finish_date FROM msdb.dbo.backupset WHERE database_name = 'MyDBname' AND type = 'D' ``` There are several table relating to backup sets: * backupfile -- contains one row for each data file or log file backed up * backupmediafamily -- contains one row for each media family * backupmediaset -- contains one row for each backup media set * backupset -- contains one row for each backup set By querying these tables you can determine when the last backups occurred, what type of backups occurred and where the files were written to.
Find out when a database backup was made
[ "", "sql", "sql-server", "database", "restore", "" ]
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post. Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? It would be perfect if I could just get the entire difference in seconds.
It seems that Python 2.7 has introduced a [total\_seconds()](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) method, which is what you were looking for, I believe!
You can compute the difference in seconds. ``` total_seconds = delta.days * 86400 + delta.seconds ``` No, you're no "missing something". It doesn't provide deltas in seconds.
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
[ "", "python", "datetime", "timedelta", "" ]
For some reason, my SQL installation isn't working :) ``` SELECT DATEADD(s,1234567890, '19700101') ``` Maybe [this site](http://coolepochcountdown.com/) would help (link from [Moose](https://stackoverflow.com/users/19032/moose)).
Total awesomeness!
I get this: ``` 2009-02-13 23:31:30.000 ```
What's the result of the SQL statement "SELECT DATEADD(s,1234567890, '19700101')"?
[ "", "sql", "date", "time", "epoch", "" ]
In plain Java SE 6 environment: ``` Logger l = Logger.getLogger("nameless"); l.setLevel(Level.ALL); l.fine("somemessage"); ``` Nothing shows up in Eclipse console. *l.info("")* and above works just fine, but anything below *fine* just doesn't seem to work. What's could be wrong? TIA.
Even though the Logger level is set to ALL, the ConsoleHandler (the default Handler on the logger) still has a default level of INFO. This comes from the default logging.properties in *JAVA\_HOME/jre/lib*
Instead of looping through all handlers and set the logging level, I prefer to set only the level of the console handler: ``` //get the top Logger Logger topLogger = java.util.logging.Logger.getLogger(""); // Handler for console (reuse it if it already exists) Handler consoleHandler = null; //see if there is already a console handler for (Handler handler : topLogger.getHandlers()) { if (handler instanceof ConsoleHandler) { //found the console handler consoleHandler = handler; break; } } if (consoleHandler == null) { //there was no console handler found, create a new one consoleHandler = new ConsoleHandler(); topLogger.addHandler(consoleHandler); } //set the console handler to fine: consoleHandler.setLevel(java.util.logging.Level.FINEST); ```
java.util.logging.Logger doesn't respect java.util.logging.Level?
[ "", "java", "logging", "" ]
I have a function which takes a reference to an object: ``` void move(Ball& ball); ``` I have another function calling 'move()' which has a pointer to ball: ``` void foo(Ball* ball){ //call move() } ``` How is `foo()` supposed to pass ball to `move()`? Should it be like: ``` move(*ball); ``` or: ``` move(ball); ``` or: ``` move(&ball); ```
The first one, move(\*ball). the second one, move(ball) tries to pass the pointer and the third one, move(&ball) tries to pass a pointer to a pointer.
move(\*ball); Here's why. You can think of a reference as basically taking a pointer to the object it is handed. Thus you want the object itself, not a pointer. If you call move(ball) you will be taking a reference (pointer) to the pointer, not the object. Instead, move(\*ball) dereferences the pointer and the reference then takes the pointer of that dereferenced object.
I've got a pointer to an object. How do I call a function that expects a reference?
[ "", "c++", "pointers", "reference", "" ]
I've recently noticed some behaviour with the Visual Studio Designer (C#) that I don't understand and was wondering if someone could clarify... One some of my Windows Forms, the first line of the designer generated code reads; ``` this.components = new System.ComponentModel.Container(); ``` When this is the case, the dispose method, in that same designer file, the dispose method places two "Dispose" calls within the case "if" condition as follows; ``` protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); base.Dispose(disposing); } } ``` i.e. Nothing is called unless disposing is true, AND components is not null. On some other forms, that first line in the designer generated code is missing. In these cases the base.Dispose call is outside the "if" condition as such... ``` protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } ``` I have noticed this while tracking down a bug with a form not closing, where this.components was null, yet the base.Dispose call was inside that condition (I suspect the designer code had been tampered with but that's another story. What controls this behaviour? (Some earlier forms in the project were created in VS 2005 and we now use VS 2008 - clue?)
This is reproducible behavior. When you create a new form, it starts out with a skeleton that includes the this.components constructor call. When you then add a component (say a Timer) and remove it again, the designer regenerates the code, now without the constructor call. That isn't a bug. Fwiw, the skeleton code is generated by `Common7\IDE\ItemTemplates\CSharp\Windows Forms\1033\Form.zip\form.designer.cs` Seeing the base.Dispose() call inside the if() statement is a bug. That might be self-induced. Or it might be a beta version of the skeleton code. VS2005 does it right. Do check the ItemsTemplatesCache folder.
6 years later and this problem still occurs. I've managed to track down at least one cause for it happening. When testing if your component has a constructor that takes an IContainer, System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer caches a reference to the Type of IContainer for your project. If you then save an object for another project within the same solution, or perhaps when you have made some other types of changes in your project, ComponentCodeDomSerializer can no longer find the constructor as the Type of IContainer is no longer equal to it's cached Type. If this is happening lots for your project, there is a very ugly workaround. Add this [VB](http://pastebin.com/tB3VGZDc) or [C#](http://pastebin.com/LUcFdGHD) `VisualStudioWorkaroundSerializer` class to your solution. Then add the attribute `DesignerSerializer(GetType(VisualStudioWorkaroundSerializer), GetType(CodeDomSerializer))` to your component. Whenever your component is saved, this custom serializer will detect the problem, fix it, and force you to save again whenever this issue is about to occur.
Why does the Visual Studio IDE sometimes initialize the "this.components object: and other times not?
[ "", "c#", "visual-studio", "winforms", "visual-studio-2008", "visual-studio-2005", "" ]
I need a PHP library/script that can retreive data from feeds, no matter if they are RSS or ATOM, because I want users to insert random feeds which will then be stored in a database. It would also be great if it could check whether a given URL is a feed or not. If anything exists that could help me out, could anyone tell me? Thanks!
Try these two, they both do RSS and Atom: * [SimplePie](http://simplepie.org/) * [PHP Universal Feed Parser](http://www.ajaxray.com/blog/2008/05/02/php-universal-feed-parser-lightweight-php-class-for-parsing-rss-and-atom-feeds/)
[Zend\_Feed](http://framework.zend.com/manual/en/zend.feed.html) > Zend\_Feed provides functionality for > consuming RSS and Atom feeds. It > provides a natural syntax for > accessing elements of feeds, feed > attributes, and entry attributes. > Zend\_Feed also has extensive support > for modifying feed and entry structure > with the same natural syntax, and > turning the result back into XML. In > the future, this modification support > could provide support for the Atom > Publishing Protocol. You don't have to use the entire Zend Framework, just take the Zend\_Feed component and its dependencies.
Is there a PHP feed reader for both RSS and ATOM?
[ "", "php", "rss", "atom-feed", "" ]
Im trying to write a small class to better understand bit flags in c++. But something isnt working out. It prints the wrong values. Where is the problem? Have I misunderstood how to add flags? Or check if the bit field has them? Heres the code: ``` #include <iostream> enum flag { A = 1, B = 2, C = 4 }; class Holder { public: Holder() : m_flags(A) {} ~Holder() {} void add_flag(flag f) { m_flags |= f; } bool has_flag(flag f) { return ((m_flags&f)==f); } void remove_flag(flag f) { unsigned int flags = 0; for (int i = 1; i<=(int)C; i *= 2) { if ((flag)i!=f && has_flag(f)) flags |= f; } m_flags = flags; } void print() { std::cout << "flags are now: " << m_flags << " | holding: "; for (int i = 1; i<=(int)C; i *= 2) { if (has_flag((flag)i)) std::cout << i << " "; } std::cout << std::endl; } private: unsigned int m_flags; }; int main() { Holder h; h.print(); // should print 1 h.add_flag(B); h.print(); // should print 1 2 h.remove_flag(A); h.print(); // should print 2 h.add_flag(C); h.print(); // should print 2 4 h.remove_flag(B); h.print(); // should print 4 } ``` Output of program: ``` flags are now: 1 | holding: 1 flags are now: 3 | holding: 1 2 flags are now: 1 | holding: 1 flags are now: 5 | holding: 1 4 flags are now: 0 | holding: ```
personally I would use std::vector< bool > to handle flags, since it is a specialization that packs bools into bit. However: I think your remove flag is a bit complex, try this instead ``` void remove_flag( flag f ) { if ( has_flag( f ) == true ) { m_flags ^= f; // toggle the bit leaving all other unchanged } } ``` Edit: A comment asked why I just didn't `do m_flags &= ~f`. I took the question as a 'learner' question not an optimization question. I show how to make his code correct, not fast.
There's a bug in your remove\_flag() method, it should be flags |= i; But, do it O(1) like this: ``` void remove_flag(flag f) { m_flags &= ~f; } ```
Enum bitfield container class
[ "", "c++", "enums", "bit-fields", "bitflags", "" ]
`Const` is baked into the client code. `Readonly` isn't. But `const` is faster. May be only slightly though. The question is, is there ever any scenario where you should prefer `const` over `readonly`? Or to rephrase, are we not practically *always* better off using a `readonly` instead of a `const` (keeping in mind the above-said baking thing)?
I believe the only time "const" is appropriate is when there is a spec that you're coding against that is more durable than the program you're writing. For instance, if you're implementing the HTTP protocol, having a const member for "GET" is appropriate because that will never change, and clients can certainly hard-code that into their compiled apps without worrying that you'll need to change the value later. If there's any chance at all you need to change the value in future versions, don't use const. Oh! And never assume const is faster than a readonly field unless you've measured it. There are JIT optimizations that may make it so it's actually exactly the same.
[Const vs readonly](http://weblogs.asp.net/psteele/archive/2004/01/27/63416.aspx): > A quick synopsis on the differences > between 'const' and 'readonly' in C#: > 'const': > > * Can't be static. > * Value is evaluated at ***compile time.*** > * Initiailized at declaration only. > > 'readonly': > > * Can be either instance-level or static. > * Value is evaluated at ***run time.*** > * Can be initialized in declaration or by code in the constructor. The above states const can't be static. That is a misnomer. They can't have the static keyword applied because they are already static. So you use const for static items that you want evaluated at compile-time.
When, if ever, should we use const?
[ "", "c#", "constants", "readonly", "" ]
I have a table, 'lasttraces', with the following fields. ``` Id, AccountId, Version, DownloadNo, Date ``` The data looks like this: ``` 28092|15240000|1.0.7.1782|2009040004731|2009-01-20 13:10:22.000 28094|61615000|1.0.7.1782|2009040007696|2009-01-20 13:11:38.000 28095|95317000|1.0.7.1782|2009040007695|2009-01-20 13:10:18.000 28101|15240000|1.0.7.1782|2009040004740|2009-01-20 14:10:22.000 28103|61615000|1.0.7.1782|2009040007690|2009-01-20 14:11:38.000 28104|95317000|1.0.7.1782|2009040007710|2009-01-20 14:10:18.000 ``` How can I, in [LINQ to SQL](http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL), only get the last lasttrace of every AccountId (the one with the highest date)?
If you just want the last date for each account, you'd use this: ``` var q = from n in table group n by n.AccountId into g select new {AccountId = g.Key, Date = g.Max(t=>t.Date)}; ``` If you want the whole record: ``` var q = from n in table group n by n.AccountId into g select g.OrderByDescending(t=>t.Date).FirstOrDefault(); ```
Here is a simple way to do it ``` var lastPlayerControlCommand = this.ObjectContext.PlayerControlCommands .Where(c => c.PlayerID == player.ID) .OrderByDescending(t=>t.CreationTime) .FirstOrDefault(); ``` Also have a look this great LINQ place - [LINQ to SQL Samples](http://msdn.microsoft.com/en-us/vstudio/bb688085)
How to select only the records with the highest date in LINQ
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
I'm trying to build an "edit" page for a database record that can be edited and saved back to the database. One of the fields will be a multi-select listbox that will need to highlight the appropriate list items in a hard-coded list when loaded. Using C#, how do I populate a multi-select listbox -- with the appropriate items selected -- based on the comma-delimited string from a database field? I've researched a few solutions that involve loops, but I have been unable to get them to work with my limited C# skillset. This is all I have now, before I got stuck. You'll see that it doesn't account for multiple values in the string. Is there a function like "contains" that I can check to see if the value matches? I'm still missing some (probably basic) C# logic and coding here. ``` int i; for (i = 0; i <= CATEGORYListBox.Items.Count - 1; i++) { if (reader["CATEGORY"].ToString() == CATEGORYListBox.Items(i).Value) { CATEGORYListBox.Items(i).Selected = True; } } ``` ... ``` <asp:ListBox ID="CATEGORYListBox" runat="server"> <asp:ListItem Value="Circulation">Circulation</asp:ListItem> <asp:ListItem Value="Interactive Media">Interactive Media</asp:ListItem> <asp:ListItem Value="Classified">Classified</asp:ListItem> <asp:ListItem Value="Publishing">Publishing</asp:ListItem> <asp:ListItem Value="Editorial">Editorial</asp:ListItem> <asp:ListItem Value="Retail">Retail</asp:ListItem> </asp:ListBox> ``` Thanks everyone.
This is brute force and ugly, but it should work. It looks like your code above is some sort of hybrid between VB and C#. The code below is C# only. Also, consider not doing your ADO.Net *in* your codebehind. ``` for (int i = 0; i < CATEGORYListBox.Items.Count; i++) { foreach (string category in reader["CATEGORY"].ToString().Split(',')) { if (category != CATEGORYListBox.Items[i].Value) continue; CATEGORYListBox.Items[i].Selected = true; break; } } ```
I would suggest something along these lines. It seems more readable than doing nested loops. ``` List<string> categories = new List<string>(reader["CATEGORY"].ToString().Split(',')); foreach (ListItem item in CATEGORYListBox.Items) { if (categories.Contains(item.Value)) item.Selected = true; } ```
Selecting items in multi-select listbox from delimited database string field
[ "", "c#", "asp.net", "database", "listbox", "multi-select", "" ]
at the begining of my application i disable some buttons and according to some conditions these buttons became enabled. my problem is when the user clicks on a button then it does my action its color becomes gray and that when i make it disabled again. for more explanation: button.Enabled = false; if(Condition) { button.enabled =true; } // user clicked on button // do button's function button.Enabled= false; // here the button's color becomes gray and i dont want this attitude i want to be enabled where at the begining of the application when all buttons are disabled its color is qiut simmilar to button's background. So why this color ?
I am not entirely sure I read your problem correctly, but It seems to me like maybe you want something like this: ``` button.Enabled = Condition; // Initial value // user clicked on button button.Enabled= false; ... do button's function ... button.Enabled = Condition ``` This should restore the state of the button as before the click, basically just disabling it while processing is taking place.
The disabled state for most winform controls is largely fixed by the Win32 control set. If you don't like it, then either: * don't **actually** disable it - just change the color manually, disable tab-stops, and ignore clicks while it is "kinda-disabled" * use WPF, which has a completely separate implementation and doesn't suffer from the Win32 roots * write your own button control from scratch (don't touch the Win32 one) * use a 3rd-party button control
a problem with GUI using C#
[ "", "c#", "winforms", "" ]
Good old [Fusebox](http://fusebox.org/) was my first framework and I still really like it. Started with PHP version, currently using latest CFML version. But time goes by and I'm wondering: maybe I should switch to another framework? Well, I don't want to start holy war here. I just want to know the pros and cons of continuing using FB. Say, I think that no-XML controllers is very good idea and step into the future. Or maybe I am wrong and it is not enogh and I should concentrate on Mach-II or maybe Model-Glue or ... (enter your favourite)? But what about PHP? Seems that it has stuck in past a bit. Symfony, CakePHP, Zend etc look much better now and growing fast. So, a rough list of comparison aspects is following: 1. Time spent for development and maintenance. For me FB seems good enough here. 2. ORM integration. Currently I am using own components (btw, was surprised to see very similar syntax in cf9 previews), but having concerns about their performance. 3. Overall application performance. Caching? "Parsed" files are still good enough? 4. Integration with other products. For example, with unit testing tools -- does anyone has experience of this? Any thoughts and opinions are appreciated. Thanks.
Fusebox is still under active development and just recently changed hands so the lead developer is now [Adam Haskell](http://cfrant.blogspot.com/). **Should you switch to another framework?** That's a subjective question. The only good answer is that -- given infinite time and opportunity -- you should try them all and see what you prefer. They all have their pros and cons, but most people agree that it's not a question of *which* framework as much as a question of *to* framework. You're already decided that it's a tool you want on your belt, so good for you. Make it a tool you understand and enjoy. That said, time and opportunity are not always available. In that case, you're probably best off sticking with what you know and learning what's new with the latest changes to Fusebox. I don't have time to learn them all myself, so I have been a Model-Glue guy myself. I see some Fusebox in my near future, but again, it's subjective and what matters is that you're doing what works best in your situation. **PHP** I can't really speak to the status of PHP frameworks as I'm a CFML developer. Again, if you have the time, play with them and evaluate where they're at and whether they are a tool you're interested in using. **ORM Integration** I know Model-Glue has ORM integration -- [Reactor](http://www.alagad.com/go/products-and-projects/reactor-for-coldfusion) and [Transfer](http://www.transfer-orm.com/) both hook in very easily. I suspect the same can be said for Mach-II, and probably Fusebox but I'm not positive about either. ColdFusion 9's baked in Hibernate will probably work nicely in any framework, but that's yet to be seen. **Performance / Caching; Parsed files?** That's more of a ColdFusion vs. .Net question, right? PHP is a "parsed" language as well. Pre-compiled binary code will always have at least a slight advantage in run-time, but consider that for most web applications adding some more capable hardware is easier and less expensive than spending an extra few months (or more) developing the software. Are "parsed" files still good enough? Yes! Heck yes! **Integration & Test Frameworks** There are multiple testing frameworks, including CFUnit, CFCUnit, and MXUnit off the top of my head for unit testing (which work well for [TDD](http://en.wikipedia.org/wiki/Test_Driven_Development)), and [CFSpec](http://cfspec.riaforge.org/) for [BDD](http://en.wikipedia.org/wiki/Behavior_Driven_Development). I'm sure there are plenty of others, too. CF8 brought integration with .Net, and Exchange (and probably a few other things I'm forgetting), and we've had integration with Java since version 6. It's never been easier to "mash-up" some components written in these various languages to get the best of all worlds. **Conclusion** Your question title is about the future of the Fusebox framework, and I can tell you that it's not going anywhere (except to continue growing and improving, like the other CFML frameworks...). If you're happy with Fusebox, there may be no reason to leave it. That doesn't mean you shouldn't try everything, but there's no reason to abandon ship.
**It can't hurt to expand your horizons:** The range of comparison is so vast that you cannot possibly get a comprehensive and precisely-tailored answer to your four criteria in a single SO thread. It's a good question, but one for which no single answer will be definitive. Instead, I would ask what (if anything) will prevent you from trying a different framework and expanding your horizons (assuming your exclusive or primary experience has been with FB). Nothing will surpass your own evaluation of your four criteria from first-hand experience, especially since you ask about factors that are either very subjective or reasonably addressed by every "high profile" web application framework out there. **A nod to FB in particular:** The Fusebox framework originated and gained momentum even before most people had heard of XML, or web frameworks. It was one of the first "annoyance busting" web development frameworks designed to actually make web-app development more "fun" (with the goal of removing some of the annoyances and tedium from ColdFusion, which itself was an exceptional framework for its time). Consequently, it has come a long way and has a relatively robust track record (just like ColdFusion). This, however, can be considered by some to be a significant detriment against FB (just as for ColdFusion). There is a lot of "baggage" in the framework that quite frankly would not be there if it were the same age as many of the other MVC frameworks that are gaining credibility as the "new kids" on the block. There are many aspects that (from a language design standpoint) reveal some rough-edges that could negatively influence your way of thinking about web application frameworks if you choose FB as your exclusive way of getting things done. Without naming names, (you've already heard them) I would suggest you would do well to keep FB on your toolbelt, but also branch off into the newer frameworks, *especially* those that are based on programming languages *other* than PHP and ColdFusion. That way, you will also expand your horizons and understanding as a programmer in general.
Future of Fusebox framework
[ "", "php", "coldfusion", "frameworks", "comparison", "" ]
I know in PHP you are able to make a call like: ``` $function_name = 'hello'; $function_name(); function hello() { echo 'hello'; } ``` Is this possible in .Net?
Yes. You can use reflection. Something like this: ``` Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString); theMethod.Invoke(this, userParameters); ``` With the above code, the method which is invoked must have access modifier `public`. If calling a non-public method, one needs to use the `BindingFlags` parameter, e.g. `BindingFlags.NonPublic | BindingFlags.Instance`: ``` Type thisType = this.GetType(); MethodInfo theMethod = thisType .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters); ```
You can invoke methods of a class instance using reflection, doing a dynamic method invocation: Suppose that you have a method called hello in a the actual instance (this): ``` string methodName = "hello"; //Get the method information using the method info class MethodInfo mi = this.GetType().GetMethod(methodName); //Invoke the method // (null- no parameter for the method call // or you can pass the array of parameters...) mi.Invoke(this, null); ```
Calling a function from a string in C#
[ "", "c#", ".net", "string", "function-call", "" ]
Like many programs **flash** their window on the **taskbar / dock** to alert the user to switch to the program, Is it possible to flash the **Browser** window using Javascript? *(FireFox-only scripts are also welcome)* This is useful for web-based Chat / Forum / Community-based software where there is lots of **real-time** activity.
@Hexagon Theory: Why would you ever rewrite the whole head element just to change the value of one element in the head? Your solution is horribly inefficient on multiple levels. ``` <html> <head> <link rel="icon" href="on.png" type="image/png" id="changeMe" /> <script type="text/javascript" src="flash.js"></script> </head> <body> </body> </html> ``` flash.js: ``` function Flasher(speed) { var elem = document.getElementById('changeMe'); this.timer = setTimeout(function() { elem.href = elem.href == 'on.png' ? 'off.png' : 'on.png'; }, speed); this.stop = function() { clearTimeout(this.timer); } } /* sample usage * * var flasher = new Flasher(1000); * flasher.stop(); */ ``` It didn't really have to be a class but it helped keep the global namespace clean. That's untested but if simply changing the href doesn't work for some reason, clone the link node, change the href and replace the old link with the cloned one.
At this point, it seems only causing an alert dialog to pop up does the trick... this seems a bit too intrusive, I feel, particularly given the use you're trying to put it to. Instead of causing it to flash, though, you could modify document.title to grab the user's attention, either by prepending some signal (perhaps the string "NEW!") to the site's name, and then using an interval to constantly change it to "", which would then give a nice little "flashing" illusion. Bare-bones example: ``` <html> <head> <title>Chat System</title> <script> var timer, old_t = document.title, blink_amount = 5, cur_b = 0; function notify() { cur_b = 0; timer = setInterval(function() { if (cur_b < blink_amount * 2) { cur_b++; document.title = (document.title.indexOf('NEW! ') != -1) ? old_t : 'NEW! ' + old_t; } else { clearInterval(timer); } }, 600); } notify(); // From here, it's just a matter of calling the // notify() function whenever you detect a new message. </script> </head> <body> </body> </html> ```
Possible to flash a Browser window using Javascript?
[ "", "javascript", "firefox", "browser", "" ]
Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each `__`init`__`.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all the tests can be done with unittest.TestLoader, but it seems that I have to add each module individually. So supposing that test.ui has editor`_`window`_`test.py and preview`_`window`_`test.py, I want the `__`init`__`.py to import these two files and get a list of the two module objects. The idea is that I want to automate making the test suites so that I can't forget to include something in the test suite. What's the best way to do this? It seems like it would be an easy thing to do, but I'm not finding anything. I'm using Python 2.5 btw.
Good answers here, but the **best** thing to do would be to use a 3rd party test discovery and runner like: * [Nose](http://somethingaboutorange.com/mrl/projects/nose/) (my favourite) * [Trial](http://twistedmatrix.com/trac/wiki/TwistedTrial) (pretty nice, especially when testing async stuff) * [py.test](http://codespeak.net/py/dist/test.html) (less good, in my opinion) They are all compatible with plain unittest.TestCase and you won't have to modify your tests in any way, neither would you have to use the advanced features in any of them. Just use as a suite discovery. Is there a specific reason you want to reinvent the nasty stuff in these libs?
Solution to exactly this problem from our django project: ``` """Test loader for all module tests """ import unittest import re, os, imp, sys def find_modules(package): files = [re.sub('\.py$', '', f) for f in os.listdir(os.path.dirname(package.__file__)) if f.endswith(".py")] return [imp.load_module(file, *imp.find_module(file, package.__path__)) for file in files] def suite(package=None): """Assemble test suite for Django default test loader""" if not package: package = myapp.tests # Default argument required for Django test runner return unittest.TestSuite([unittest.TestLoader().loadTestsFromModule(m) for m in find_modules(package)]) if __name__ == '__main__': unittest.TextTestRunner().run(suite(myapp.tests)) ``` EDIT: The benefit compared to bialix's solution is that you can place this loader anytwhere in the project tree, there's no need to modify **init**.py in every test directory.
Getting a list of all modules in the current package
[ "", "python", "unit-testing", "module", "package", "python-2.5", "" ]
I want to add logging or tracing to my C# application but I don't want the overhead of formatting the string or calculating values to be logged if the log verbosity level is set so low that the message will not be logged. In C++, you can use the preprocessor to define macros that will prevent code from being executed at all like this: ``` #define VLOG(level,expr) if (level >= g_log.verbosity) { g_log.output << expr; } ``` Used like this: ``` VLOG(5,"Expensive function call returns " << ExpensiveFunctionCall()); ``` How do you do that in C#? I've read the Microsoft docs explaining the Trace and Debug facilities [here](http://msdn.microsoft.com/en-us/library/64yxa344(VS.80).aspx), and they claim that using #undef DEBUG and #undef TRACE removes all tracing and debugging code from the produced executable, but does it really remove the whole call? Meaning, if I write ``` System.Diagnostics.Trace.WriteLineIf(g_log.verbosity>=5,ExpensiveFunctionCall()); ``` it won't call my expensive function if I undefine TRACE? Or does make the call, **then** decide it won't trace anything? Anyway, even if it does remove it, this is inferior to the C++ macro because I can't make that big ugly call look like my simple VLOG() call in C++ and still avoid evaluating parameters, can I? Nor can I avoid the overhead by defining the verbosity lower at runtime like I can in C++, right?
Two of these answers (Andrew Arnott's and Brian's) did answer part of my question. The ConditionalAttribute that is applied to the Trace and Debug class methods causes all calls to the methods to be removed if TRACE or DEBUG are #undef'd, including the expensive parameter evaluation. Thanks! For the second part, whether you can completely remove all calls at runtime, not at compile time, I found the answer in the log4net [fac](http://logging.apache.org/log4net/release/faq.html#What%20is%20REALLY%20the%20FASTEST%20way%20of%20(not)%20logging%3F). According to them, if you set a readonly property at startup time, the runtime will compile away all calls that don't pass the test! This doesn't let you change it after startup but that's fine, it's better than removing them at compile time.
To answer one of your questions, all method calls that must evaluate in order to call Trace.WriteLine (or its siblings/cousins) do not get called if Trace.WriteLine is compiled out. So go ahead and put your expensive method calls in directly as parameters to the Trace call and it will be removed at compile-time if you don't define the TRACE symbol. Now for your other question regarding changing your verbosity at runtime. The trick here is that Trace.WriteLine and similar methods take 'params object[] args' for their string formatting arguments. Only when the string is actually emitted (when verbosity is set sufficiently high) does the method call ToString on those objects to get a string out of them. So a trick I often play is to pass objects rather than fully-assembled strings to these methods, and leave the string creation in the ToString of the object I pass in. That way the runtime performance tax is only paid when logging is actually occurring, and it gives you the freedom to change verbosity without recompiling your app.
C# conditional logging/tracing
[ "", "c#", "logging", "trace", "" ]
I'm sorry for a redundant question. However, I've found many solutions to my problem but none of them are very well explained. I'm hoping that it will be made clear, here. My C# application's main thread spawns 1..n background workers using the ThreadPool. I wish for the original thread to lock until all of the workers have completed. I have researched the ManualResetEvent in particular but I'm not clear on it's use. In pseudo: ``` foreach( var o in collection ) { queue new worker(o); } while( workers not completed ) { continue; } ``` If necessary, I will know the number of workers that are about to be queued before hand.
Try this. The function takes in a list of Action delegates. It will add a ThreadPool worker entry for each item in the list. It will wait for every action to complete before returning. ``` public static void SpawnAndWait(IEnumerable<Action> actions) { var list = actions.ToList(); var handles = new ManualResetEvent[actions.Count()]; for (var i = 0; i < list.Count; i++) { handles[i] = new ManualResetEvent(false); var currentAction = list[i]; var currentHandle = handles[i]; Action wrappedAction = () => { try { currentAction(); } finally { currentHandle.Set(); } }; ThreadPool.QueueUserWorkItem(x => wrappedAction()); } WaitHandle.WaitAll(handles); } ```
Here's a different approach - encapsulation; so your code could be as simple as: ``` Forker p = new Forker(); foreach (var obj in collection) { var tmp = obj; p.Fork(delegate { DoSomeWork(tmp); }); } p.Join(); ``` Where the `Forker` class is given below (I got bored on the train ;-p)... again, this avoids OS objects, but wraps things up quite neatly (IMO): ``` using System; using System.Threading; /// <summary>Event arguments representing the completion of a parallel action.</summary> public class ParallelEventArgs : EventArgs { private readonly object state; private readonly Exception exception; internal ParallelEventArgs(object state, Exception exception) { this.state = state; this.exception = exception; } /// <summary>The opaque state object that identifies the action (null otherwise).</summary> public object State { get { return state; } } /// <summary>The exception thrown by the parallel action, or null if it completed without exception.</summary> public Exception Exception { get { return exception; } } } /// <summary>Provides a caller-friendly wrapper around parallel actions.</summary> public sealed class Forker { int running; private readonly object joinLock = new object(), eventLock = new object(); /// <summary>Raised when all operations have completed.</summary> public event EventHandler AllComplete { add { lock (eventLock) { allComplete += value; } } remove { lock (eventLock) { allComplete -= value; } } } private EventHandler allComplete; /// <summary>Raised when each operation completes.</summary> public event EventHandler<ParallelEventArgs> ItemComplete { add { lock (eventLock) { itemComplete += value; } } remove { lock (eventLock) { itemComplete -= value; } } } private EventHandler<ParallelEventArgs> itemComplete; private void OnItemComplete(object state, Exception exception) { EventHandler<ParallelEventArgs> itemHandler = itemComplete; // don't need to lock if (itemHandler != null) itemHandler(this, new ParallelEventArgs(state, exception)); if (Interlocked.Decrement(ref running) == 0) { EventHandler allHandler = allComplete; // don't need to lock if (allHandler != null) allHandler(this, EventArgs.Empty); lock (joinLock) { Monitor.PulseAll(joinLock); } } } /// <summary>Adds a callback to invoke when each operation completes.</summary> /// <returns>Current instance (for fluent API).</returns> public Forker OnItemComplete(EventHandler<ParallelEventArgs> handler) { if (handler == null) throw new ArgumentNullException("handler"); ItemComplete += handler; return this; } /// <summary>Adds a callback to invoke when all operations are complete.</summary> /// <returns>Current instance (for fluent API).</returns> public Forker OnAllComplete(EventHandler handler) { if (handler == null) throw new ArgumentNullException("handler"); AllComplete += handler; return this; } /// <summary>Waits for all operations to complete.</summary> public void Join() { Join(-1); } /// <summary>Waits (with timeout) for all operations to complete.</summary> /// <returns>Whether all operations had completed before the timeout.</returns> public bool Join(int millisecondsTimeout) { lock (joinLock) { if (CountRunning() == 0) return true; Thread.SpinWait(1); // try our luck... return (CountRunning() == 0) || Monitor.Wait(joinLock, millisecondsTimeout); } } /// <summary>Indicates the number of incomplete operations.</summary> /// <returns>The number of incomplete operations.</returns> public int CountRunning() { return Interlocked.CompareExchange(ref running, 0, 0); } /// <summary>Enqueues an operation.</summary> /// <param name="action">The operation to perform.</param> /// <returns>The current instance (for fluent API).</returns> public Forker Fork(ThreadStart action) { return Fork(action, null); } /// <summary>Enqueues an operation.</summary> /// <param name="action">The operation to perform.</param> /// <param name="state">An opaque object, allowing the caller to identify operations.</param> /// <returns>The current instance (for fluent API).</returns> public Forker Fork(ThreadStart action, object state) { if (action == null) throw new ArgumentNullException("action"); Interlocked.Increment(ref running); ThreadPool.QueueUserWorkItem(delegate { Exception exception = null; try { action(); } catch (Exception ex) { exception = ex;} OnItemComplete(state, exception); }); return this; } } ```
Wait for pooled threads to complete
[ "", "c#", ".net", "multithreading", "" ]
I have 2 objects from the same type and i would like to shallow copy one state to the other. In C++ i have memcpy which is great. How can i do it in C#? The MemberwiseClone() is not good enough because it creates & returns a new object and i like to copy to an existing object. I thought of using reflection but i'm afraid it will be too slow for production code. I also thought of using one of the .Net serializers but i think they also create object rather than setting an existing one. **My Use Case:** I have a template object (class not struct) which needs to be updated by one of its instances (objects made of this template) Any ideas?
[edit] regarding your clarification: As I understand, you have N objects, each has a (direct) reference to the template object. You want to write back to the template so all objects "see" these changes. Suggestion: imlement a template broker. ``` class TemplateProvider { public MyData Template { get; set; } } ``` Instead of passing the template, pass the template provider to the objects. to simplyfy the syntax in the components, you can add a (private/internal?) property ``` MyData Template { get { return m_templateProvider.Template; } } void UpdateTemplate() { m_templateProvider.Template = (MyData) this.MemberwiseClone(); } ``` The template provider also simplifies locking in multithreaded scenarios. --- In short, no way unless you do it yourself. But why not create a new object if you override all properties anyway? `memcopy` and similar low level constructs are not supported since they undermine guarantees made by the environment. A shallow copy for structs is made by assignment. For classes, `MemberwiseClone` is the method to do that - but as you say that creates a new object. There is no built in way for that, and as it potentially breaks encapsulation it should be used with care anyway. You could build a generic routine using reflection, but whether it works or not depends on the class itself. And yes, ti will be comparedly slow. What's left is supporting it by a custom interface. You can provide a generic "Shallow Copy" routine that checks for the interface and uses that, and falls back to reflection when it doesn't. This makes the functionality available generally, and you can optimize the classes for which performance matters later.
In `C#` (and in `C++` too), there is no difference between "new object" and "a copy of existing object" as long as all their members equal to each other. Given: ``` Int32 a = 5; ``` , both operations: ``` Int32 b = 5; Int32 b = a; ``` yield the same result. As stated in [MSDN reference](http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx): > The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. > > If a field is a value type, a bit-by-bit copy of the field is performed. > > If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. , i.e. it does just the same as `memcpy()` in `C++`
C# memcpy equivalent
[ "", "c#", "serialization", "copying", "" ]
Is it possible to do a cross-site call, in Javascript, to a WCF service? I don't mind if it's a POST or a GET. But I've heard that these days, browsers don't allow cross-site calls with either POST or GET. How can I circumvent this and still call a *WCF Service*?
There's not a whole lot you can do to circumvent the browser's cross-site scripting blockers. Those blockers stop XMLHTTPRequest's from happening to any domain but the one that loaded the containing script or page. That said, there is one commonly used workaround: Use JavaScript to write a new entry into the DOM that references a src that is a cross-site URL. You'll pass all your RPC method arguments to this "script" which will return some JavaScript that will be executed, telling you success or failure. There's no way to do a POST in this manner, the src URL must be a GET, so you can pass arguments that way. I'm not sure if WCF has a "GET only" method of access. And, since the browser will expect the result of the remote tag to be a valid JavaScript object, you'll have to make sure that your WCF service obeys that as well, otherwise you'll get JavaScript errors. Another common method of circumventing cross-site scripting is to write a proxy for your requests. In other words, if you want to access domain test.com from scripts hosted on example.com, then make some URL on example.com that proxies the request over to test.com in the proper way. For your example, the proxying is likely the right answer, assuming that WCF doesn't have it's own cross-site scripting restrictions.
Are you using jQuery by any chance? jQuery supports Cross-Domain JSON requests using "JSONP". You will be limited to GET requests, but I've tried it out and it works well! It's also very simple to get working. See the "Cross-Domain getJSON (using JSONP) " section on this page for details: <http://docs.jquery.com/Release:jQuery_1.2/Ajax> And here's some background on JSONP: <http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/> Let me know how it goes!
Cross-site ajax call to a WCF Service
[ "", "javascript", "wcf", "json", "cross-site", "" ]
How do I find out the name of the class used to create an instance of an object in Python? I'm not sure if I should use the [`inspect`](https://docs.python.org/2/library/inspect.html "inspect — Inspect live objects") module or parse the `__class__` attribute.
Have you tried the [`__name__` attribute](https://docs.python.org/library/stdtypes.html#definition.__name__) of the class? ie `type(x).__name__` will give you the name of the class, which I think is what you want. ``` >>> import itertools >>> x = itertools.count(0) >>> type(x).__name__ 'count' ``` If you're still using Python 2, note that the above method works with [new-style classes](https://wiki.python.org/moin/NewClassVsClassicClass) only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both: ``` x.__class__.__name__ ```
Do you want the name of the class as a string? ``` instance.__class__.__name__ ```
Getting the class name of an instance
[ "", "python", "introspection", "instanceof", "python-datamodel", "" ]
``` class Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Super " + s; } } class Sub extends Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Sub " + s; } } ``` > if suppose in main, ``` Super s = new Sub(); s.anotherMethod("Test"); ``` > Output will be, Sub Test Can you anyone help me in telling how to get output **Super Test** with the **given sequences in main**. > > *And let me explain why I want this, say I have a class which has method test() and it can be overriden by sub classes, in some cases I want the overriden test() and in some cases I want the test() of super class itself, there are many ways to do this, best suggestions will be helpful.*
Whenever I find myself asking (or being asked) a question like this, I **know**, categorically, that I have made a mistake in my design and/or my object definitions. Go back to your object hierarchy and check, double-check and triple-check that every inheritance relationship represents an "IS-A", and not a "HAS-A" or something even weaker.
Why would you ever want to do that ?? The whole point of polymorphism is to call the right method without the need to know which kind of instance you've got ...
How to by-pass inheritance in java when invoking a method
[ "", "java", "inheritance", "oop", "" ]
I have an application which uses 2 forms, a Main Form and a Splash Form being used in the following configuration: ``` public class MainForm : Form { public MainForm() { SplashScreen splash = new SplashScreen(); // configure Splash Screen } } public class SplashScreen { public SplashScreen() { InitializeComponent(); // perform initialization this.ShowDialog(); this.BringToFront(); } } ``` NB: Main form is created with the following code: ``` Application.Run( new MainForm() ); ``` The problem above is that the configuration of splash does not occur unless splash is closed with ``` splash.Close(); ``` only when this occurs does the rest of the MainForm constructor run. how can I easily stop this blocking behaviour?
I already replied to you with a working example on the other question you asked for the same thing: [C# winforms startup (Splash) form not hiding](https://stackoverflow.com/questions/510765/510786#510786)
Generally, you need to show splash screens on a separate thread, and let the primary thread carry on with loading. Not trivial - in particular, you will need to use `Control.Invoke` to ask the splash screen to close itself when ready (thread affinity)...
c# one Form blocking another in a winform Project
[ "", "c#", "winforms", "forms", "blocking", "" ]
I have several Multi-Select parameters in my report. I am trying to find a way to pass in multiple values for a single parameter in the web query string? If I pass in a single value, it works fine. The report runs fine selecting multiple choices for a single param. My trouble lies in the web query string.
Although John Sansom's solution works, there's another way to do this, without having to use a potentially inefficient scalar valued UDF. In the SSRS report, on the parameters tab of the query definition, set the parameter value to ``` =join(Parameters!<your param name>.Value,",") ``` In your query, you can then reference the value like so: ``` where yourColumn in (@<your param name>) ```
This is what I use when passing a multi-select param to another multi-select param. ``` =SPLIT(JOIN(Parameters!<your param name>.Value,","),",") ```
Passing multiple values for a single parameter in Reporting Services
[ "", "sql", "reporting-services", "parameters", "query-string", "" ]
when doing ``` #include <string> class MyString : public std::string { public: MyString() {} }; ``` But the usage below: ``` MyString s = "Happy day"; MyString s("Happy Day"); MyString s = (MyString)"Happy day"; ``` neither of them works. It seems that there's something to do with constructors/operators declaration/overridding, but can anyone help point out where may I find these resources? Thanks.
You need to define some constructors for the different types that you want to be able to convert into your strings. These constructors can basically just hand the parameters through to the underlying `std::string`. If you don't manually create them, the compiler creates a default- and a copy-constructor for you: ``` MyString() : std::string() { } MyString(const MyString &other) : std::string(other) { } ``` To allow construction from string literals, you need a constructor that takes a `const char*`: ``` MyString(const char* other) : std::string(other) { } ``` A constructor that takes a `const std::string&` would also be useful to convert `std::string`s to your string type. If you want to avoid implicit conversions of normal strings, you should make it `explicit`: ``` explicit MyString(const std::string &other) : std::string(other) { } ``` (Edited because my original version was full of errors and I can't delete the accepted answer)
`std::string` isn't designed for inheritance. It doesn't have **any** virtual functions (not even the destructor!), so you can't override anything. It also doesn't have a protected interface, so you gain nothing from subclassing that you couldn't get by making some standalone utility functions that take `std::string`. Keep in mind that most STL implementations expect you to use `std::string` with copy semantics, not reference semantics, and this makes the case for adding inherited fields or overriding functions even weaker. If you **really** want something like `std::string` with extra functions, you could consider using composition instead of inheritance, but this isn't great either. You don't have to worry about the `std::string` destructor not getting called properly, but you do end up having to wrap a lot of methods from `std::string` that you need, which is tedious. Also, your utility functions will only work with MyString when most code is going to expect `std::string`, so it isn't very reusable. You're better off making some utility functions that take `std::string`. Or, if `std::string` isn't providing what you need, you should go with some other string implementation that suits your needs. Here are some possibilities that come to mind: * SGI's STL extension, [`std::rope`](http://www.sgi.com/tech/stl/Rope.html). It's in GNU C++, so maybe you can rely on it. * [Boost](http://www.boost.org) has a pretty extensive [string algorithm library](http://www.boost.org/doc/libs/1_38_0/doc/html/string_algo.html) that lets you use concepts to specify [how your string is represented](http://www.boost.org/doc/libs/1_38_0/doc/html/string_algo/design.html). * Also see this [if you *must* "derive"](https://stackoverflow.com/a/4205121/15161) from std::string
Constructor doesn't work for class inherited from std::string
[ "", "c++", "stl", "" ]
I have learned how to use classes in PHP and so far I have only really found one useful application for them. I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect. Aside from this example, what are some other useful ways to utilize classes in a practical sense?
I use a database class all the time. Here are a couple examples: <http://www.massless.org/_tests/phpdb/> <http://slaout.linux62.org/php/index.html> <http://www.tonymarston.net/php-mysql/databaseobjects.html>
It's a really good idea to read other people's code and see how they have separated things into classes. Look at some [PEAR](http://pear.php.net) modules or a framework ( [Zend](http://framework.zend.com), [Symfony](http://www.symfony-project.org), Cake ).
What are some useful ways to utilize classes in PHP?
[ "", "php", "class", "" ]
I'm trying to display an image using a PHP script. Basically so the php script is passed on the full path to the image, and it then displays that image in the browser. I've checked to make sure the image exists, it is being read correctly, etc, however in the browser i just see the broken image box (e.g the small red cross in IE) if I go there. My script sends out these headers: ``` <?php header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file))); header('Content-Type: '.$mime); header('Content-Length: '.filesize($file)."\n\n"); header('Etag: '.md5($file)); echo $file; die; ``` `$file` contains something like `'/var/www/htdocs/images/file.jpg'` which works. the `$mime` is `'image/jpeg'`. I have also tried echoing `file_get_contents($file)` but it didn't work either. What is the problem, any thoughts?
I found the answer, i had some extra whitespace after the `?>` tag which was causing the header to not work. grrrrrrr
``` <?php $filename = basename($file); $file_extension = strtolower(substr(strrchr($filename,"."),1)); switch( $file_extension ) { case "gif": $ctype="image/gif"; break; case "png": $ctype="image/png"; break; case "jpeg": case "jpg": $ctype="image/jpeg"; break; default: } ob_clean(); // add this before header header('Content-type: ' . $ctype); readFile($file); ?> ``` Some time extra space may be produced in any other file.So those extra spaces can be removed by calling ob\_clean() before header() is called.
Displaying images using PHP not working
[ "", "php", "image", "image-processing", "gd", "gd2", "" ]
Using this SQL on SQL Server 2005 ``` SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = @TableName AND COLUMN_NAME=@ColumnName ``` I get the Primary Keys AND the Foreign Keys. How can I get only Foreign Keys? How can I see if a Constraint is a Primary or a Foreign Key? Thanks
I used the following SQL with SQL Server 2005 to get the Constraint Names by Primary Key: ``` SELECT Constraint_Name FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE UNIQUE_CONSTRAINT_NAME = (SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName) ``` To get the Constraint Name by Foreing Key: ``` SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName ``` To get the Foreign Key's Table and Field by Constraint Name: ``` SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_NAME = @ConstraintName ``` To get the Primary Key's Table and Field by Constraint Name: ``` SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_NAME = (SELECT UNIQUE_CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = @ConstraintName) ```
Found a much more elegant solution [here](http://blog.sqlauthority.com/2007/09/04/sql-server-2005-find-tables-with-foreign-key-constraint-in-database/) Code added below for completeness but all credit goes to Pinal Dave ``` SELECT f.name AS ForeignKey, OBJECT_NAME(f.parent_object_id) AS TableName, COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName, OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName, COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName FROM sys.foreign_keys AS f LEFT JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id ``` And if you just want the primary keys... ``` SELECT i.name AS IndexName, OBJECT_NAME(ic.OBJECT_ID) AS TableName, COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id WHERE i.is_primary_key = 1 ``` Added this as an additional answer because it's so far removed from my previous one :)
How do I know if CONSTRAINT_NAME is a Primary or Foreign Key?
[ "", "sql", "sql-server", "metadata", "constraints", "table-structure", "" ]
I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though. Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or is the prefered way to roll your own? I have looked at [pylucene](http://lucene.apache.org/pylucene/) and [lupy](http://pypi.python.org/pypi/Lupy/0.2.1), but both projects seem rather inactive and unsupported, so I am not sure if should rely on them. Final notes: Woosh and pylucene seems promising, but woosh is still alpha so I am not sure I want to rely on it, and I have problems compiling pylucene, and there are no actual releases off it. After I have looked a bit more at the data, it's mostly numbers and default text strings, so as off now an indexing engine won't help me. Hopefully these libraries will stabilize and later visitors will find some use for them.
Lupy [has been retired](http://divmod.org/trac/wiki/WhitherLupy) and the developers recommend PyLucene instead. As for PyLucene, its mailing list activity may be low, but it is definitely supported. In fact, it just recently became an [official apache subproject](http://lucene.apache.org/pylucene/#news20090108). You may also want to look at a new contender: [Whoosh](http://pypi.python.org/pypi/Whoosh/). It's similar to lucene, but implemented in pure python.
I haven't done indexing before, however the following may be helpful :- 1. pyIndex - <http://rgaucher.info/beta/pyIndex/> -- File indexing library for Python 2. <http://www.xml.com/pub/a/ws/2003/05/13/email.html> -- Thats a script for searching Outlook email using Python and Lucene 3. <http://gadfly.sourceforge.net/> - Aaron water's gadfly database (I think you can use this one for indexing. Haven't used it myself.) As far as using HDF files goes, I have heard of a module called h5py. I hope this helps.
Python file indexing and searching
[ "", "python", "search", "indexing", "lucene", "" ]
Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. [`Package`](http://java.sun.com/javase/6/docs/api/java/lang/Package.html), it would seem like no.)
Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception. However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this. If there are classes that get generated, or delivered remotely, you will not be able to discover those classes. The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming. Addendum: [The Reflections Library](https://github.com/ronmamo/reflections) will allow you to look up classes in the current classpath. It can be used to get all classes in a package: ``` Reflections reflections = new Reflections("my.project.prefix"); Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class); ```
You should probably take a look at the open source [Reflections library](https://github.com/ronmamo/reflections). With it you can easily achieve what you want. First, setup the reflections index (it's a bit messy since searching for all classes is disabled by default): ``` List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("org.your.package")))); ``` Then you can query for all objects in a given package: ``` Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); ```
Can you find all classes in a package using reflection?
[ "", "java", "reflection", "package", "" ]
HI all, I use jQuery to parse my xml responses. I have this xml : ``` <?xml version="1.0" encoding="UTF-8"?> <response status="ok"> <client_id>185</client_id> </response> ``` And i want to get "client\_id" value.
First, make a request for the XML with $.get or however you want. Then: ``` clientID = $(myXML).find("client_id").text(); ```
To fix the expected response data type to XML right in your request, set the `dataType` parameter to "xml". If you don't, jQuery uses the response headers to make a guess. It is supported on the `$.ajax()` function as part of the `options` object, as well as on `$.get()` and `$.post()`: ``` jQuery.ajax( options ) jQuery.get( url, data, callback, type ) jQuery.post( url, data, callback, type ) ``` So you could do this: ``` $.ajax({ type: 'GET', url: "foo.aspx", data: { key: "value" }, dataType: "xml", success: function (xml){ var clientid = $(xml).find('client_id').first().text(); alert(clientid); } }); ``` --- Note that as of jQuery 1.5 you can use a nicer version of the above Ajax request: ``` $.get("foo.aspx", { key: "value" }) .done(function (xml){ var clientid = $(xml).find('client_id').first().text(); alert(clientid); }); ```
parse xml response with jQuery
[ "", "javascript", "jquery", "xml", "" ]
I would like to write applications that use C++ and the Cocoa frameworks because Apple is not making Carbon 64-bit capable. C++ seems to be pretty vanilla in its implementation on Linux and Windows but on Mac OS X it seems like additional Apple specific pieces of code are required (like an Obj-C wrapper). It also seems that Apple is forcing developers to write in Objective-C rather than C++, although I could be wrong. I am trying to find a path to write code on the Mac that would be easy to keep cross platform. Having to write code in C++ for Linux/Windows and then rewrite large portions in Objective-C would be very inefficient. Is there a way to write code in C++ that will be supported for the future and supported in Xcode? Also, if this is possible, how would I mix C++ and Objective-C in Xcode? Thanks.
You cannot write a Cocoa application entirely in C++. Cocoa relies heavily on the late binding capabilities of Objective-C for many of its core technologies such as Key-Value Bindings, delegates (Cocoa style), and the target-action pattern. The late binding requirements make it *very* difficult to implement the Cocoa API in a compile-time bound, typed language like C++ⁱ. You can, of course, write a pure C++ app that runs on OS X. It just can't use the Cocoa APIs. So, you have two options if you want to share code between C++ apps on other platforms and your Cocoa-based application. The first is to write the model layer in C++ and the GUI in Cocoa. This is a common approach used by some very large apps, including [Mathematica](http://wolfram.com). Your C++ code can be left unchanged (you do not need "funky" apple extensions to write or compile C++ on OS X). Your controller layer will likely make use of Objective-C++ (perhaps the "funky" Apple extension you refer to). Objective-C++ is a superset of C++, just as Objective-C is a superset of C. In Objective-C++, you can make objc-style message passing calls (like `[some-objc-object callMethod];`) from within a C++ function. Conversely, you can call C++ functions from within ObjC code like: ``` @interface MyClass { MyCPPClass *cppInstance; } @end @implementation MyClass - (id)init { if(self = [super init]) { cppInstance = new MyCPPClass(); } return self; } - (void) dealloc { if(cppInstance != NULL) delete cppInstance; [super dealloc]; } - (void)callCpp { cppInstance->SomeMethod(); } @end ``` You can find out more about Objective-C++ in the Objective-C language [guide](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_14_section_1.html#//apple_ref/doc/uid/TP30001163-CH10-SW1). The view layer can then be pure Objective-C. The second option is to use a cross-platform C++ toolkit. The [Qt](http://qt.nokia.com/) toolkit might fit the bill. Cross-platform toolkits are generally despised by Mac users because they do not get all the look and feel details exactly right and Mac users expect polish in the UI of Mac applications. Qt does a surprisingly good job, however, and depending on the audience and the use of your app, it may be good enough. In addition, you will lose out on some of the OS X-specific technologies such as Core Animation and some QuickTime functionality, though there are approximate replacements in the Qt API. As you point out, Carbon will not be ported to 64-bit. Since Qt is implemented on Carbon APIs, Trolltech/Nokia have had to port Qt to the Cocoa API to make it 64-bit compatible. My understanding is that the next relase of Qt (currently in [release candiate](http://qt.nokia.com/about/news/qt-4.5-release-candidate-available)) completes this transition and is 64-bit compatible on OS X. You may want to have a look at the source of Qt 4.5 if you're interested in integrating C++ and the Cocoa APIs. --- ⁱ For a while Apple made the Cocoa API available to Java, but the bridge required extensive hand-tuning and was unable to handle the more advanced technologies such as Key-Value Bindings described above. Currently dynamically typed, runtime-bound languages like Python, Ruby, etc. are the only real option for writing a Cocoa app without Objective-C (though of course these bridges use Objective-C under the hood).
Well, it may sound silly, but actually we can write pure C++ code to create GUI for Mac OS X, but we must link against Cocoa framework. ``` /* * test1.cpp * This program shows how to access Cocoa GUI from pure C/C++ * and build a truly functional GUI application (although very simple). * * Compile using: * g++ -framework Cocoa -o test1 test1.cpp * * that will output 'test1' binary. */ #include <CoreFoundation/CoreFoundation.h> #include <objc/objc.h> #include <objc/objc-runtime.h> #include <iostream> extern "C" int NSRunAlertPanel(CFStringRef strTitle, CFStringRef strMsg, CFStringRef strButton1, CFStringRef strButton2, CFStringRef strButton3, ...); int main(int argc, char** argv) { id app = NULL; id pool = (id)objc_getClass("NSAutoreleasePool"); if (!pool) { std::cerr << "Unable to get NSAutoreleasePool!\nAborting\n"; return -1; } pool = objc_msgSend(pool, sel_registerName("alloc")); if (!pool) { std::cerr << "Unable to create NSAutoreleasePool...\nAborting...\n"; return -1; } pool = objc_msgSend(pool, sel_registerName("init")); app = objc_msgSend((id)objc_getClass("NSApplication"), sel_registerName("sharedApplication")); NSRunAlertPanel(CFSTR("Testing"), CFSTR("This is a simple test to display NSAlertPanel."), CFSTR("OK"), NULL, NULL); objc_msgSend(pool, sel_registerName("release")); return 0; } ```
Use C++ with Cocoa Instead of Objective-C?
[ "", "c++", "objective-c", "cocoa", "language-interoperability", "" ]
I have seen numerous examples of lazy loading - what's your choice? Given a model class for example: ``` public class Person { private IList<Child> _children; public IList<Child> Children { get { if (_children == null) LoadChildren(); return _children; } } } ``` The Person class should not know anything about how it's children are loaded .... or should it? Surely it should control when properties are populated, or not? Would you have a repository that couples a Person together with its children collection or would you use a different approach, such as using a [lazyload](https://stackoverflow.com/questions/375881/lazy-loading-and-lazy-execution-patterns) class - even then, I don't want a lazyload class blurring in my model architecture. How would you handle performance if first requesting a Person and then its Children (i.e. not lazy loading in this instance) or somehow lazy loading. Does all this boil down to personal choice?
The best lazy loading is avoiding it ;) Thread safety is an immediate problem you'll have to handle. I have no count of how often I have seen production systems with 8 cpu cores run lazy loading 8 times for *every single* lazy loading pattern in use. At least on server startups all server cores have a tendency to end up in the same places. Let a DI framework construct it for you instead, if you can. And if you cannot, I still prefer explicit construction. So all sorts of AOP magic simply do not cut it with me, go for explicit construction outside the class. Don't put it inside the person class, just make a service that constructs the objects in the proper manner. Introducing "magic" layers that more or less transparently do these things *seem* like a nice idea, but I have yet to come across implementations that do not have unforseen and problematic consequences.
You can use the `Lazy<T>` class I talked about here : [What is the proper way to inject a data access dependency for lazy loading?](https://stackoverflow.com/questions/130292/what-is-the-proper-way-to-inject-a-data-access-dependency-for-lazy-loading/522547#522547) There is also link to a more detailed blog post there...
Lazy loading - what's the best approach?
[ "", "c#", "architecture", "coding-style", "lazy-loading", "methodology", "" ]