source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
60,221
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this: [======>                    ] 37% and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?
There are two ways I know of to do this: Use the backspace escape character ('\b') to erase your line Use the curses package, if your programming language of choice has bindings for it. And a Google revealed ANSI Escape Codes , which appear to be a good way. For reference, here is a function in C++ to do this: void DrawProgressBar(int len, double percent) { cout << "\x1B[2K"; // Erase the entire current line. cout << "\x1B[0E"; // Move to the beginning of the current line. string progress; for (int i = 0; i < len; ++i) { if (i < static_cast<int>(len * percent)) { progress += "="; } else { progress += " "; } } cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%"; flush(cout); // Required.}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ] }
60,244
I need to join two binary files with a *.bat script on Windows. How can I achieve that?
Windows type command works similarly to UNIX cat . Example 1: type file1 file2 > file3 is equivalent of: cat file1 file2 > file3 Example 2: type *.vcf > all_in_one.vcf This command will merge all the vcards into one.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/60244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ] }
60,260
I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number: (defmacro multp (value factor) `(= (rem ,value ,factor) 0)) so that : (multp 40 10) evaluates to true whilst (multp 40 13) does not The question is does this macro leak in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?
Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both value and factor are evaluated only once and in order, and rem doesn't have any side effects. This is not good Lisp though, because there's no reason to use a macro in this case. A function (defun multp (value factor) (zerop (rem value factor))) is identical for all practical purposes. (Note the use of zerop . I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, (= ... 0) might be better)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303/" ] }
60,269
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs. EDIT : The Java Tutorials - Drag and Drop and Data Transfer .
Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are: Detect that a drag has occurred Draw the dragged tab to an offscreen buffer Track the mouse position whilst dragging occurs Draw the tab in the buffer on top of the component. The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it. Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p import java.awt.Component;import java.awt.Graphics;import java.awt.Image;import java.awt.Point;import java.awt.Rectangle;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseMotionAdapter;import java.awt.image.BufferedImage;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JTabbedPane;public class DraggableTabbedPane extends JTabbedPane { private boolean dragging = false; private Image tabImage = null; private Point currentMouseLocation = null; private int draggedTabIndex = 0; public DraggableTabbedPane() { super(); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if(!dragging) { // Gets the tab index based on the mouse position int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY()); if(tabNumber >= 0) { draggedTabIndex = tabNumber; Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber); // Paint the tabbed pane to a buffer Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics totalGraphics = totalImage.getGraphics(); totalGraphics.setClip(bounds); // Don't be double buffered when painting to a static image. setDoubleBuffered(false); paintComponent(totalGraphics); // Paint just the dragged tab to the buffer tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB); Graphics graphics = tabImage.getGraphics(); graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this); dragging = true; repaint(); } } else { currentMouseLocation = e.getPoint(); // Need to repaint repaint(); } super.mouseDragged(e); } }); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(dragging) { int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10); if(tabNumber >= 0) { Component comp = getComponentAt(draggedTabIndex); String title = getTitleAt(draggedTabIndex); removeTabAt(draggedTabIndex); insertTab(title, null, comp, null, tabNumber); } } dragging = false; tabImage = null; } }); } protected void paintComponent(Graphics g) { super.paintComponent(g); // Are we dragging? if(dragging && currentMouseLocation != null && tabImage != null) { // Draw the dragged tab g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this); } } public static void main(String[] args) { JFrame test = new JFrame("Tab test"); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setSize(400, 400); DraggableTabbedPane tabs = new DraggableTabbedPane(); tabs.addTab("One", new JButton("One")); tabs.addTab("Two", new JButton("Two")); tabs.addTab("Three", new JButton("Three")); tabs.addTab("Four", new JButton("Four")); test.add(tabs); test.setVisible(true); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827/" ] }
60,278
In all the Git tutorials I've read they say that you can do: git initgit add .git commit When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.
You're meant to put the commit message in this text file, then save and quit. You can change the default text editor that git uses with this command: git config --global core.editor "nano" You have to change nano to whatever command would normally open your text editor.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
60,285
If it's possible, I'm interested in being able to embed a PostgreSQL database, similar to sqllite . I've read that it's not possible . I'm no database expert though, so I want to hear from you. Essentially I want PostgreSQL without all the configuration and installation. If it's possible, tell me how.
Unless you do a major rewrite of code, it is not possible to run Postgres "embedded". Either run it as a separate process or use something else. SQLite is an excellent choice. But there are others. MySQL has an embedded version. See it at http://mysql.com/oem/ . Also several java choices, and Mac has Core Data you can write too. Hell, you can even use FoxPro. What OS you on and what services you need from the database?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525/" ] }
60,302
If I start a process via Java's ProcessBuilder class, I have full access to that process's standard in, standard out, and standard error streams as Java InputStreams and OutputStreams . However, I can't find a way to seamlessly connect those streams to System.in , System.out , and System.err . It's possible to use redirectErrorStream() to get a single InputStream that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C system() call. This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of isatty() in the child process carries through the redirection.
You will need to copy the Process out, err, and input streams to the System versions. The easiest way to do that is using the IOUtils class from the Commons IO package. The copy method looks to be what you need. The copy method invocations will need to be in separate threads. Here is the basic code: // Assume you already have a processBuilder all configured and ready to gofinal Process process = processBuilder.start();new Thread(new Runnable() {public void run() { IOUtils.copy(process.getOutputStream(), System.out);} } ).start();new Thread(new Runnable() {public void run() { IOUtils.copy(process.getErrorStream(), System.err);} } ).start();new Thread(new Runnable() {public void run() { IOUtils.copy(System.in, process.getInputStream());} } ).start();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5696/" ] }
60,330
I see them all the time and always ignore them. Can someone explain to me why they have become so prevalent? If I'm using a site that allows me to explore it via tags (e.g., this one, del.icio.us, etc.) that's what I will do. Why would I need a "cloud" of tags upon which to click? I can just type that tag(s) into a search box. What am I missing?
It's more of a browse assist than a search assist. If you see a large or bold tag in a tag cloud that interests you it my lead to some knowledge discovery that wouldn't have otherwise been sought out with a deliberate search. When I am browsing del.ico.us or stackoverflow I appreciate the tags as they sometimes lead me to discover related topics. Wikipedia has an interesting definition : A tag cloud or word cloud (or weighted list in visual design) is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. 1 Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ] }
60,394
Are there any tools available that will calculate code metrics (for example number of code lines, cyclomatic complexity, coupling, cohesion) for your project and over time produce a graph showing the trends?
On my latest project I used SourceMonitor . It's a nice free tool for code metrics analysis. Here is an excerpt from SourceMonitor official site: Collects metrics in a fast, single pass through source files. Measures metrics for source code written in C++, C, C#, VB.NET, Java, Delphi, Visual Basic (VB6) or HTML. Includes method and function level metrics for C++, C, C#, VB.NET, Java, and Delphi. Saves metrics in checkpoints for comparison during software development projects. Displays and prints metrics in tables and charts. Operates within a standard Windows GUI or inside your scripts using XML command files. Exports metrics to XML or CSV (comma-separated-value) files for further processing with other tools. For .NET beside NDepend which is simply the best tool, I can recommend vil . Following tools can perform trend analysis: CAST Klocwork Insight
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1324220/" ] }
60,409
I know in php you can embed variables inside variables, like: <? $var1 = "I\'m including {$var2} in this variable.."; ?> But I was wondering how, and if it was possible to include a function inside a variable.I know I could just write: <?php$var1 = "I\'m including ";$var1 .= somefunc();$var1 = " in this variable..";?> But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions: <?php$var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> There is <b>alot</b> of text and html here... but I want some <i>functions</i>! -somefunc() doesn't work -{somefunc()} doesn't work -$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string -more non-working: ${somefunc()} </body> </html>EOF;?> Or I want dynamic changes in that load of code: <?function somefunc($stuff) { $output = "my bold text <b>{$stuff}</b>."; return $output;}$var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> somefunc("is awesome!") somefunc("is actually not so awesome..") because somefunc("won\'t work due to my problem.") </body> </html>EOF;?> Well?
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call: <?function somefunc($stuff){ $output = "<b>{$stuff}</b>"; return $output;}$somefunc='somefunc';echo "foo {$somefunc("bar")} baz";?> will output " foo <b>bar</b> baz ". I find it easier however (and this works in PHP4) to either just call the function outside of the string: <?echo "foo " . somefunc("bar") . " baz";?> or assign to a temporary variable: <?$bar = somefunc("bar");echo "foo {$bar} baz";?>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4867/" ] }
60,455
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server? I'm not so concerned with browser security issues. etc. as the implementation would be for HTA . But is it possible?
Google is doing this in Google+ and a talented developer reverse engineered it and produced http://html2canvas.hertzen.com/ . To work in IE you'll need a canvas support library such as http://excanvas.sourceforge.net/
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915/" ] }
60,464
I am fairly new to Emacs and I have been trying to figure out how to change the default folder for C-x C-f on start-up. For instance when I first load Emacs and hit C-x C-f its default folder is C:\emacs\emacs-21.3\bin , but I would rather it be the desktop. I believe there is some way to customize the .emacs file to do this, but I am still unsure what that is. Update: There are three solutions to the problem that I found to work, however I believe solution 3 is Windows only. Solution 1: Add (cd "C:/Users/Name/Desktop") to the .emacs file Solution 2: Add (setq default-directory "C:/Documents and Settings/USER_NAME/Desktop/") to the .emacs file Solution 3: Right click the Emacs short cut, hit properties and change the start in field to the desired directory.
You didn't say so, but it sounds like you're starting Emacs from a Windows shortcut. The directory that you see with c-x c-f is the cwd, in Emacs terms, the default-directory (a variable). When you start Emacs using an MS Windows shortcut, the default-directory is initially the folder (directory) specified in the "Start In" field of the shortcut properties. Right click the shortcut, select Properties , and type the path to your desktop in the Start In field. If you're using Emacs from the command line, default-directory starts as the directory where you started Emacs (the cwd). This approach is better than editing your .emacs file, since it will allow you to have more than one shortcuts with more than one starting directory, and it lets you have the normal command line behavior of Emacs if you need it. CWD = current working directory = PWD = present working directory . It makes a lot more sense at the command line than in a GUI.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ] }
60,477
I am looking for some good links with best practices and sample code on creating REST ful web services using .NET. Also, any other input you might have regarding REST would be greatly appreciated.
ADO.Net Data Servcies makes it really easy to build and consume RESTful web services in the .Net world but nevertheless understanding the concepts is important. Compared to WCF (which added REST support later), ADO.Net Data Services was built primarily for REST. Guidelines for Building RESTful Web Services has all the info on the resources you need. This is another useful blog entry : The uniform interface constraints describe how a service built for the Web can be a good participant in the Web architecture. These constraints are described briefly as follows : 1) Identification of resources: A resource is any information item that can be named and represented (e.g. a document, a stock price at a given point in time, the current weather in Las Vegas, etc). Resources in your service should be identified using URIs. 2) Manipulation of resources via representations: A representation is the physical representation of a resource and should correspond to a valid media type. Using standard media types as the data formats behind your service increases the reach of your service by making it accessible to a wide range of potential clients. Interaction with the resource should be based on retrieval and manipulation of the representation of the resource identified by its URI. 3)Self-descriptive messages: Following the principles of statelessness in your service's interactions, using standard media types and correctly indicating the cacheability of messages via HTTP method usage and control headers ensures that messages are self descriptive. Self descriptive messages make it possible for messages to be processed by intermediaries between the client and server without impacting either. 4)Hypermedia as the engine of application state: Application state should be expressed using URIs and hyperlinks to transition between states. This is probably the most controversial and least understood of the architectural constraints set forth in Roy Fielding's dissertation . In fact, Fielding's dissertation contains an explicit arguments against using HTTP cookies for representing application state to hammer this point home yet it is often ignored.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ] }
60,507
Say I have: void Render(void(*Call)()){ D3dDevice->BeginScene(); Call(); D3dDevice->EndScene(); D3dDevice->Present(0,0,0,0);} This is fine as long as the function I want to use to render is a function or a static member function: Render(MainMenuRender);Render(MainMenu::Render); However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g. Render(MainMenu->Render); However I really have no idea how to do this, and still allow functions and static member functions to be used.
There are a lot of ways to skin this cat, including templates. My favorite is Boost.function as I've found it to be the most flexible in the long run. Also read up on Boost.bind for binding to member functions as well as many other tricks. It would look like this: #include <boost/bind.hpp>#include <boost/function.hpp>void Render(boost::function0<void> Call){ // as before...}Render(boost::bind(&MainMenu::Render, myMainMenuInstance));
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ] }
60,547
Whilst working on a recent project, I was visited by a customer QA representitive, who asked me a question that I hadn't really considered before: How do you know that the compiler you are using generates machine code that matches the c code's functionality exactly and that the compiler is fully deterministic? To this question I had absolutely no reply as I have always taken the compiler for granted. It takes in code and spews out machine code. How can I go about and test that the compiler isn't actually adding functionality that I haven't asked it for? or even more dangerously implementing code in a slightly different manner to that which I expect? I am aware that this is perhapse not really an issue for everyone, and indeed the answer might just be... "you're over a barrel and deal with it". However, when working in an embedded environment, you trust your compiler implicitly. How can I prove to myself and QA that I am right in doing so?
For safety critical embedded application certifying agencies require to satisfy the "proven-in-use" requirement for the compiler. There are typically certain requirements (kind of like "hours of operation") that need to be met and proven by detailed documentation. However, most people either cannot or don't want to meet these requirements because it can be very difficult especially on your first project with a new target/compiler. One other approach is basically to NOT trust the compiler's output at all. Any compiler and even language-dependent (Appendix G of the C-90 standard, anyone?) deficiencies need to be covered by a strict set of static analysis, unit- and coverage testing in addition to the later functional testing. A standard like MISRA-C can help to restrict the input to the compiler to a "safe" subset of the C language. Another approach is to restrict the input to a compiler to a subset of a language and test what the output for the entire subset is. If our application is only built of components from the subset it is assumed to be known what the output of the compiler will be. The usually goes by "qualification of the compiler". The goal of all of this is to be able to answer the QA representative's question with "We don't just rely on determinism of the compiler but this is the way we prove it...".
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ] }
60,570
Backgrounder: The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of. This hides internal implementation details and data from the user of the library. When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file? To illustrate, this code puts the Purr() implementation on the impl class and wraps it as well. Why not implement Purr directly on the public class? // header file:class Cat { private: class CatImpl; // Not defined here CatImpl *cat_; // Handle public: Cat(); // Constructor ~Cat(); // Destructor // Other operations... Purr();};// CPP file:#include "cat.h"class Cat::CatImpl { Purr();... // The actual implementation can be anything};Cat::Cat() { cat_ = new CatImpl;}Cat::~Cat() { delete cat_;}Cat::Purr(){ cat_->Purr(); }CatImpl::Purr(){ printf("purrrrrr");}
I think most people refer to this as the Handle Body idiom. See James Coplien's book Advanced C++ Programming Styles and Idioms . It's also known as the Cheshire Cat because of Lewis Caroll's character that fades away until only the grin remains. The example code should be distributed across two sets of source files. Then only Cat.h is the file that is shipped with the product. CatImpl.h is included by Cat.cpp and CatImpl.cpp contains the implementation for CatImpl::Purr() . This won't be visible to the public using your product. Basically the idea is to hide as much as possible of the implementation from prying eyes. This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to. We did this with the rewrite of IONA's Orbix 3.3 product in 2000. As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses Cat if you just want to change the implementation of Purr() . This technique is used in a methodology called design by contract .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ] }
60,573
Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor: XmlSerializer serializer = new XmlSerializer(typeof(DataClass)); I am getting an exception saying: There was an error reflecting type. Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing. You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute. XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/60573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
60,590
On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment." A couple of possible approaches I know about, and browser compatibility (based on a quick test): 1) Do a window.open pointing to the new file. - FireFox 3 blocks this. - IE6 blocks this. - IE7 blocks this. 2) Create an iframe pointing to the new file. - FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?) - IE6 blocks this. - IE7 blocks this.How can I do this so that at least these three browsers will not object? Bonus: is there a method that doesn't require browser-conditional statements? (I believe that download.com employs both methods conditionally, but I can't get either one to work.) Responses and Clarifications: Q: "Why not point the current window to the file?" A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?" UPDATE: I have abandoned this approach. See my answer below for reasons.
You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag. <meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip"/>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ] }
60,620
How does one start development in Silverlight? Does one need a new IDE? or Visual studio will support?
Yes there is tooling support for Visual Studio. It is still in Beta though. Get Started Building Silverlight 2 Applications 1) Install Visual Studio 2008 then Install Silverlight Tools Beta 2 for Visual Studio 2008This add-on to Visual Studio 2008 allows you to use .NET to create Silverlight 2 Beta 2 Web sites. The Silverlight 2 Beta 2 Runtime and the Silverlight 2 Beta 2 SDK are installed as part of this install. For additional information read the overview and the Silverlight 2 Beta 2 Readme Notes. Note if you have Visual Studio 2008 Service Pack 1 Beta installed, please see this information for details on installing correctly. 2) Install Expression Blend 2.5 June 2008 PreviewThis is a preview version of Expression Blend for designing Silverlight 2 experiences. 3) Install Deep Zoom ComposerThis tool allows you to prepare your images for use with the Deep Zoom feature in Silverlight 2. One thing to watch out for is that Silverlight does not support Synchronous calls to the server. All calls are Asynchronous as of this Beta .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
60,645
Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure.
Here is an implementation for an anonymous pipe function with the possibility to specify FILE_FLAG_OVERLAPPED: /******************************************************************************\* This is a part of the Microsoft Source Code Samples. * Copyright 1995 - 1997 Microsoft Corporation.* All rights reserved. * This source code is only intended as a supplement to * Microsoft Development Tools and/or WinHelp documentation.* See these sources for detailed information regarding the * Microsoft samples programs.\******************************************************************************//*++Copyright (c) 1997 Microsoft CorporationModule Name: pipeex.cAbstract: CreatePipe-like function that lets one or both handles be overlappedAuthor: Dave Hart Summer 1997Revision History:--*/#include <windows.h>#include <stdio.h>static volatile long PipeSerialNumber;BOOLAPIENTRYMyCreatePipeEx( OUT LPHANDLE lpReadPipe, OUT LPHANDLE lpWritePipe, IN LPSECURITY_ATTRIBUTES lpPipeAttributes, IN DWORD nSize, DWORD dwReadMode, DWORD dwWriteMode )/*++Routine Description: The CreatePipeEx API is used to create an anonymous pipe I/O device. Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or both handles. Two handles to the device are created. One handle is opened for reading and the other is opened for writing. These handles may be used in subsequent calls to ReadFile and WriteFile to transmit data through the pipe.Arguments: lpReadPipe - Returns a handle to the read side of the pipe. Data may be read from the pipe by specifying this handle value in a subsequent call to ReadFile. lpWritePipe - Returns a handle to the write side of the pipe. Data may be written to the pipe by specifying this handle value in a subsequent call to WriteFile. lpPipeAttributes - An optional parameter that may be used to specify the attributes of the new pipe. If the parameter is not specified, then the pipe is created without a security descriptor, and the resulting handles are not inherited on process creation. Otherwise, the optional security attributes are used on the pipe, and the inherit handles flag effects both pipe handles. nSize - Supplies the requested buffer size for the pipe. This is only a suggestion and is used by the operating system to calculate an appropriate buffering mechanism. A value of zero indicates that the system is to choose the default buffering scheme.Return Value: TRUE - The operation was successful. FALSE/NULL - The operation failed. Extended error status is available using GetLastError.--*/{ HANDLE ReadPipeHandle, WritePipeHandle; DWORD dwError; UCHAR PipeNameBuffer[ MAX_PATH ]; // // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED // if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } // // Set the default timeout to 120 seconds // if (nSize == 0) { nSize = 4096; } sprintf( PipeNameBuffer, "\\\\.\\Pipe\\RemoteExeAnon.%08x.%08x", GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber) ); ReadPipeHandle = CreateNamedPipeA( PipeNameBuffer, PIPE_ACCESS_INBOUND | dwReadMode, PIPE_TYPE_BYTE | PIPE_WAIT, 1, // Number of pipes nSize, // Out buffer size nSize, // In buffer size 120 * 1000, // Timeout in ms lpPipeAttributes ); if (! ReadPipeHandle) { return FALSE; } WritePipeHandle = CreateFileA( PipeNameBuffer, GENERIC_WRITE, 0, // No sharing lpPipeAttributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | dwWriteMode, NULL // Template file ); if (INVALID_HANDLE_VALUE == WritePipeHandle) { dwError = GetLastError(); CloseHandle( ReadPipeHandle ); SetLastError(dwError); return FALSE; } *lpReadPipe = ReadPipeHandle; *lpWritePipe = WritePipeHandle; return( TRUE );}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3923/" ] }
60,649
I'm looking for suggestions on possible IPC mechanisms that are: Cross platform (Win32 and Linux at least) Simple to implement in C++ as well as the most common scripting languages (perl, ruby, python, etc). Finally, simple to use from a programming point of view! What my options are? I'm programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets and pipes behave pretty much the same behavior. While the APIs for setting them up and connecting them are different, they both just act like streams of data. The difficult part, however, is not the communication channel, but the messages you pass over it. You really want to look at something that will perform verification and parsing for you. I recommend looking at Google's Protocol Buffers . You basically create a spec file that describes the object you want to pass between processes, and there is a compiler that generates code in a number of different languages for reading and writing objects that match the spec. It's much easier (and less bug prone) than trying to come up with a messaging protocol and parser yourself.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ] }
60,658
In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic. Please answer in the affirmative - With Do put this here , rather than Don't put that there .
MVC Controller : Put code here that has to do with working out what a user wants, and deciding what to give them, working out whether they are logged in, whether they should see certain data, etc. In the end, the controller looks at requests and works out what data (Models) to show and what Views to render. If you are in doubt about whether code should go in the controller, then it probably shouldn't. Keep your controllers skinny . View : The view should only contain the minimum code to display your data (Model), it shouldn't do lots of processing or calculating, it should be displaying data calculated (or summarized) by the Model, or generated from the Controller. If your View really needs to do processing that can't be done by the Model or Controller, put the code in a Helper. Lots of Ruby code in a View makes the pages markup hard to read. Model : Your model should be where all your code that relates to your data (the entities that make up your site e.g. Users, Post, Accounts, Friends etc.) lives. If code needs to save, update or summarise data related to your entities, put it here. It will be re-usable across your Views and Controllers.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2167252/" ] }
60,680
I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port? What I'm doing now: class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...]class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): passserver = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)server.serve_forever()
Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both http://localhost:1111/ and http://localhost:2222/ from threading import Threadfrom SocketServer import ThreadingMixInfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandlerclass Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!")class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = Truedef serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever()Thread(target=serve_on_port, args=[1111]).start()serve_on_port(2222) update: This also works with Python 3 but three lines need to be slightly changed: from socketserver import ThreadingMixInfrom http.server import HTTPServer, BaseHTTPRequestHandler and self.wfile.write(bytes("Hello World!", "utf-8"))
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4321/" ] }
60,683
Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated. I am using visual studio 2005
Better use grid view control, but if you want only one column with checkboxes and that column is the first one you can just write: this.listView1.CheckBoxes = true;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
60,720
What is the best way for me to determine a controller variable's value during execution? For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?
Yes. The easiest way is to raise the value as a string. Like so: raise @foo.to_s Or, you can install the debugger ( gem install ruby-debug ), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction. Inside the debugger prompt, you have many commands, including p to print the value of a variable. Update: here's a bit more about ruby-debug .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ] }
60,736
I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to: Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific) Configure a secure way of accessing the server (SSH/HTTPS) Configure a set of authorised users (as in, they must authorised to commit, but are free to browse) Validate the setup with an initial commit (a "Hello world" of sorts) These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, nano instead of vi ).
Steps I've taken to make my laptop a Subversion server. Credit must go to AlephZarro for his directions here . I now have a working SVN server (which has currently only been tested locally). Specific setup: Kubuntu 8.04 Hardy Heron Requirements to follow this guide: apt-get package manager program text editor (I use kate) sudo access rights 1: Install Apache HTTP server and required modules: sudo apt-get install libapache2-svn apache2 The following extra packages will be installed: apache2-mpm-worker apache2-utils apache2.2-common 2: Enable SSL sudo a2enmod sslsudo kate /etc/apache2/ports.conf Add or check that the following is in the file: <IfModule mod_ssl.c> Listen 443</IfModule> 3: Generate an SSL certificate: sudo apt-get install ssl-certsudo mkdir /etc/apache2/sslsudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem 4: Create virtual host sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserversudo kate /etc/apache2/sites-available/svnserver Change (in ports.conf): "NameVirtualHost *" to "NameVirtualHost *:443" and (in svnserver) <VirtualHost *> to <VirtualHost *:443> Add, under ServerAdmin (also in file svnserver): SSLEngine onSSLCertificateFile /etc/apache2/ssl/apache.pemSSLProtocol allSSLCipherSuite HIGH:MEDIUM 5: Enable the site: sudo a2ensite svnserversudo /etc/init.d/apache2 restart To overcome warnings: sudo kate /etc/apache2/apache2.conf Add: "ServerName $your_server_name" 6: Adding repository(ies):The following setup assumes we want to host multiple repositories.Run this for creating the first repository: sudo mkdir /var/svnREPOS=myFirstReposudo svnadmin create /var/svn/$REPOSsudo chown -R www-data:www-data /var/svn/$REPOSsudo chmod -R g+ws /var/svn/$REPOS 6.a. For more repositories: do step 6 again (changing the value of REPOS), skipping the step mkdir /var/svn 7: Add an authenticated user sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name 8: Enable and configure WebDAV and SVN: sudo kate /etc/apache2/mods-available/dav_svn.conf Add or uncomment: <Location /svn>DAV svn# for multiple repositories - see comments in fileSVNParentPath /var/svnAuthType BasicAuthName "Subversion Repository"AuthUserFile /etc/apache2/dav_svn.passwdRequire valid-userSSLRequireSSL</Location> 9: Restart apache server: sudo /etc/init.d/apache2 restart 10: Validation: Fired up a browser: http://localhost/svn/$REPOShttps://localhost/svn/$REPOS Both required a username and password. I think uncommenting: <LimitExcept GET PROPFIND OPTIONS REPORT></LimitExcept> in /etc/apache2/mods-available/dav_svn.conf , would allow anonymous browsing. The browser shows "Revision 0: /" Commit something: svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing” Accept the certificate and enter password.Check out what you've just committed: svn co --username $user_name https://localhost/svn/$REPOS Following these steps (assuming I haven't made any error copy/pasting), I had a working SVN repository on my laptop.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ] }
60,763
I was always attracted to the world of kernel hacking and embedded systems. Has anyone got good tutorials (+easily available hardware) on starting to mess with such stuff? Something like kits for writing drivers etc, which come with good documentation and are affordable? Thanks!
If you are completely new to kernel development, i would suggest not starting with hardware development and going to some "software-only" kernel modules like proc file / sysfs or for more complex examples filesystem / network development , developing on a uml/vmware/virtualbox/... machine so crashing your machine won't hurt so much :) For embedded development you could go for a small ARM Development Kit or a small Via C3/C4 machine, or any old PC which you can burn with your homebrew USB / PCI / whatever device. A good place to start is probably Kernelnewbies.org - which has lots of links and useful information for kernel developers, and also features a list of easy to implement tasks to tackle for beginners. Some books to read: Understanding the Linux Kernel - a very good reference detailing the design of the kernel subsystems Linux Device Drivers - is written more like a tutorial with a lot of example code, focusing on getting you going and explaining key aspects of the linux kernel. It introduces the build process and the basics of kernel modules. Linux Kernel Module Programming Guide - Some more introductory material As suggested earlier, looking at the linux code is always a good idea, especially as Linux Kernel API's tend to change quite often ... LXR helps a lot with a very nice browsing interface - lxr.linux.no To understand the Kernel Build process, this link might be helpful: Linux Kernel Makefiles (kbuild) Last but not least, browse the Documentation directory of the Kernel Source distribution! Here are some interesting exercises insolently stolen from a kernel development class: Write a kernel module which creates the file /proc/jiffies reporting the current time in jiffies on every read access. Write a kernel module providing the proc file /proc/sleep. When an application writes a number of seconds as ASCII text into this file ("echo 3 > /proc/sleep"), it should block for the specified amount of seconds. Write accesses should have no side effect on the contents of the file, i.e., on the read accesses, the file should appear to be empty (see LDD3, ch. 6/7) Write a proc file where you can store some text temporarily (using echo "blah" > /proc/pipe) and get it out again (cat /proc/pipe), clearing the file. Watch out for synchronisation issues. Modify the pipe example module to register as a character device /dev/pipe, add dynamic memory allocation for write requests. Write a really simple file system.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/573/" ] }
60,764
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own ClassLoader , but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument. Any suggestions for simple code that does this?
The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader: URLClassLoader child = new URLClassLoader( new URL[] {myJar.toURI().toURL()}, this.getClass().getClassLoader());Class classToLoad = Class.forName("com.MyClass", true, child);Method method = classToLoad.getDeclaredMethod("myMethod");Object instance = classToLoad.newInstance();Object result = method.invoke(instance); Painful, but there it is.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/60764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
60,779
Trying to do this sort of thing... WHERE username LIKE '%$str%' ...but using bound parameters to prepared statements in PDO. e.g.: $query = $db->prepare("select * from comments where comment like :search");$query->bindParam(':search', $str);$query->execute(); I've tried numerous permutations of single quotes and % signs and it's just getting cross with me. I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine: $str = "%$str%";$query = $db->prepare("select * from comments where comment like :search");$query->bindParam(':search', $str);$query->execute();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ] }
60,785
How can I show a grey transparent overlay in C#? It should overlay other process which are not owned by the application doing the overlay.
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine: $str = "%$str%";$query = $db->prepare("select * from comments where comment like :search");$query->bindParam(':search', $str);$query->execute();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ] }
60,805
How do I select one or more random rows from a table using SQLAlchemy?
This is very much a database-specific issue. I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy: from sqlalchemy.sql.expression import func, selectselect.order_by(func.random()) # for PostgreSQL, SQLiteselect.order_by(func.rand()) # for MySQLselect.order_by('dbms_random.value') # For Oracle Next, you need to limit the query by the number of records you need (for example using .limit() ). Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; here is good article about it.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ] }
60,825
I am working on a web application, where I transfer data from the server to the browser in XML. Since I'm danish, I quickly run into problems with the characters æøå . I know that in html, I use the "&amp;aelig;&amp;oslash;&amp;aring;" for æøå . however, as soon as the chars pass through JavaScript, I get black boxes with "?" in them when using æøå , and "&aelig;&oslash;&aring;" is printed as is. I've made sure to set it to utf-8, but that isn't helping much. Ideally, I want it to work with any special characters (naturally). The example that isn't working is included below: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" charset="utf-8"> alert("&aelig;&oslash;&aring;"); alert("æøå"); </script> </head> <body> </body></html> What am I doing wrong? Ok, thanks to Grapefrukts answer, I got it working. I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP: utf8_encode($MyStringHere)
Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ] }
60,830
While it would be very convenient to use inline functions at some situations, Are there any drawbacks with inline functions? Conclusion : Apparently, There is nothing wrong with using inline functions. But it is worth noting the following points! Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. - Google Guidelines The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source There are few situations where an inline function may not work: For a function returning values; if a return statement exists. For a function not returning any values; if a loop, switch or goto statement exists. If a function is recursive. -Source The __inline keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline keyword to be ignored. -Source
It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace. The main drawback to inline functions is that it can increase the size of your executable (depending on the number of instantiations). This can be a problem on some platforms (eg. embedded systems), especially if the function itself is recursive. I'd also recommend making inline'd functions very small - The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
60,848
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
The standard Python dict does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python). On older versions of Python you can use collections.OrderedDict .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/60848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
60,857
Is there a mod_rewrite equivalent for IIS 7.0 that's a) more or less complete b) suitable for a production environment, i.e. battle-tested/dependable/secure Do you have an experience-based recommendation?
Check out the URL Rewrite Module for IIS 7 created by Microsoft
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050/" ] }
60,871
We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation. Therefore, we've been looking at some alternative memory allocation mechanisms that may help us and I'm hoping someone can tell me the best one: 1) Use Windows Low-fragmentation Heap 2) jemalloc - as used in Firefox 3 3) Doug Lea's malloc Our server process is developed using cross-platform C++ code, so any solution would be ideally cross-platform also (do *nix operating systems suffer from this type of memory fragmentation?). Also, am I right in thinking that LFH is now the default memory allocation mechanism for Windows Server 2008 / Vista?... Will my current problems "go away" if our customers simply upgrade their server os?
First, I agree with the other posters who suggested a resource leak. You really want to rule that out first. Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all free blocks) and also the total number of blocks that it is divided over. If the average free block size is relatively small compared to the total free space in the heap, then you do have a fragmentation problem. Alternatively, if you can dump the size of the largest free block and compare that to the total free space, that will accomplish the same thing. The largest free block would be small relative to the total free space available across all blocks if you are running into fragmentation. To be very clear about the above, in all cases we are talking about free blocks in the heap, not the allocated blocks in the heap. In any case, if the above conditions are not met, then you do have a leak situation of some sort. So, once you have ruled out a leak, you could consider using a better allocator. Doug Lea's malloc suggested in the question is a very good allocator for general use applications and very robust most of the time. Put another way, it has been time tested to work very well for most any application. However, no algorithm is ideal for all applications and any management algorithm approach can be broken by the right pathelogical conditions against it's design. Why are you having a fragmentation problem? - Sources of fragmentation problems are caused by the behavior of an application and have to do with greatly different allocation lifetimes in the same memory arena. That is, some objects are allocated and freed regularly while other types of objects persist for extended periods of time all in the same heap.....think of the longer lifetime ones as poking holes into larger areas of the arena and thereby preventing the coalesce of adjacent blocks that have been freed. To address this type of problem, the best thing you can do is logically divide the heap into sub arenas where the lifetimes are more similar. In effect, you want a transient heap and a persistent heap or heaps that group things of similar lifetimes. Some others have suggested another approach to solve the problem which is to attempt to make the allocation sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation - which is in effect the wasted space you have by allocating more memory in the block than you need. Additionally, with a good heap allocator, like Doug Lea's, making the block sizes more similar is unnecessary because the allocator will already be doing a power of two size bucketing scheme that will make it completely unnecessary to artificially adjust the allocation sizes passed to malloc() - in effect, his heap manager does that for you automatically much more robustly than the application will be able to make adjustments.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2958/" ] }
60,877
I have a query where I wish to retrieve the oldest X records. At present my query is something like the following: SELECT Id, Title, Comments, CreatedDateFROM MyTableWHERE CreatedDate > @OlderThanDateORDER BY CreatedDate DESC I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first. So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.
Why not just use a subquery? SELECT T1.* FROM(SELECT TOP X Id, Title, Comments, CreatedDateFROM MyTableWHERE CreatedDate > @OlderThanDateORDER BY CreatedDate) T1ORDER BY CreatedDate DESC
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5086/" ] }
60,878
Is there a way to tell MS SQL that a query is not too important and that it can (and should) take its time? Likewise is there a way to tell MS SQL that it should give higher priority to a query?
Not in versions below SQL 2008. In SQL Server 2008 there's the resource governor. Using that you can assign logins to groups based on properties of the login (login name, application name, etc). The groups can then be assigned to resource pools and limitations or restrictions i.t.o. resources can be applied to those resource pools
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
60,904
How can I open a cmd window in a specific location without having to navigate all the way to the directory I want?
This might be what you want: cmd /K "cd C:\Windows\" Note that in order to change drive letters, you need to use cd /d . For example: C:\Windows\System32\cmd.exe /K "cd /d H:\Python\" (documentation)
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/60904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ] }
60,918
I'm trying to do 'Attach to Process' for debugging in Visual Studio 2008 and I can't figure out what process to attach to. Help.
Indeed it is still w3wp.exe - You'll need to check the ' Show processes in all sessions ' option to get it to show up though. (It caught me out for a while too.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/60918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ] }
60,919
Can I use this approach efficiently? using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)){ cmd.Connection.Open(); // set up parameters and CommandType to StoredProcedure etc. etc. cmd.ExecuteNonQuery();} My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?
No, Disposing of the SqlCommand will not effect the Connection. A better approach would be to also wrap the SqlConnection in a using block as well: using (SqlConnection conn = new SqlConnection(connstring)){ conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdstring, conn)) { cmd.ExecuteNonQuery(); }} Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should be disposed of as well, and likely more important to dispose of than a command. EDIT: I just tested this: SqlConnection conn = new SqlConnection(connstring);conn.Open();using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn)){ Console.WriteLine(cmd.ExecuteScalar().ToString());}using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn)){ Console.WriteLine(cmd.ExecuteScalar().ToString());}conn.Dispose(); The first command was disposed when the using block was exited. The connection was still open and good for the second command. So, disposing of the command definitely does not dispose of the connection it was using.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ] }
60,939
When you are starting a personal programming project, what is your first step? I'm trying to start a project thats just an idea at the moment. I get lots of these and I dive right into the code and after a while just completely lose interest and or just forget about the project. When you are starting, what is your first step? do you plan out the project? make a diagram? write some code on paper? How do you start a project in a manner that you know you will succeed?
The only thing that works for me: Create the smallest possible implementation of it that's somehow usable and then use it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/60939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ] }
60,942
I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3: proc2 -> stdout / proc1 \ proc3 -> stdout I tried proc1 | (proc2 & proc3) but it doesn't seem to work, i.e. echo 123 | (tr 1 a & tr 1 b) writes b23 to stdout instead of a23 b23
Editor's note : - >(…) is a process substitution that is a nonstandard shell feature of some POSIX-compatible shells: bash , ksh , zsh . - This answer accidentally sends the output process substitution's output through the pipeline too : echo 123 | tee >(tr 1 a) | tr 1 b . - Output from the process substitutions will be unpredictably interleaved, and, except in zsh , the pipeline may terminate before the commands inside >(…) do. In unix (or on a mac), use the tee command : $ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/nullb23a23 Usually you would use tee to redirect output to multiple files, but using >(...) you canredirect to another process. So, in general, $ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null will do what you want. Under windows, I don't think the built-in shell has an equivalent. Microsoft's Windows PowerShell has a tee command though.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/60942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085/" ] }
60,950
I find working on the command line in Windows frustrating, primarily because the console window is wretched to use compared to terminal applications on linux and OS X such as "rxvt", "xterm", or "Terminal". Major complaints: No standard copy/paste. You have to turn on "mark" mode and it's only available from a multi-level popup triggered by the (small) left hand corner button. Then copy and paste need to be invoked from the same menu You can't arbitrarily resize the window by dragging, you need to set a preference (back to the multi-level popup) each time you want to resize a window You can only make the window so big before horizontal scroll bars enter the picture. Horizontal scroll bars suck. With the cmd.exe shell, you can't navigate to folders with \\netpath notation (UNC?), you need to map a network drive. This sucks when working on multiple machines that are going to have different drives mapped Are there any tricks or applications, (paid or otherwise), that address these issue?
Sorry for the self-promotion, I'm the author of another Console Emulator, not mentioned here. ConEmu is opensource console emulator with tabs, which represents multiple consoles and simple GUI applications as one customizable GUI window. Initially, the program was designed to work with Far Manager (my favorite shell replacement - file and archive management, command history and completion, powerful editor). But ConEmu can be used with any other console application or simple GUI tools (like PuTTY for example). ConEmu is a live project, open to suggestions. A brief excerpt from the long list of options: Latest versions of ConEmu may set up itself as default terminal for Windows Use any font installed in the system, or copied to a folder of the program (ttf, otf, fon, bdf) Run selected tabs as Administrator (Vista+) or as selected user Windows 7 Jump lists and Progress on taskbar Integration with DosBox (useful in 64bit systems to run DOS applications) Smooth resize, maximized and fullscreen window modes Scrollbar initially hidden, may be revealed by mouseover or checkbox in settings Optional settings (e.g. pallette) for selected applications User friendly text and block selection (from keyboard or mouse), copy, paste, text search in console ANSI X3.64 and Xterm 256 color Far Manager users will acquire shell style drag-n-drop, thumbnails and tiles in panles, tabs for editors and viewers, true colors and font styles (italic/bold/underline). PS. Far Manager supports UNC paths (\\server\share\...)
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/60950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ] }
61,002
I'd like to script, preferably in rake, the following actions into a single command: Get the version of my local git repository. Git pull the latest code. Git diff from the version I extracted in step #1 to what is now in my local repository. In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.
You could do this fairly simply with refspecs. git pull origingit diff @{1}.. That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version: current=`git rev-parse HEAD`git pull origingit diff $current.. I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch: git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ] }
61,005
What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?
You could do this fairly simply with refspecs. git pull origingit diff @{1}.. That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version: current=`git rev-parse HEAD`git pull origingit diff $current.. I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch: git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ] }
61,008
I know this is a broad question, but I've inherited several poor performers and need to optimize them badly. I was wondering what are the most common steps involved to optimize. So, what steps do some of you guys take when faced with the same situation? Related Question: What generic techniques can be applied to optimize SQL queries?
Look at the execution plan in query analyzer See what step costs the most Optimize the step! Return to step 1 [thx to Vinko ]
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
61,033
I've got a table of URLs and I don't want any duplicate URLs. How do I check to see if a given URL is already in the table using PHP/MySQL?
If you don't want to have duplicates you can do following: add uniqueness constraint use " REPLACE " or " INSERT ... ON DUPLICATE KEY UPDATE " syntax If multiple users can insert data to DB, method suggested by @Jeremy Ruten, can lead to an error : after you performed a check someone can insert similar data to the table.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ] }
61,084
I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g. XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement("url", new XElement("loc", "http://www.example.com/page"), new XElement("lastmod", "2008-09-14")))); The result is ... <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url xmlns=""> <loc>http://www.example.com/page</loc> <lastmod>2008-09-14</lastmod> </url></urlset> I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?
The "more correct way" would be: XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),new XElement(ns + "urlset",new XElement(ns + "url", new XElement(ns + "loc", "http://www.example.com/page"), new XElement(ns + "lastmod", "2008-09-14")))); Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.example.com/page</loc> <lastmod>2008-09-14</lastmod> </url></urlset> which is, if I'm not mistaken, what you want.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4449/" ] }
61,085
I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to? By the way, my machine is the standard Mac OS X Leopard install with PHP activated. @Tom Martin Thank you for your reply. I just ran your code and it looks like PHP runs as user _www. I then tried chowning the database to be owned by _www, but that didn't work either. I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write? I've decided to include the code in question. This is going to be more or less a port of Grant's script to PHP. So far it's just the Questions section: <?php$db = new PDO('sqlite:test.db');$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle");curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652");$page = curl_exec($ch);preg_match('/summarycount">.*?([,\d]+)<\/div>.*?Reputation/s', $page, $rep);$rep = preg_replace("/,/", "", $rep[1]);preg_match('/iv class="summarycount".{10,60} (\d+)<\/d.{10,140}Badges/s', $page, $badge);$badge = $badge[1];$qreg = '/question-summary narrow.*?vote-count-post"><strong.*?>(-?\d*).*?\/questions\/(\d*).*?>(.*?)<\/a>/s';preg_match_all($qreg, $page, $questions, PREG_SET_ORDER);$areg = '/(answer-summary"><a href="\/questions\/(\d*).*?votes.*?>(-?\d+).*?href.*?>(.*?)<.a)/s';preg_match_all($areg, $page, $answers, PREG_SET_ORDER);echo "<h3>Questions:</h3>\n";echo "<table cellpadding=\"3\">\n";foreach ($questions as $q){ $query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;'; $dbitem = $db->query($query)->fetch(PDO::FETCH_ASSOC); if ($dbitem['count(id)'] > 0) { $lastQ = $q[1] - $dbitem['votes']; if ($lastQ == 0) { $lastQ = ""; } $query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'"; $db->exec($query); } else { $query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')"; echo "$query\n"; $db->exec($query); $lastQ = "(NEW)"; } echo "<tr><td>$lastQ</td><td align=\"right\">$q[1]</td><td>$q[3]</td></tr>\n";}echo "</table>";?>
Kyle, in order for PDO/Sqlite to work you need write permission to directory where your database resides. Also, I see you perform multiple selects in loop. This may be ok if you are building something small and not heavy loaded. Otherwise I'd suggest building single query that returns multiple rows and process them in separate loop.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ] }
61,088
What "Hidden Features" of JavaScript do you think every programmer should know? After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript. Hidden Features of HTML Hidden Features of CSS Hidden Features of PHP Hidden Features of ASP.NET Hidden Features of C# Hidden Features of Java Hidden Features of Python Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.
You don't need to define any parameters for a function. You can just use the function's arguments array-like object. function sum() { var retval = 0; for (var i = 0, len = arguments.length; i < len; ++i) { retval += arguments[i]; } return retval;}sum(1, 2, 3) // returns 6
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/61088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ] }
61,092
Having read the threads Is SqlCommand.Dispose enough? and Closing and Disposing a WCF Service I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?
I want to clarify this situation. According to Microsoft guidelines, it's a good practice to provide Close method where suitable. Here is a citation from Framework design guidelines Consider providing method Close() , in addition to the Dispose() , if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose ... In most of cases Close and Dispose methods are equivalent. The main difference between Close and Dispose in the case of SqlConnectionObject is: An application can call Close morethan one time. No exception isgenerated. If you called Dispose method SqlConnection object state will bereset. If you try to call anymethod on disposed SqlConnection object, you will receive exception. That said: If you use connection object onetime, use Dispose . A using block will ensure this is called even in the event of an exception. If connection object must be reused,use Close method.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/61092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5086/" ] }
61,109
I have been learning C++ for a while now, I find it very powerful. But, the problem is the the level of abstraction is not much and I have to do memory management myself. What are the languages that I can use which uses a higher level of abstraction.
Java, C#, Ruby, Python and JavaScript are probably the big choices before you. Java and C# are not hugely different languages. This big difference you'll find from C++ is memory management (i.e. objects are automatically freed when they are no longer referenced). You would chose these if you were interested in desktop style applications, or keen on static typing (and you'd probably choose between them based on how you feel towards Microsoft and the Windows platform). In both cases you'll find much richer standard libraries than you'll be used to from C++. Python and Ruby take a step away from static typing, into a world where you can call and method on any object (and fail at runtime if it's not there). That is both a blessing (a lot less boilerplate code) and a curse (the compiler can't catch those errors for you anymore). Once again, you'll find they have richer standard libraries, and are higer level again than Java / C#. Performance is the main downfall, with Python being somewhat faster than Ruby as I understand it. To choose between them, you'd probably choose Ruby if you're interesting in web development for the Ruby on Rails framework community, and otherwise go with Python. JavaScript is even more different from C++ in that it does away with classes entirely. Objects are simply cloned from other objects and can have methods and properties added to them at runtime. Very flexible, but also very easy to make into a total mess. JavaScript is the only real choice if you're interested in running applications in a browser, which is really coming into its own as a platform. You'll find the standard libraries available rather limited if you're not doing a lot with the browser, but there are quite a few good frameworks which fill in some of the gaps. Some other interesting, though more niche choices are Smalltalk - More or less in the Ruby and Python camp, and significantly faster as I understand it. Be careful though _ I've seen lots of good engineers learn Smalltalk and never come back ;) Objective-C - When C went object oriented, C++ went one way (static typing), and Objective-C went the other (dynamic typing). It's quite Smalltalk inspired, and has a good standard library if you're in Mac / iPhone land. In terms of memory management, unlike everything else I've listed, it's not garbage collected (though that's now an option on Mac OS X 10.5), but it does have a reference counting scheme which makes life significantly simpler than managing memory by hand. Lisp - I've never learnt it myself beyond what I needed for minor Emacs hacking. As I understand it, the libraries were nice in their day, but though the language remains supremely elegant, they've fallen a little behind the times. Haskel - If you wanted a complete break from objects and classes, Haskel and it's functional approach is an interesting way to go (or Lisp as above, or F# if you are in .Net land). Basically, you're giving up loops and variables in favour of doing everything recursively. Takes some time to wrap your mind around, and probably isn't practical for most real world applications, but it's a good one to learn. Eiffel - I love it - Very clean syntax, and designed for serious engineering type systems. Statically types like C# and Java, and with a weaker standard library, but it will make you really think about language and class library design. ActionScript and Flex - The programming interface to Flash, which is based on what seems to be a statically typed version of JavaScript. I've played with it a bit, and it's quite slick if you're interested in developing media based applications. You can also push beyond the browser with Flex and into the Air platform to build real desktop apps.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323/" ] }
61,143
Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
Ok, I found some free time finally. Here we go: class TreeNode{ public string Value { get; set;} public List<TreeNode> Nodes { get; set;} public TreeNode() { Nodes = new List<TreeNode>(); }}Action<TreeNode> traverse = null;traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};var root = new TreeNode { Value = "Root" };root.Nodes.Add(new TreeNode { Value = "ChildA"} );root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" });root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" });root.Nodes.Add(new TreeNode { Value = "ChildB"} );root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" });root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" });traverse(root);
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ] }
61,150
My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it staticInit . This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock staticInit with JMockit to not do anything. Let's see this in example. public class ClassWithStaticInit { static { System.out.println("static initializer."); }} Will be changed to public class ClassWithStaticInit { static { staticInit(); } private static void staticInit() { System.out.println("static initialized."); }} So that we can do the following in a JUnit . public class DependentClassTest { public static class MockClassWithStaticInit { public static void staticInit() { } } @BeforeClass public static void setUpBeforeClass() { Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class); }} However this solution also comes with its own problems. You can't run DependentClassTest and ClassWithStaticInitTest on the same JVM since you actually want the static block to run for ClassWithStaticInitTest . What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?
PowerMock is another mock framework that extends EasyMock and Mockito. With PowerMock you can easily remove unwanted behavior from a class, for example a static initializer. In your example you simply add the following annotations to your JUnit test case: @RunWith(PowerMockRunner.class)@SuppressStaticInitializationFor("some.package.ClassWithStaticInit") PowerMock does not use a Java agent and therefore does not require modification of the JVM startup parameters. You simple add the jar file and the above annotations.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3087/" ] }
61,151
If you're writing a library, or an app, where do the unit test files go? It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. Is there a best practice here?
For a file module.py , the unit test should normally be called test_module.py , following Pythonic naming conventions. There are several commonly accepted places to put test_module.py : In the same directory as module.py . In ../tests/test_module.py (at the same level as the code directory). In tests/test_module.py (one level under the code directory). I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with test_ . Actually, the default unittest pattern used for test discovery is test*.py .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
61,156
How do I set up a network between the Host and the guest OS in Windows vista?
Give the guest two network adapters, one NAT and the other Host-only. The NAT one will allow the guest to see the Internet, and the Host-only one will allow the host to see the guest. One of them also allows the guest to see the host. I'm not sure which, but I know it works since I've tested web server stuff with it. You just have to choose the right IP address, 10.x.x.x or 192.168.x.x. Also, you may have to be careful about having File and Printer Sharing running on both adapters at once, since the guest will see its own name and conflict with itself. I ran into this during install.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
61,176
I want to access messages in Gmail from a Java application using JavaMail and IMAP . Why am I getting a SocketTimeoutException ? Here is my code: Properties props = System.getProperties();props.setProperty("mail.imap.host", "imap.gmail.com");props.setProperty("mail.imap.port", "993");props.setProperty("mail.imap.connectiontimeout", "5000");props.setProperty("mail.imap.timeout", "5000");try { Session session = Session.getDefaultInstance(props, new MyAuthenticator()); URLName urlName = new URLName("imap://[email protected]:[email protected]"); Store store = session.getStore(urlName); if (!store.isConnected()) { store.connect(); }} catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1);} catch (MessagingException e) { e.printStackTrace(); System.exit(2);} I have set the timeout values so that it wouldn't take "forever" to timeout. Also, MyAuthenticator also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for IMAP .)
Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now. Properties props = System.getProperties();props.setProperty("mail.store.protocol", "imaps");try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", "<username>@gmail.com", "<password>"); ...} catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1);} catch (MessagingException e) { e.printStackTrace(); System.exit(2);} This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2512222/" ] }
61,211
If you were to self-fund a software project which tools, frameworks, components would you employ to ensure maximum productivity for the dev team and that the "real" problem is being worked on. What I'm looking for are low friction tools which get the job done with a minimum of fuss. Tools I'd characterize as such are SVN/TortioseSVN, ReSharper, VS itself. I'm looking for frameworks which solve the problems inherient in all software projects like ORM, logging, UI frameworks/components. An example on the UI side would be ASP.NET MVC vs WebForms vs MonoRail.
Versioning. Subversion is the popular choice. If you can afford it, Team Foundation Server offers some benefits. If you want to be super-modern, consider a distributed versioning system, such as git , bazaar or Mercurial . Whatever you do, don't use SourceSafe or other lock-based tools, but rather merge-baseed ones. Consider installing both a Windows Explorer client (such as TortoiseSVN ) as well as a Visual Studio add-in (such as AnkhSVN or VisualSVN ). Issue tracking. Given that Joel Spolsky is on this site's staff, FogBugz deserves a mention. Trac , Mantis and BugZilla are widespread open-source choices. Continuous integration. CruiseControl.NET is a popular and open-source choice. There's also Draco.NET . Unit testing. NUnit is the popular open-source choice. Does the job. Consider installing the TestDriven.NET Visual Studio add-in. That said, you want to look at the answers to Essential Programming Tools and What is your best list of ‘must have’ development tools? ; while not .NET-specific, they should apply anyway.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6149/" ] }
61,212
How do I delete untracked local files from the current working tree?
git-clean - Remove untracked files from the working tree Synopsis git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>… Description Cleans the working tree by recursively removing files that are not under version control, starting from the current directory . Normally, only files unknown to Git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to remove all build products. If any optional <path>... arguments are given, only those paths are affected. Step 1 is to show what will be deleted by using the -n option: # Print out the list of files and directories which will be removed (dry run)git clean -n -d Clean Step - beware: this will delete files : # Delete the files from the repositorygit clean -f To remove directories, run git clean -f -d or git clean -fd To remove ignored files, run git clean -f -X or git clean -fX To remove ignored and non-ignored files, run git clean -f -x or git clean -fx Note the case difference on the X for the two latter commands. If clean.requireForce is set to "true" (the default) in your configuration, one needs to specify -f otherwise nothing will actually happen. Again see the git-clean docs for more information. Options -f , --force If the Git configuration variable clean.requireForce is not set tofalse, git clean will refuse to run unless given -f , -n or -i . -x Don’t use the standard ignore rules read from .gitignore (perdirectory) and $GIT_DIR/info/exclude , but do still use the ignorerules given with -e options. This allows removing all untracked files,including build products. This can be used (possibly in conjunctionwith git reset) to create a pristine working directory to test a cleanbuild. -X Remove only files ignored by Git. This may be useful to rebuildeverything from scratch, but keep manually created files. -n , --dry-run Don’t actually remove anything, just show what would be done. -d Remove untracked directories in addition to untracked files. If anuntracked directory is managed by a different Git repository, it isnot removed by default. Use -f option twice if you really want toremove such a directory.
{ "score": 14, "source": [ "https://Stackoverflow.com/questions/61212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
61,219
I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...). He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.: Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter"); Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i <= 3 must never happen because of the flobittyjam widgitification process". So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things. But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this: Debug.Assert(i > 3, "i must be greater than 3 because of the flibbity widgit status");if (i <= 3){ throw new ArgumentOutOfRangeException("i", "i must be > 3 because... i=" + i.ToString());} What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation... double interestAmount = loan.GetInterest();Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc"); ...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?
Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the ArgumentOutOfRangeException thrown as necessary. Assertions are for testing for "impossible" situations, i.e., things that you (in your program logic) assume are true. The assertions are there to tell you if these assumptions are broken for any reason. Hope this helps!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004/" ] }
61,227
If I have: signed char * p; and I do a comparison: if ( *p == 0xFF ) break; it will never catch 0XFF, but if I replace it with -1 it will: if ( *p == (signed char)0xFF ) break; How can this happen? Is it something with the sign flag? I though that 0xFF == -1 == 255 .
The value 0xFF is a signed int value. C will promote the *p to an int when doing the comparison, so the first if statement is equivalent to: if( -1 == 255 ) break; which is of course false. By using (signed char)0xFF the statement is equivalent to: if( -1 == -1 ) break; which works as you expect. The key point here is that the comparison is done with int types instead of signed char types.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ] }
61,233
What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so: INSERT INTO some_table (column1, column2, column3)SELECTRows.n.value('(@column1)[1]', 'varchar(20)'),Rows.n.value('(@column2)[1]', 'nvarchar(100)'),Rows.n.value('(@column3)[1]', 'int'),FROM @xml.nodes('//Rows') Rows(n) However I find that this is getting very slow for even moderate size xml data.
Stumbled across this question whilst having a very similar problem, I'd been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up. However, after a little more research I found that having typed the XML using a schema and created an XML Index (I'd bulk inserted into a table) the same query completed in ~ 0.04ms. How's that for a performance improvement! Code to create a schema: IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema')DROP XML SCHEMA COLLECTION [MyXmlSchema]GODECLARE @MySchema XMLSET @MySchema = ( SELECT * FROM OPENROWSET ( BULK 'C:\Path\To\Schema\MySchema.xsd', SINGLE_CLOB ) AS xmlData)CREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema GO Code to create the table with a typed XML column: CREATE TABLE [dbo].[XmlFiles] ( [Id] [uniqueidentifier] NOT NULL, -- Data from CV element [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL,CONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED ( [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] Code to create Index CREATE PRIMARY XML INDEX PXML_DataON [dbo].[XmlFiles] (Data) There are a few things to bear in mind though. SQL Server's implementation of Schema doesn't support xsd:include. This means that if you have a schema which references other schema, you'll have to copy all of these into a single schema and add that. Also I would get an error: XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'. if I tried to navigate above the node I had selected with the nodes function. E.g. SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,C.value('../SequenceNumber[1]', 'INT') AS [Level]FROM [dbo].[XmlFiles]CROSS APPLY [Data].nodes('/CVSet/Level/CVElement') AS T(C) Found that the best way to handle this was to use the OUTER APPLY to in effect perform an "outer join" on the XML. SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,B.value('SequenceNumber[1]', 'INT') AS [Level]FROM [dbo].[XmlFiles]CROSS APPLY [Data].nodes('/CVSet/Level') AS T(B)OUTER APPLY B.nodes ('CVElement') AS S(C) Hope that that helps someone as that's pretty much been my day.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ] }
61,250
I know that tables are for tabular data, but it's so tempting to use them for layout. I can handle DIV's to get a three column layout, but when you got 4 nested DIV's, it get tricky. Is there a tutorial/reference out there to persuade me to use DIV's for layout? I want to use DIV's, but I refuse to spend an hour to position my DIV/SPAN where I want it. @GaryF: Blueprint CSS has to be the CSS's best kept secret. Great tool - Blueprint Grid CSS Generator .
There's the Yahoo Grid CSS which can do all sorts of things. But remember: CSS IS NOT A RELIGION . If you save hours by using tables instead of css, do so. One of the corner cases I could never make my mind up about is forms. I'd love to do it in css, but it's just so much more complicated than tables. You could even argue that forms are tables, in that they have headers (labels) and data (input fields).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661/" ] }
61,253
The subject says it all - normally easy and cross platform way is to poll, intelligently. But every OS has some means to notify without polling. Is it possible in a reasonably cross platform way? (I only really care about Windows and Linux, but I use mac, so I thought posix may help?)
Linux users can use inotify inotify is a Linux kernel subsystem that provides file system event notification. Some goodies for Windows fellows: File Change Notification on MSDN " When Folders Change " article File System Notification on Change
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699/" ] }
61,256
I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message: Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nacheiner bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oderdie hergestellte Verbindung war fehlerhaft, da der verbundene Hostnicht reagiert hat 192.168.123.254:8080 Which roughly translates to "cant connect to 192.168.123.254:8080" The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used. How do I prevent the IIS from using a proxy? I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined. The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user? What can I do, where else i could check?
Proxy use can be configured in the web.config.The system.net/defaultProxy element will let you specify whether a proxy is used by default or provide a bypass list. For more info see: http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6297/" ] }
61,262
Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file. Now you want to create a class or use a symbol which is defined in multiple namespaces, e.g. System.Windows.Controls.Image & System.Drawing.Image Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here? (Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)
Use alias using System.Windows.Controls;using Drawing = System.Drawing;...Image img = ... //System.Windows.Controls.ImageDrawing.Image img2 = ... //System.Drawing.Image C# using directive
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ] }
61,278
What method do you use when you want to get performance data about specific code paths?
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't. I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with DbgView ), including how many times the code was executed (and the average time spent of course)). #pragma once#include <tchar.h>#include <windows.h>#include <sstream>#include <boost/noncopyable.hpp>namespace scope_timer { class time_collector : boost::noncopyable { __int64 total; LARGE_INTEGER start; size_t times; const TCHAR* name; double cpu_frequency() { // cache the CPU frequency, which doesn't change. static double ret = 0; // store as double so devision later on is floating point and not truncating if (ret == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); ret = static_cast<double>(freq.QuadPart); } return ret; } bool in_use; public: time_collector(const TCHAR* n) : times(0) , name(n) , total(0) , start(LARGE_INTEGER()) , in_use(false) { } ~time_collector() { std::basic_ostringstream<TCHAR> msg; msg << _T("scope_timer> ") << name << _T(" called: "); double seconds = total / cpu_frequency(); double average = seconds / times; msg << times << _T(" times total time: ") << seconds << _T(" seconds ") << _T(" (avg ") << average <<_T(")\n"); OutputDebugString(msg.str().c_str()); } void add_time(__int64 ticks) { total += ticks; ++times; in_use = false; } bool aquire() { if (in_use) return false; in_use = true; return true; } }; class one_time : boost::noncopyable { LARGE_INTEGER start; time_collector* collector; public: one_time(time_collector& tc) { if (tc.aquire()) { collector = &tc; QueryPerformanceCounter(&start); } else collector = 0; } ~one_time() { if (collector) { LARGE_INTEGER end; QueryPerformanceCounter(&end); collector->add_time(end.QuadPart - start.QuadPart); } } };}// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)#define TIME_THIS_SCOPE(name) \ static scope_timer::time_collector st_time_collector_##name(_T(#name)); \ scope_timer::one_time st_one_time_##name(st_time_collector_##name)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ] }
61,307
I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't. I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with DbgView ), including how many times the code was executed (and the average time spent of course)). #pragma once#include <tchar.h>#include <windows.h>#include <sstream>#include <boost/noncopyable.hpp>namespace scope_timer { class time_collector : boost::noncopyable { __int64 total; LARGE_INTEGER start; size_t times; const TCHAR* name; double cpu_frequency() { // cache the CPU frequency, which doesn't change. static double ret = 0; // store as double so devision later on is floating point and not truncating if (ret == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); ret = static_cast<double>(freq.QuadPart); } return ret; } bool in_use; public: time_collector(const TCHAR* n) : times(0) , name(n) , total(0) , start(LARGE_INTEGER()) , in_use(false) { } ~time_collector() { std::basic_ostringstream<TCHAR> msg; msg << _T("scope_timer> ") << name << _T(" called: "); double seconds = total / cpu_frequency(); double average = seconds / times; msg << times << _T(" times total time: ") << seconds << _T(" seconds ") << _T(" (avg ") << average <<_T(")\n"); OutputDebugString(msg.str().c_str()); } void add_time(__int64 ticks) { total += ticks; ++times; in_use = false; } bool aquire() { if (in_use) return false; in_use = true; return true; } }; class one_time : boost::noncopyable { LARGE_INTEGER start; time_collector* collector; public: one_time(time_collector& tc) { if (tc.aquire()) { collector = &tc; QueryPerformanceCounter(&start); } else collector = 0; } ~one_time() { if (collector) { LARGE_INTEGER end; QueryPerformanceCounter(&end); collector->add_time(end.QuadPart - start.QuadPart); } } };}// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)#define TIME_THIS_SCOPE(name) \ static scope_timer::time_collector st_time_collector_##name(_T(#name)); \ scope_timer::one_time st_one_time_##name(st_time_collector_##name)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ] }
61,317
It seems that Silverlight/WPF are the long term future for user interface development with .NET. This is great because as I can see the advantage of reusing XAML skills on both the client and web development sides. But looking at WPF/XAML/Silverlight they seem very large technologies and so where is the best place to get start? I would like to hear from anyone who has good knowledge of both and can recommend which is a better starting point and why.
Should you learn ASP.NET or Winforms first? ASP or MFC? HTML or VB? C# or VB? Set aside the idea that there is a logical progression through what has become a highly complex interwoven set of technologies, and take a step back and ask yourself a series of questions: What are your goals; how do you want to balance profit against enjoyment Are you short term oriented or in for the long haul Are you the type of person who likes to get good at something and do it a lot or do you get bored once you fully understand it? The next and hardest step is to come to accept that any advice you are given is bound to be wrong; and the longer the time horizon the more likely it is to be incorrect. If the advice is for more than six to 12 months, the probability the advice is wildly incorrect approaches 1. I can only tell you my story, quickly. In 2000 I was happy as a consultant working profitably in C++ on Windows applications, writing about ASP.NET and WinForms. then I saw C# and the world turned upside down. I never went back. Two years ago I had the same kind of revelation, only an order of magnitude bigger, stronger and with more conviction about Silverlight. Yes, WPF is magnificent, and it may be that I'm all wet about this, but I believe in my gut that Silverlight changes everything. There was no doubt then and there is no doubt today that Silverlight is the most important development platform for Microsoft since .NET (certainly) and possibly since the switch to C++. In a nutshell, here is why. I don't understand where its limitations are. With most platforms I do: you can do this, but you can't do that. WPF is a pretty good case in point, as was ASP.Net and WinForms and, well really everything until now. With Silverlight, I don't see the boundaries yet. Silverlight has already leaped off the desktop onto phones, and I don't see any reason for it to stop there. Yes, it is true, it is bound by the browser, but I see that less as a jail cell than as a tank in which Silverlight will be riding over lots of terrain (it must be very late, I should go to bed). In any case, for now, learning Silverlight is a gas, there is a lot of material on the Silverlight.net site , and what is the very best thing about learning Silverlight is that if you don't see what you need you can holler at me and I'll make sure you get it pretty quickly. Enjoy, good luck and the dirty little secret is you'll be fine whichever you choose. It's all just software. -jesse Jesse Liberty "Silverlight Geek"
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ] }
61,320
SVN in Eclipse is spread into two camps. The SVN people have developed a plugin called Subclipse . The Eclipse people have a plugin called Subversive . Broadly speaking they both do the same things. What are the advantages and disadvantages of each?
Both are very similar but Subversive is the "eclipse svn provider". I primarily use Subversive because of a few convenient features: Grouping of history When I'm browsing the history of a branch instead of just seeing a bunch of rows for every commit it can group commits by today, week, etc. Mapping of trunk, branches, and tags Subversive assumes the default svn layout: trunk, branches, tags (which you can change), so whenever you want to tag or branch it is one click and you provide the name of the tag or branch. Like I said these are minor differences that I just find convenient. Both work great with mylyn, but overall there really isn't a whole lot of differences with these two extensions. Merging with Subversive is a pain though (haven't tried Subclipse), I've never been able to successfully merge. The preview of the merge is great but it would never complete the merge or it will take way to long. Most of the time I complete merging through the command line without any issues.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408/" ] }
61,341
I remember back in the day with the old borland DOS compiler you could do something like this: asm { mov ax,ex etc etc...} Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.
Using GCC __asm__("movl %edx, %eax\n\t" "addl $2, %eax\n\t"); Using VC++ __asm { mov eax, edx add eax, 2}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6062/" ] }
61,357
Should I still be using tables anyway? The table code I'd be replacing is: <table> <tr> <td>Name</td><td>Value</td> </tr> ...</table> From what I've been reading I should have something like <label class="name">Name</label><label class="value">Value</value><br />... Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth. EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.
I think that definition lists are pretty close semantically to name/value pairs. <dl> <dt>Name</dt> <dd>Value</dd></dl> Definition lists - misused or misunderstood?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ] }
61,383
My current project is in Rails. Coming from a Symfony (PHP) and Django (Python) background, they both have excellent admin generators. Seems like this is missing in Rails. For those who aren't familiar with Symfony or Django, they both allow you to specify some metadata around your models to automatically (dynamically) generate an admin interface to do the common CRUD operations. You can create an entire Intranet with only a few commands or lines of code. They have a good appearance and are extensible enough for 99% of your admin needs. I've looked for something similar for Rails, but all of the projects either have no activity or they died long ago. Is there anything to generate an intranet/admin site for a rails app other than scaffolding?
Active Admin ( http://activeadmin.info/ ) was released in May of 2011, and looks like it's going to become the best Rails 3 option.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ] }
61,386
Do you expect your WPF developers to know expression blend? Any good resources for learning more about Blend? [UPDATE] Does knowing blend make you more productive?
I found Blend a great way to ease into XAML. Many of the common things you want to do are easy in Blend, especially databinding. Databinding has no intellisense and I found doing things in Blend a great way of discovering how do write the databinding syntax. I now find myself mostly editing raw XAML buy hand. The areas where blend is really handy: Customizing templates. Animation Breaking the UI down into user controls
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ] }
61,400
I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing. My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the properties of good unit tests or how do you write your tests? Language agnostic suggestions are encouraged.
Let me begin by plugging sources - Pragmatic Unit Testing in Java with JUnit (There's a version with C#-Nunit too.. but I have this one.. its agnostic for the most part. Recommended.) Good Tests should be A TRIP (The acronymn isn't sticky enough - I have a printout of the cheatsheet in the book that I had to pull out to make sure I got this right..) Automatic : Invoking of tests as well as checking results for PASS/FAIL should be automatic Thorough : Coverage; Although bugs tend to cluster around certain regions in the code, ensure that you test all key paths and scenarios.. Use tools if you must to know untested regions Repeatable : Tests should produce the same results each time.. every time. Tests should not rely on uncontrollable params. Independent : Very important. Tests should test only one thing at a time. Multiple assertions are okay as long as they are all testing one feature/behavior. When a test fails, it should pinpoint the location of the problem. Tests should not rely on each other - Isolated. No assumptions about order of test execution. Ensure 'clean slate' before each test by using setup/teardown appropriately Professional : In the long run you'll have as much test code as production (if not more), therefore follow the same standard of good-design for your test code. Well factored methods-classes with intention-revealing names, No duplication, tests with good names, etc. Good tests also run Fast . any test that takes over half a second to run.. needs to be worked upon. The longer the test suite takes for a run.. the less frequently it will be run. The more changes the dev will try to sneak between runs.. if anything breaks.. it will take longer to figure out which change was the culprit. Update 2010-08: Readable : This can be considered part of Professional - however it can't be stressed enough. An acid test would be to find someone who isn't part of your team and asking him/her to figure out the behavior under test within a couple of minutes. Tests need to be maintained just like production code - so make it easy to read even if it takes more effort. Tests should be symmetric (follow a pattern) and concise (test one behavior at a time). Use a consistent naming convention (e.g. the TestDox style). Avoid cluttering the test with "incidental details".. become a minimalist. Apart from these, most of the others are guidelines that cut down on low-benefit work: e.g. 'Don't test code that you don't own' (e.g. third-party DLLs). Don't go about testing getters and setters. Keep an eye on cost-to-benefit ratio or defect probability.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ] }
61,401
I know this sounds like a point-whoring question but let me explain where I'm coming from. Out of college I got a job at a PHP shop. I worked there for a year and a half and thought that I had learned all there was to learn about programming. Then I got a job as a one-man internal development shop at a sizable corporation where all the work was in C#. In my commitment to the position I started reading a ton of blogs and books and quickly realized how wrong I was to think I knew everything. I learned about unit testing, dependency injection and decorator patterns, the design principle of loose coupling, the composition over inheritance debate, and so on and on and on - I am still very much absorbing it all. Needless to say my programming style has changed entirely in the last year. Now I find myself picking up a php project doing some coding for a friend's start-up and I feel completely constrained as opposed to programming in C#. It really bothers me that all variables at a class scope have to be referred to by appending '$this->' . It annoys me that none of the IDEs that I've tried have very good intellisense and that my SimpleTest unit tests methods have to start with the word 'test'. It drives me crazy that dynamic typing keeps me from specifying implicitly which parameter type a method expects, and that you have to write a switch statement to do method overloads. I can't stand that you can't have nested namespaces and have to use the :: operator to call the base class's constructor. Now I have no intention of starting a PHP vs C# debate, rather what I mean to say is that I'm sure there are some PHP features that I either don't know about or know about yet fail to use properly. I am set in my C# universe and having trouble seeing outside the glass bowl. So I'm asking, what are your favorite features of PHP? What are things you can do in it that you can't or are more difficult in the .Net languages?
Documentation . The documentation gets my vote. I haven't encountered a more thorough online documentation for a programming language - everything else I have to piece together from various websites and man pages.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ] }
61,405
I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project?
Here is what I would do. Let's say I want the following folder hierarchy : /MyWholeApp will contain the files for the whole application. /MyWholeApp/DummyDlg/ will contain the files for the standalone dialogbox which will be eventually part of the whole application. I would develop the standalone dialog box and the related classes. I would create a Qt-project file which is going to be included. It will contain only the forms and files which will eventually be part of the whole application. File DummyDlg.pri, in /MyWholeApp/DummyDlg/ : # InputFORMS += dummydlg.uiHEADERS += dummydlg.hSOURCES += dummydlg.cpp The above example is very simple. You could add other classes if needed. To develop the standalone dialog box, I would then create a Qt project file dedicated to this dialog : File DummyDlg.pro, in /MyWholeApp/DummyDlg/ : TEMPLATE = appDEPENDPATH += .INCLUDEPATH += .include(DummyDlg.pri)# InputSOURCES += main.cpp As you can see, this PRO file is including the PRI file created above, and is adding an additional file (main.cpp) which will contain the basic code for running the dialog box as a standalone : #include <QApplication>#include "dummydlg.h"int main(int argc, char* argv[]){ QApplication MyApp(argc, argv); DummyDlg MyDlg; MyDlg.show(); return MyApp.exec();} Then, to include this dialog box to the whole application you need to create a Qt-Project file : file WholeApp.pro, in /MyWholeApp/ : TEMPLATE = appDEPENDPATH += . DummyDlgINCLUDEPATH += . DummyDlginclude(DummyDlg/DummyDlg.pri)# InputFORMS += OtherDlg.uiHEADERS += OtherDlg.hSOURCES += OtherDlg.cpp WholeApp.cpp Of course, the Qt-Project file above is very simplistic, but shows how I included the stand-alone dialog box.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ] }
61,421
I'm making an example for someone who hasn't yet realized that controls like ListBox don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the ListBox and I'd like to show him there's a better way. I noticed that if I have an object stored in the ListBox then update a value that affects ToString , the ListBox does not update itself. I've tried calling Refresh and Update on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form: Public Class Form1 Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) MyBase.OnLoad(e) For i As Integer = 1 To 3 Dim tempInfo As New NumberInfo() tempInfo.Count = i tempInfo.Number = i * 100 ListBox1.Items.Add(tempInfo) Next End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click For Each objItem As Object In ListBox1.Items Dim info As NumberInfo = DirectCast(objItem, NumberInfo) info.Count += 1 Next End SubEnd ClassPublic Class NumberInfo Public Count As Integer Public Number As Integer Public Overrides Function ToString() As String Return String.Format("{0}, {1}", Count, Number) End FunctionEnd Class I thought that perhaps the problem was using fields and tried implementing INotifyPropertyChanged , but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.) Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work. So what am I missing?
BindingList handles updating the bindings by itself. using System;using System.ComponentModel;using System.Windows.Forms;namespace TestBindingList{ public class Employee { public string Name { get; set; } public int Id { get; set; } } public partial class Form1 : Form { private BindingList<Employee> _employees; private ListBox lstEmployees; private TextBox txtId; private TextBox txtName; private Button btnRemove; public Form1() { InitializeComponent(); FlowLayoutPanel layout = new FlowLayoutPanel(); layout.Dock = DockStyle.Fill; Controls.Add(layout); lstEmployees = new ListBox(); layout.Controls.Add(lstEmployees); txtId = new TextBox(); layout.Controls.Add(txtId); txtName = new TextBox(); layout.Controls.Add(txtName); btnRemove = new Button(); btnRemove.Click += btnRemove_Click; btnRemove.Text = "Remove"; layout.Controls.Add(btnRemove); Load+=new EventHandler(Form1_Load); } private void Form1_Load(object sender, EventArgs e) { _employees = new BindingList<Employee>(); for (int i = 0; i < 10; i++) { _employees.Add(new Employee() { Id = i, Name = "Employee " + i.ToString() }); } lstEmployees.DisplayMember = "Name"; lstEmployees.DataSource = _employees; txtId.DataBindings.Add("Text", _employees, "Id"); txtName.DataBindings.Add("Text", _employees, "Name"); } private void btnRemove_Click(object sender, EventArgs e) { Employee selectedEmployee = (Employee)lstEmployees.SelectedItem; if (selectedEmployee != null) { _employees.Remove(selectedEmployee); } } }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ] }
61,437
In evaluating different systems integration strategies, I've come across some words of encouragement, but also some words of frustration over BizTalk Server. What are some pros and cons to using BizTalk Server (both from a developer standpoint and a business user), and should companies also consider open source alternatives? What viable alternatives are out there? EDIT: Jitterbit seems like an interesting choice. Open Source and seems to be nicely engineered. Anyone on here have any experience working with it?
My experience with BizTalk was basically a frustrating waste of time. There are so many edge cases and weird little business logic tweaks you have to make when you are doing B2B data integration (which is probably the hardest part of any enterprise application) that you just need to roll your own solution. How hard is it to parse data files and convert them to a different format? Not that hard. Unless you're trying to inject a bloated middleware system like Biztalk into the middle of it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
61,446
Particularly, what is the best snippets package out there? Features: easy to define new snippets (plain text, custom input with defaults) simple navigation between predefined positions in the snippet multiple insertion of the same custom input accepts currently selected text as a custom input cross-platform (Windows, Linux) dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred) nicely coexists with others packages in Emacs Example of code template, a simple for loop in C: for (int i = 0; i < %N%; ++i) { _} It is a lot of typing for such common code. I want to invoke a code template or snippet which insertsthat boilerplate code for me. Additionally it stops (on TAB or other keystroke) at %N% (my input replaces it) and final position of the cursor is _ .
TextMate's snippets is the most closest match but it is not a cross-platform solution and not for Emacs. The second closest thing is YASnippet ( screencast shows the main capabilities). But it interferes with hippie-expand package in my setup and the embedded language is EmacsLisp which I'm not comfortable with outside .emacs . EDIT : Posted my answer here to allow voting on YASnippet .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ] }
61,449
I've just created a new Windows XP VM on my Mac using VMware Fusion. The VM is using NAT to share the host's internet connection. How do I access a Rails application, which is accessible on the Mac itself using http://localhost:3000 ?
On the XP machine, find your IP address by going to the command prompt and typing ipconfig . Try replacing the last number with 1 or 2. For example, if your IP address is 192.168.78.128, use http://192.168.78.1:3000 .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ] }
61,451
Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using {% url mapper.views.foo %} But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link_to helper? I found django-helpers but since this is a common thing I thought Django would have something built-in.
No it doesn't. James Bennett answered a similar question a while back, regarding Rails' built-in JavaScript helpers. It's really unlikely that Django will ever have 'helper' functionality built-in. The reason, if I understand correctly, has to do with Django's core philosophy of keeping things loosely coupled . Having that kind of helper functionality built-in leads to coupling Django with a specific JavaScript library or (in your case) html document type. EG. What happens if/when HTML 5 is finally implemented and Django is generating HTML 4 or XHTML markup? Having said that, Django's template framework is really flexible, and it wouldn't be terribly difficult to write your own tags/filters that did what you wanted. I'm mostly a designer myself, and I've been able to put together a couple custom tags that worked like a charm.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ] }
61,456
After trying to avoid JavaScript for years, Iv started using Query for validation in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is. Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api? Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.: <script type="text/javascript">$().ready(function() {$("#CreateLog").validate({ rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters", } } });});</script><form id="CreateLog" action="Create" method="post" /> <label>UserName</label><br /> <%=Html.TextBox("UserName")%> <br /> <div class="error"> </div> <input type=submit value=Save /> </form> I tried adding this to the script: errorLabelContainer: $("#CreateLog div.error") and this to the html: <div class="error"> </div> But this didn't work.
Try specifying both a wrapper and a label container in your options. I also added display:none; to the style of error-container to let jQuery decide when to show it. $().ready(function() { $("#CreateLog").validate({ errorLabelContainer: $("ul", $('div.error-container')), wrapper: 'li', rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters" } } });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="error-container"> <ul></ul></div><form id="CreateLog" action="Create" method="post" /> <label>UserName</label><br /> <%=Html.TextBox("UserName")%> <br /> <input type=submit value=Save /></form> That should work.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
61,480
In the past we declared properties like this: public class MyClass{ private int _age; public int Age { get{ return _age; } set{ _age = value; } }} Now we can do: public class MyClass{ public int Age {get; set;} } My question is, how can I access the private variable that is created automatically using this notation? I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?
The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set. If you want to access the private member that these properties use, that's usually for a few reasons: You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member. You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly. You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e. public class MyClass{ public int Age {get; private set;} } This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/61480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
61,486
I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time. This is what I have that works so far: $("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id"); Is there a way to refactor this? Is there an easier way to figure this out?
Assign the same class to each div then: $("div.myClass:visible").attr("id");
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ] }
61,517
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo:... bar = 'hello'... baz = 'world'...>>> f = Foo()>>> props(f){ 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.
Note that best practice in Python 2.7 is to use new-style classes (not needed with Python 3), i.e. class Foo(object): ... Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary object , it's sufficient to use __dict__ . Usually, you'll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example: >>> class A(object):... def __init__(self):... self.b = 1... self.c = 2... def do_nothing(self):... pass...>>> a = A()>>> a.__dict__{'c': 2, 'b': 1} A better approach (suggested by robert in comments) is the builtin vars function: >>> vars(a){'c': 2, 'b': 1} Alternatively, depending on what you want to do, it might be nice to inherit from dict . Then your class is already a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example: class Foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc...
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/61517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ] }
61,520
There is a lot of information out there on object-relational mappers and how to best avoid impedance mismatch, all of which seem to be moot points if one were to use an object database. My question is why isn't this used more frequently? Is it because of performance reasons or because object databases cause your data to become proprietary to your application or is it due to something else?
Familiarity. The administrators of databases know relational concepts; object ones, not so much. Performance. Relational databases have been proven to scale far better. Maturity. SQL is a powerful, long-developed language. Vendor support. You can pick between many more first-party (SQL servers) and third-party (administrative interfaces, mappings and other kinds of integration) tools than is the case with OODBMSs. Naturally, the object-oriented model is more familiar to the developer , and, as you point out, would spare one of ORM. But thus far, the relational model has proven to be the more workable option. See also the recent question, Object Orientated vs Relational Databases .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ] }
61,524
I have a network C++ program in Windows that I'd like to test for network disconnects at various times. What are my options? Currently I am: Actually disconnecting the network wire from the back of my computer using ipconfig /release Using the cports program to close out the socket completely None of these methods though are ideal for me, and I'd like to emulate network problems more easily. I would like for sometimes connects to fail, sometimes socket reads to fail, and sometimes socket writes to fail. It would be great if there was some utility I could use to emulate these types of problems. It would also be nice to be able to build some automated unit tests while this emulated bad network is up.
You might want to abstract the network layer, and then you can have unit tests that inject interesting failure events at appropriate points.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
61,535
I get a URL from a user. I need to know: a) is the URL a valid RSS feed? b) if not is there a valid feed associated with that URL using PHP/Javascript or something similar (Ex. http://techcrunch.com fails a), but b) would return their RSS feed)
Found something that I wanted: Google's AJAX Feed API has a load feed and lookup feed function (Docs here ). a) Load feed provides the feed (and feed status) in JSON b) Lookup feed provides the RSS feed for a given URL Theres also a find feed function that searches for RSS feeds based on a keyword. Planning to use this with JQuery's $.getJSON
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ] }
61,552
Alan Storm's comments in response to my answer regarding the with statement got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of with , while avoiding its pitfalls. Where have you found the with statement useful?
Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: Defining Variables inside Block Scope . Background JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in: var name = "Joe";if ( true ){ var name = "Jack";}// name now contains "Jack" Declaring a closure in a loop is a common task where this can lead to errors: for (var i=0; i<3; ++i){ var num = i; setTimeout(function() { alert(num); }, 10);} Because the for loop does not introduce a new scope, the same num - with a value of 2 - will be shared by all three functions. A new scope: let and with With the introduction of the let statement in ES6 , it becomes easy to introduce a new scope when necessary to avoid these problems: // variables introduced in this statement // are scoped to each iteration of the loopfor (let i=0; i<3; ++i){ setTimeout(function() { alert(i); }, 10);} Or even: for (var i=0; i<3; ++i){ // variables introduced in this statement // are scoped to the block containing it. let num = i; setTimeout(function() { alert(num); }, 10);} Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using with : for (var i=0; i<3; ++i){ // object members introduced in this statement // are scoped to the block following it. with ({num: i}) { setTimeout(function() { alert(num); }, 10); }} The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared within the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a let block syntax introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/61552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811/" ] }
61,559
How much less libraries are there for Mono than for Java? I lack the overview over both alternatives but I have pretty much freedom of choice for my next project. I'm looking for hard technical facts in the areas of performance (for example, I'm told Java is good for threading, and I hear the runtime code optimization has become very good recently for .NET) real world portability (it's both meant to be portable, what's Catch-22 for each?) tool availability ( CI , build automation, debugging, IDE) I am especially looking for what you actually experienced in your own work rather than the things I could google. My application would be a back-end service processing large amounts of data from time series. My main target platform would be Linux. Edit: To phrase my question more adequately, I am interested in the whole package (3rd party libraries etc.), not just the language. For libraries, that probably boils down to the question "how much less libraries are there for Mono than for Java"? FYI, I have since chosen Java for this project, because it seemed just more battle-worn on the portability side and it's been around for a while on older systems, too. I'm a tiny little bit sad about it, because I'm very curious about C# and I'd love to have done some large project in it, but maybe next time. Thanks for all the advice.
Well....Java is actually more portable. Mono isn't implemented everywhere, and it lags behind the Microsoft implementation significantly. The Java SDK seems to stay in better sync across platforms (and it works on more platforms). I'd also say Java has more tool availability across all those platforms, although there are plenty of tools available for .NET on Windows platforms. Update for 2014 I still hold this opinion in 2014. However, I'll qualify this by saying I'm just now starting to pay some attention to Mono after a long while of not really caring, so there may be improvements in the Mono runtime (or ecosystem) that I haven't been made aware of. AFAIK, there is still no support for WPF, WCF, WF, of WIF. Mono can run on iOS, but to my knowledge, the Java runtime still runs on far more platforms than Mono. Also, Mono is starting to see some much improved tooling (Xamarin), and Microsoft seems to have a much more cross-platform kind of attitude and willingness to work with partners to make them complimentary, rather than competitive (for example, Mono will be a pretty important part of the upcoming OWIN/Helios ASP.NET landscape). I suspect that in the coming years the differences in portability will lessen rapidly, especially after .NET being open-sourced. Update for 2018 My view on this is starting to go the other way. I think .NET, broadly, particularly with .NET Core, has started to achieve "portability parity" with Java. There are efforts underway to bring WPF to .NET Core for some platforms, and .NET Core itself runs on a great many platforms now. Mono (owned by Xamarin, which is now owned by Microsoft) is a more mature and polished product than ever, and writing applications that work on multiple platforms is no longer the domain of deep gnosis of .NET hackery, but is a relatively straightforward endeavor. There are, of course, libraries and services and applications that are Windows-only or can only target specific platforms - but the same can be said of Java (broadly). If I were in the OP's shoes at this point, I can think of no reason inherent in the languages or tech stacks themselves that would prevent me from choosing .NET for any application going forward from this point.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ] }
61,605
In python, you can have a function return multiple values. Here's a contrived example: def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also"). When should you draw the line and define a different method?
Absolutely (for the example you provided). Tuples are first class citizens in Python There is a builtin function divmod() that does exactly that. q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x There are other examples: zip , enumerate , dict.items . for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e)# reverse keys and values in a dictionaryd = dict((v, k) for k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys())) BTW, parentheses are not necessary most of the time.Citation from Python Library Reference : Tuples may be constructed in a number of ways: Using a pair of parentheses to denote the empty tuple: () Using a trailing comma for a singleton tuple: a, or (a,) Separating items with commas: a, b, c or (a, b, c) Using the tuple() built-in: tuple() or tuple(iterable) Functions should serve single purpose Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp). Sometimes it is sufficient to return (x, y) instead of Point(x, y) . Named tuples With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples. >>> import collections>>> Point = collections.namedtuple('Point', 'x y')>>> x, y = Point(0, 1)>>> p = Point(x, y)>>> x, y, p(0, 1, Point(x=0, y=1))>>> p.x, p.y, p[0], p[1](0, 1, 0, 1)>>> for i in p:... print(i)...01
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/61605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
61,615
C# and Java allow almost any character in class names, method names, local variables, etc.. Is it bad practice to use non-ASCII characters, testing the boundaries of poor editors and analysis tools and making it difficult for some people to read, or is American arrogance the only argument against?
I would stick to english, simply because you usually never know who is working on that code, and because some third-party tools used in the build/testing/bugtracking progress may have problems. Typing äöüß on a Non-German Keyboard is simply a PITA, and I simply believe that anyone involved in software development should speak english, but maybe that's just my arrogance as a non-native-english speaker. What you call "American arrogance" is not whether or not your program uses international variable names, it's when your program thinks "Währung" and "Wahrung" are the same words.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926/" ] }
61,622
Has anyone been able to get an NHibernate-based project up and running on a shared web host? NHibernate does a whole lot of fancy stuff with reflection behind the scenes but the host that I'm using at the moment only allows applications to run in medium trust, which limits what you can do with reflection, and it's throwing up all sorts of security permission errors. This is the case even though I'm only using public properties in my mapping files, though I do have some classes defined as proxies. Which companies offer decent (and reasonably priced) web hosting that allows NHibernate to run without complaining? Update: It seems from these answers (and my experimentation -- sorry Ayende, but I still can't get it to work on my web host even after going through the article you linked to) is to choose your hosting provider wisely and shop around. It seems that WebHost4Life are pretty good in this respect. However, has anyone tried NHibernate with Windows shared hosting with 1and1? I have a Linux account with them already and I'm fairly satisfied on that front, and if I could get NHibernate to work seamlessly with Windows I'd probably stick with them.
I have had no issues with running NHibernate based apps on WebHost4Life, although I don't like them. Getting NHibernate to run on medium trust is possible. A full description on how this can be done is found here: http://blechie.com/WPierce/archive/2008/02/17/Lazy-Loading-with-nHibernate-Under-Medium-Trust.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886/" ] }
61,669
How do I use the profiler in Visual Studio 2008? I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item). Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?
Microsoft has released stand-alone Profiler for VS 2008 here
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ] }
61,680
I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha). I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class? Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800). Thanks!
You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See C++ FAQ Lite for an example of using a "2D" heap array. int *array = new int[800*800]; (Don't forget to delete[] it when you're done.)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ] }
61,733
Which of the following is better code in c# and why? ((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString() or DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString() Ultimately, is it better to cast or to parse?
If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/61733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246/" ] }
61,747
How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.
I had to install the PDO_PGSQL driver recently on Leopard, and I ran across a multitude of problems. In my search for answers, I stumbled across this question. Now I have it successfully installed, and so, even though this question is quite old, I hope that what I've found can help others (like myself) who will undoubtedly run into similar problems. The first thing you'll need to do is install PEAR , if you haven't done so already, since it doesn't come installed on Leopard by default. Once you do that, use the PECL installer to download the PDO_PGSQL package: $ pecl download pdo_pgsql$ tar xzf PDO_PGSQL-1.0.2.tgz (Note: you may have to run pecl as the superuser, i.e. sudo pecl .) After that, since the PECL installer can't install the extension directly, you'll need to build and install it yourself: $ cd PDO_PGSQL-1.0.2$ phpize$ ./configure --with-pdo-pgsql=/path/to/your/PostgreSQL/installation$ make && sudo make install If all goes well, you should have a file called " pdo_pgsql.so " sitting in a directory that should look something like " /usr/lib/php/extensions/no-debug-non-zts-20060613/ " (the PECL installation should have outputted the directory it installed the extension to). To finalize the installation, you'll need to edit your php.ini file. Find the section labeled "Dynamic Extensions", and underneath the list of (probably commented out) extensions, add this line: extension=pdo_pgsql.so Now, assuming this is the first time you've installed PHP extensions, there are two additional steps you need to take in order to get this working. First, in php.ini , find the extension_dir directive (under "Paths and Directories"), and change it to the directory that the pdo_pgsql.so file was installed in. For example, my extension_dir directive looks like: extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20060613" The second step, if you're on a 64-bit Intel Mac, involves making Apache run in 32-bit mode. (If there's a better strategy, I'd like to know, but for now, this is the best I could find.) In order to do this, edit the property list file located at /System/Library/LaunchDaemons/org.apache.httpd.plist . Find these two lines: <key>ProgramArguments</key><array> Under them, add these three lines: <string>arch</string><string>-arch</string><string>i386</string> Now, just restart Apache, and PDO_PGSQL will be up and running.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/61747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6371/" ] }
61,817
I am wondering what the best way to obtain the current domain is in ASP.NET? For instance: http://www.domainname.com/subdir/ should yield http://www.domainname.com http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.
Same answer as MattMitchell's but with some modification.This checks for the default port instead. Edit: Updated syntax and using Request.Url.Authority as suggested $"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}"
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/61817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ] }