Thursday, April 7, 2011

Difficulty removing all components from a Jpanel

G'day all,

I am coding a main menu for a project. The menu displays properly. I have also set up ActionListeners for the three buttons on the menu.

What I wish to do is reuse the JPanel for a new set of radio buttons when the user chooses "Start a New Game".

However, coding ActionPerformed to remove the existing components from the JPanel has me stumped. I know removeAll is somehow important, but unfortunately NetBeans informs me I cannot call it on my mainMenu JPanel object within ActionPerformed. So i have commented it out in my code below, but left it in so you can see what I am trying to do.

Your thoughts or hints are appreciated.

Here is my main code:

public class Main {

    public static void main(String[] args) {
        MainMenu menu = new MainMenu();
        menu.pack();
        menu.setVisible(true);
    }
}

Here is my mainMenu code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

    public class MainMenu extends JFrame implements ActionListener {
        JButton startNewGame = new JButton("Start a New Game");
        JButton loadOldGame = new JButton("Load an Old Game");
        JButton seeInstructions = new JButton("Instructions");

        public MainMenu() {
            super("RPG Main Menu");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel mainMenu = new JPanel();
            mainMenu.setLayout(new FlowLayout());
            startNewGame.setMnemonic('n');
            loadOldGame.setMnemonic('l');
            seeInstructions.setMnemonic('i');
            startNewGame.addActionListener(this);
            loadOldGame.addActionListener(this);
            seeInstructions.addActionListener(this);
            mainMenu.add(startNewGame);
            mainMenu.add(loadOldGame);
            mainMenu.add(seeInstructions);
            setContentPane(mainMenu);

        }

        public void actionPerformed(ActionEvent evt) {
            Object source = evt.getSource();
            if (source == startNewGame) {
                // StartNewGame code goes here
                // mainMenu.removeAll();
            }
            if (source == loadOldGame) {
                // LoadOldGame code goes here
            }
            if (source == seeInstructions) {
                // Quit code goes here
            }
        }
    }
From stackoverflow
  • You don't have a reference to mainMenu actionPerformed use. If you declare mainMenu with the buttons. It would work.

  • You need mainMenu to be a member variable:

     public class MainMenu extends JFrame implements ActionListener {
            JButton startNewGame = new JButton("Start a New Game");
            JButton loadOldGame = new JButton("Load an Old Game");
            JButton seeInstructions = new JButton("Instructions");
            JPanel mainMenu = new JPanel();
    

    Why do you feel the need to re-use this object?

  • The problem is that the actionPerformed method is trying to call the JPanel mainMenu which is out of scope, i.e. the mainMenu variable is not visible from the actionPerformed method.

    One way to get around this is to have the JPanel mainMenu declaration in the class itself and make it an instance field which is accessible to all instance methods of the class.

    For example:

    public class MainMenu extends JFrame implements ActionListener
    {
        ...
        JPanel mainMenu;
    
        public MainMenu()
        {
            ...
            mainMenu = new JPanel();
            ...
        }
    
        public void actionPerformed(ActionEvent e)
        {
            ...
            mainMenu.removeAll();
        }
    }
    
  • Consider using a CardLayout instead, which manages two or more components (usually JPanel instances) that share the same display space. That way you don't have to fiddle with adding and removing components at runtime.

    elwynn : Thanks Zach. I will consider CardLayout.
  • Avoid attempting to "reuse" stuff. Computers are quite capable of tidying up. Concentrate on making you code clear.

    So instead of attempting to tidy up the panel, simply replace it with a new one.

    Generally a better way to write listeners is as anonymous inner classes. Code within these will have access to final variables in the enclosing scope and to members of the enclosing class. So, if you make mainMenu final and you ActionListeners anonymous inner classes, your code should at least compile.

    Also don't attempt to "reuse" classes. Try to make each class do one sensible thing, and avoid inheritance (of implementation). There is almost never any need to extend JFrame, so don't do that. Create an ActionListener for each action, rather than attempting to determine the event source.

    Also note, you should always use Swing components on the AWT Event Dispatch Thread. Change the main method to add boilerplate something like:

    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
            runEDT();
        }});
    }
    

scripty (scriptaculous) draggable onEnd not executing in Safari

hey all,

i've created a very iphone-y slider element that is both restricted in overall movement horizontally (0-400px and it does not move vertically) and "snaps" to either side of the 400px "container" when it has passed the 200px mark and the drag has ended. It works perfect in firefox. In Safari, the onEnd function that positions the element to either end of this 400px container, is never called. Whats more, the draggable element "sticks" to the mouse cursor and i have to reload the page to end the animation.

Here's my code

<div style="width:100px;height: 60px;background-color:#000;z-index:999" id="dragtest" />
<script language="JavaScript" type="text/javascript">
new Draggable('dragtest', { constraint: 'horizontal',
 onEnd: function(e, me) {
  console.debug("!!!")
  element = e.element
  x = element.style.left
  x = x.gsub('px','')

  if (x >= 200) {
   $('dragtest').style.left = 400+'px';

  }

  if (x < 200) {
   $('dragtest').style.left = 0+'px';
  }

  console.debug("Snapping to ", element.style.left, " (x was ", x, ")")
  return true;

    },
 snap: function(x, y) {
  ret_x = x
  ret_y = y

  if (x >= 400) {
   ret_x = 400
  }

  if (x <= 0) {
   ret_x = 0
  }

  return [ret_x,ret_y]

 }
});
</script>

thanks! andrew

From stackoverflow
  • For your future reference (couldnt google anything out of this), uncommenting console.debug() calls from within the onEnd handler resolved this. Weird.

    Cory R. King : Do you mean commenting out console.debug()? If you use firebug, go to their website and make sure to use their stub file which defines functions like "console.debug()" so browsers /w-out firebug don't blow up.
    pgn : Thanks, i did have firebug-lite loaded though..

Java newbie: inheritance and where to declare an intended universal object

G'day all, I have a Player class, which inherits from an ArmedHumanoids class, which inherits in turn from a Humanoids class.

Where and when should I create the Player object so that it is accessible in all my other classes - for example, a selectPlayerRace class?

I know that by extending the Player class it becomes accessible, but I am thwarted because all my other classes extend JFrame. There can be only one extension, not two.

At the moment the NetBeansIDE complains that it cannot locate the Player object when I code for it in selectPlayerRace, after creating the Player object in my Main class.

Obviously, it is happier when I create the Player object in the selectPlayerRace class, but then I can't access the Player object in all my other classes as it is internal to selectPlayerRace.

The Player object is intended to be a universal object accessible in all my other classes. I'm sorry for this dreadfully newbieish question, but I can't figure it out.

From stackoverflow
  • It sounds like you are looking for a static declaration here. As I understand it you want to get a global access to some instance of Player but would not need to extend some other class or implement some interface to do so (which means you don't have to inherit any behaviour, you just want access to one object). You could store the Player instance you want to access static e.g. in a PlayerManagement class. You then put a static method in it like getPlayer(String playerName) which synchronizes access to its array/Vector/whatever containing all Player objects and then returns the object in question (or null if not found). You can link your humanoid-classes into PlayerManagement and vice versa.

    Maybe you also want a Player interface. You can implement as many interfaces as you like but only extend one other class but you have to reimplement all functionality since you cannot write any code into an interface, just define what attributes/methods a class implementing that interface must provide.

    Energiequant : Oooookay?! Any comment why this has been down-voted? I don't get it?
  • You can create a object of your Player class and pass it to the other objects via e.g. constructor or method which accepts Player type.

    public class Entry
    {
       public static void main(string[] args)
       {
          // initialize a player object
          Player player=new Player("elwynn");
          // initialize some other object which requires player object.
          // since player object needs to be accessed within foo.
          Foo foo = new Foo(player);
          // you are about to use player object within foo.
          foo.MakePlayerPlay(); 
       } 
    } 
    
    public class Foo
    {
    
      Player player;
      public Foo(Player p)
      {
       this.player = p;
      }
    
      public void MakePlayerPlay()
      {
        // you are using player object here
        // which is the same instance you created 
        // within main() in Entry class.
        if(this.player!=null) this.player.play();
      }
    
    }
    
  • It is bad style to have global objects, because this

    • will make testing more difficult, and

    • will cause problems when there arises a need to have more than one instances.

    It is better to give references to other objects on construction (this is called dependency injection) on a need-to-know basis, or where appropriate to pass references by parameter.

    That said, look up the Singleton design pattern.

    Tom Hawtin - tackline : Look up the singleton antipattern, and make a note never to use it.
  • The Player object is intended to be a universal object accessible in all my other classes.

    Why not just pass this Player object in the constructor of the other classes, or in the methods that you call?

  • This sounds like a singleton pattern.

    public class Player extends ArmedHumanoid {
    
      private static Player instance = new Player();
    
      private Player() {}
    
      public static Player getIntstance() {
        return instance
      }
    
    }
    

    Then any class can call Player.getInstance() to get access to the Player object.

    elwynn : That is exactly the solution I needed. It works perfectly in my code. For example, I can call Player.getInstance.classType = "Mage" in the selectClassType class. Thank you so much for solving this problem for me.

A WCF service behind a firewall generates a wrong wsdl URI

Hi, I developed a WCF service and i have published it with IIS. All goes well inside the local network but when the service is accessed by an external client from the internet, redirected by a firewall, the service generates a local wsdl uri that cannot be solve by the client.

Something like this:

  • URI needed: http://external_url/service.svc?wsdl
  • URI created: http://internal_url/service.svc?wsdl

I would like to continue using the automatic generation of the wsdl file without indicating an external path. I also have prove manipulating the ServiceBehavior attribute into the service class but the problem persists.

How can I do it?

From stackoverflow

REXML preserve attributes order

I try to generate such XML using REXML

<root>
  <add key='foo' value='bar'/>
</root>

But what I get is (notice that key/value order)

<root>
  <add value='bar' key='foo'/>
</root>

Code:

require 'rexml/document'
include REXML

doc = Document.new
doc.add_element('root')
el = doc.root.add_element('add')
el.add_attribute('key', 'foo')
el.add_attribute('value', 'bar')
puts doc

It does not matter if I write:

el.add_attribute('key', 'foo')
el.add_attribute('value', 'bar')

or

el.add_attribute('value', 'bar')
el.add_attribute('key', 'foo')

result is the same. Looks like REXML uses some dictionary to keep the attributes...

Can I enforce the desired order: key/value?

From stackoverflow
  • In XML, it doesn't matter what order the attributes are in. If you have some piece of XML processing code where it does matter, then I would suggest that code was buggy.

    From the XML spec here, note the phrase: "Note that the order of attribute specifications in a start-tag or empty-element tag is not significant".

    In answer to your specific question on whether you can enforce a certain order, I don't believe so. I've never actually tried to do it (since it's unnecessary) but it seems unlikely the REXML people would waste time implementing such a non-feature :-). Since the key/value pairs are stored as a hash, their order is likely to be random (as far as you could tell from the alphabetic sequence of the keys).

    Of course, since Ruby comes with the source code for REXML, you could (if desperate) replace or augment the included copy with your own version (REXML2 ?).

    Since you're doing a simple puts, it's probably using the pretty formatter so check the start of the write_element code in src/rexml/formatters/pretty.rb where it performs the "node.attributes.each_attribute do |attr|" - you may find it's as simple as sorting that list before processing the elements.

    You may also want to suggest to the developers (see here for the mailing list or here for bug reports and enhancement requests) that they make this an option in a future release but, if I were them, I'd simply say it was unnecessary.

    alex2k8 : Sure, the order does not matter from machine perspective. I need it for readability only. Actually I have to modify config file, and whould like to preserve formatting as much as possible.
    paxdiablo : See updates on possible approaches (basically either forking for local use or trying to convince developers to add this feature).
  • If you're modifying a config file and formatting is important, then it might be easier to read it in via REXML but modify via regexps.

    Also, keep in mind that generating a lot of XML via REXML is incredibly slow. I had a site that had to both read and write a lot of XML; I found that for reading, REXML was fast enough, but for writing I had to use libxml. And actually, libxml was such a bear to install and the ruby libraries for it so immature, that I ended up using erb to just replace certain parts of already-written XML docs.

    Good luck!

MySQL Great Circle Distance (Haversine formula)

Hello All, I've got a PHP script that gets Longitude and Latitude values...then inputs them into a MySQL query. I'd really like to make it solely MySQL.

Live site can be found at http://MotoListr.com

Here's my current PHP Code:

if ($distance != "Any" && $customer_zip != "") { //get the great circle distance

    //get the origin zip code info
    $zip_sql = "SELECT * FROM zip_code WHERE zip_code = '$customer_zip'";
    $result = mysql_query($zip_sql);
    $row = mysql_fetch_array($result);
    $origin_lat = $row['lat'];
    $origin_lon = $row['lon'];

    //get the range
    $lat_range = $distance/69.172;
    $lon_range = abs($distance/(cos($details[0]) * 69.172));
    $min_lat = number_format($origin_lat - $lat_range, "4", ".", "");
    $max_lat = number_format($origin_lat + $lat_range, "4", ".", "");
    $min_lon = number_format($origin_lon - $lon_range, "4", ".", "");
    $max_lon = number_format($origin_lon + $lon_range, "4", ".", "");
    $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon' AND ";
    }

Does anyone know how to make this entirely MySQL? I've browsed the internet a bit but most of the literature on it is pretty confusing.

Best, Nick

From stackoverflow
  • From Google Code FAQ - Creating a Store Locator with PHP, MySQL & Google Maps:

    Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.

    SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
    FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
    
  • $greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

    with latitude and longitude in radian.

    so

    SELECT 
      acos( 
          cos(radians( $latitude0 ))
        * cos(radians( $latitude1 ))
        * cos(radians( $longitude0 ) - radians( $longitude1 ))
        + sin(radians( $latitude0 )) 
        * sin(radians( $latitude1 ))
      ) AS greatCircleDistance 
     FROM yourTable;
    

    is your sequel query

    to get your results in Km or miles, multiply the result with the mean radius of Earth (3959 miles, 6371 Km or 3440 nautical miles)

    The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.

    SELECT 
      id
    FROM spatialEnabledTable
    WHERE 
      MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))
    
  • Using the above formula I am getting big difference in distance ... The distance using maps.google.com is ~1500 but using this formula its 1240.. Can anybody tell why is this ?

    Thanks

    Pavel Chuchuva : Please ask a separate question. You can put link to your question here, as comment to the answer.

Why does Consolas in Visual Studio look bold?

I have tried installing the Consolas font pack so that I can use it with VS 2005. For some reason it looks a lot bolder than Wikipedia's and Jeff Atwood's examples. I read something about anti-aliasing and I am trying that now. Any ideas on how to get it too look thin and sleak?

EDIT: Sorry found out. It has something to do with ClearType fonts. Turning it on sorted out all my problems.

From stackoverflow
  • Did you make sure you have ClearType activated?

  • It looks bolder when your Windows OS (XP?) has Font smoothing turned on.

    Right click your Desktop > Properties > Appearance tab > Effects > "Use the following method to smoothe screen fonts".

    Try changing it to ClearType / Standard / Turn it off. Keep switching back to VS and scroll up/down a bit to see the effect.

  • You can turn on the clearType by running through the wizard from MS website below,

    http://www.microsoft.com/typography/cleartype/tuner/step1.aspx

Storing and retrieving session variables in Reporting Services 2008

Is there a way to set session variables during login that are then available to reports?

We have a reporting services server where we move and denormalize data from our transaction system for reporting purposes. In order to allow our users to login with the same user name and password from the transactional system we have set up custom forms authentication and after much trial and error it is finally working. In addition we have the authorization accessing our transactional system so that any changes in user authority is immediately reflected in Reporting Services.

Our problem now is that we would like to add some additional features such as locking down parameters depending on user authority/groups in our transactional system. We have found a way to do it but it's inefficient, basically we have stored procedures that will query our transactional system to check for access. The problem is that these queries will often be run for every report request even though the answer is unlikely to change. It would be nice to have access to session level data that can be set once during log in and then accessed from the reports.

From stackoverflow
  • There are no direct access from SSRS to session. My suggestions:

    1. create table in database to host all authority/group related information, pass userID as a parameter into stored procedure. Issue - to trigger changes in this table.
    2. use ASP.NET as a wrapper for SSRS, so there will be no troubles with session variables. Starting with SQL Reporting Services in ASP.NET Application
  • Using reflection, you can get access to the HTTPContext of the running job, from where you can possibly get the Session object (depending on your set-up). We've had to use this method for a slightly different scenario related to security: if you have a report that uses multiple datasets, only the first one gets the proper user context. This hack allows you to get the HTTPContext yourself (which we use in a custom data layer).

    Excerpt from MSDN forum article here :

    using System.Reflection;
    using Microsoft.ReportingServices.Diagnostics;
    
    // This is declared outside of a method body for improved performance,
    // since this reflection bit only needs to run once
    
    private static FieldInfo contextField = 
      typeof(RunningJobContext).GetField("m_optionalWebCtx", 
                       BindingFlags.Instance | BindingFlags.NonPublic);
    
    // Call this in your method
    HttpContext context = (HttpContext)contextField.GetValue(Globals.JobContext);
    
  • You definitely have a lot more flexibility moving the access into an asp.net site and using the reportviewer control.

    Make sure you have the same version of the control on both your dev machine and on the IIS machine, Version 9.0.0.0 for VS 2008.

    You then have to get the permissions / access between IIS and the reporting server setup but that is not too hard.

    At that point you have more control for setting, hiding and controlling all the parameters or providing your own parameter controls.

Javascript - check if method prototype has been changed?

What's the best method to check if the protoype of a method has been changed?

From stackoverflow
  • It depends on what you mean by "changed" if you mean changed between when your code gets loaded and some later time, you can just store a reference to the function, a la

    var oldFunc = SomeType.prototype.someFunction;
    ...
    if (oldFunc === someInstance.someFunction) // unchanged, note the use of strict equality
    

    But if you mean changed from the default native implementation there's no real way to tell.

    Geuis : So some libraries like Prototype modify the core object prototypes, like Array.prototype.push or pop. So I'm wondering how you can check if the default prototype method for a native object has been changed.
  • If you do a toString() on a function you get the source code of the function. For native functions, FF, IE, Opera and Chrome returns a function with the body [native code]. However, Chrome has most functions implemented in javascript and will return the source for most functions (Object.constructor is one of the few native functions in Chrome that does return [native code])

    Below you find a function with a regexp that checks for [native code]. (there is no need to call toString() since it is done automatically when the function isn't called). It is tested with FF3, IE7, Opera 9.6 and Chrome 1. But as I said, since Chrome does return the real source code for most functions it isn't useful to test it in that browser.

    function isNative(func) {
        return /^\s*function[^{]+{\s*\[native code\]\s*}\s*$/.test(func);
    }
    
    
    alert(isNative(Array.prototype.push));
    

    Update

    The above code will of course not detect if a native method is replaced with some other native method, like Array.prototype.push = Math.abs. If you want to detect that kind of change, or if methods of your own objects are changed, you must store the original method in a variable, then run the function that you suspect changes it, followed by a compare with the stored methods.

    However, after reading the comment from the op on olliej answer, it is quite clear that the OP wanted to know how to detect if methods on the native objects has been changed. If they are changed they are usually not replaced with another native function but with some new code, usually to add methods that the browser don't have natively, or to change the behavior to be compatible with the expected standard. In that case the code above will work in FF, IE and Opera but not Crome.

    If you want to detect any type of changes of the methods the following code might be of use. The following function creates an object with two methods: save and compare. save is automatically called if arguments is supplied when the object is created. save expects two or more arguments where the first is the object and the rest is the method names to be saved. The reason you must supply the names of the methods is because most internal objects has the "do not enumerate"-flag set on the methods.

    function Cmpobj() {
        if (this.constructor !== arguments.callee){
            throw SyntaxError("Constructor called as function");
        }
        var srcobj, methods=[];
        this.save=function(obj) {
            var undef; //Local undefined
            srcobj=obj;
            for (var i=arguments.length -1; i>0; --i) {
                var name = arguments[i];
                //Push an object on the array without using push
                methods[methods.length] = {
                    name:name,
                    func:typeof obj[name] === "function" ? obj[name]:undef
                };
            }
        }
        this.compare=function(obj) {
            var changed=[];
            obj = obj || srcobj;
            for (var i=methods.length-1; i>=0; --i) {
                if (methods[i].func !== obj[methods[i].name]) {
                    changed[changed.length]=methods[i].name;
                }
            }
            return changed;
        }
        if (arguments.length) this.save.apply(this,arguments);
    }
    
    // Creating a compare object. The first parameter is the object,
    // followed by up to 254 method names.    
    var saved = new Cmpobj(Array.prototype,"pop","push","slice");
    
    //Do some change
    Array.prototype.pop = Array.prototype.push;
    
    // Compare if something is changed    
    alert(saved.compare().join(", "));
    
    olliej : This doesn't work if you do `Array.push = Math.abs` that's why i didn't suggest it in my answer.
    some : @olliej: That was implied, but I have updated the answer anyway.

CUDA + Visual Studio = suppressed output window

Normally, when I use Visual Studio to do a build, I see warnings and errors shown in the output pane, e.g.

1>------ Build started: Project: pdcuda, Configuration: Release x64 ------
Compiling...
foo.cpp
Linking...
foo.obj : error LNK2001: unresolved external symbol "foo"
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I'm doing some GPU programming with CUDA. Upon upgrading to 2.1, I no longer get any useful output in Visual Studio. For example, all I now see is:

1>------ Build started: Project: pdcuda, Configuration: Release x64 ------
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The other details can be found in BuildLog.htm, but it's inconvenient to hunt that file down all the time.

Does anyone know how to force Visual Studio to show the output in its output pane?

Things that don't help:

  • uninstalling CUDA: the problem persists in all projects
  • Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity: changing this pulldown, even to "Diagnostic" has no discernable effect.

EDIT: Additional things that don't help:

  • devenv.exe /resetsettings
  • devenv.exe /resetuserdata

UPDATE (in response to Die in Sente): It's now working on one of the two machines (I'm not sure what I did to fix it though). The machine that's still having problems has a CUDA Visual Studio Wizard installed that has caused similar problems before. The still-broken machine had version 15.00.21022.8 of the compiler. The working machine has 15.00.30729.1. After making a backup, I transferred "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64" from the working to the broken machine. I observe no changes in behavior on the broken machine.

From stackoverflow
  • did you tried to reset IDE devenv.exe /resetsettings or devenv.exe /resetuserdata

    Mr Fooz : good ideas...unfortunately they don't fix it either.
  • It is compler and linker errors that you're not seeing? Or some other tool in the build?

    How has the format of the error messages changed? IIRC, Visual Studio is just scanning the build log for the strings "error" and "warning". Maybe the syntax of the errors has changed enough to defeat the parser?

    Does the CUDA SDK install replace or patch any compiler modules? You can check this by running "cl -Bv".

    Mr Fooz : I'm missing output from all tools (compiler, linker, custom build steps, etc.). I see exactly one line per project that's built plus a single line summarizing what was built / skipped / failed / etc.
    Mr Fooz : If I hunt down the correct BuildLog.htm files, the formatting there is unchanged. Normally, the output window has the warnings and errors streamed to it. BuildLog.htm is untouched until a project's built is done, then it's dumped all at once.
    Mr Fooz : I don't think that the SDK patches the compiler modules, but I did find an older version on the broken machine (see the update in the OP). Copying the bin directory from a working machine doesn't seem to help.
  • I also recently install CUDA 2.1 (on top of 2.0 I believe). The default installation for CUDA 2.1 moved the SDK from

    C:\Program Files\NVIDIA Corporation\NVIDIA CUDA SDK\

    to

    C:\Documents and Settings\All Users\Application Data\NVIDIA Corportation\NVIDIA CUDA SDK\

    which initially caused me some problems. Are all of your paths resolving correctly?

    Mr Fooz : I've able to resolve the paths correctly. Oddly, it's installed in the hidden directory tree C:\ProgramData for me. When I fix the bugs and linker issues in my program, I can get it to build. I just don't see any build messages like nvcc results, warnings, errors, etc.
    Zachary Garrett : I thought perhaps Visual Studio was having trouble locating nvcc and not being descriptive about it. The BuildLog.htm contains all the errors that normally would be displayed in the output? What does your .cu build rule look like?
    Mr Fooz : Yes, the BuildLog.htm contains all the errors and warnings that would have normally been displayed. If I fix the errors, the build works (but the IDE output is still suppressed). The build rule shows up as "CUDA Build Rule v2.1.0". Its command line contains nothing surprising.
  • This might sound like a far out suggestion. Get the CUDA SDK and try your code with the sample CUDA-C++ project in there. Maybe something changed in the build rules for CUDA v2.1.

    Mr Fooz : Good idea. Unfortunately, running the cppIntegration sample does not restore the IDE output.
  • Hey,

    how do u get this colored red errors in the output window of studio ? Is it a new feature or tool ? Im using VS2005 and i like to see this help with colors also in my output window, so i better can recognize errors if they are red ?

    Can anybody tell me, because i know how to set the color of the output window in studio->options ... at all, but not the red warning and error numbers. Would be great if anyone can help me thx

    ben

    Mr Fooz : AFAIK, there is no coloring of errors in the output window. It's just mildly-hyperlinked text. The color coding you see above is done by stackoverflow.
  • If you go to Tools->Options->Projects and Solutions->Build and Run. Last property is "MSBuild Project build output verbosity". It defaults to Minimal, change it to normal and the build messages will show up in Output window.

    This also enables any <Message Text="test message"></Message> output to show up in Visual Studio Build Output Window.

  • I have exactly the same problem, but without CUDA. Today Visual Studio just decided it wasn't going to show any build messages anymore. It was working fine, then one of my builds it just stopped working. The problem persists over all my projects now, and persists over reboots. I also see the correct messages in buildlog.htm. This is ridonkulous!

    EDIT: Ooh, I used the add/remove programs to do a repair, and now it works again! Yeah!

  • Final solution: reinstall the OS.

How does this not cause a stack overflow?

I'm looking at the source code for a server using SocketAsyncEventArgs, and I'm trying to figure out how this wouldn't cause a stack overflow:

So this code is called to allow the socket to accept an incoming connection (scroll down to the bottom to see what I mean):

/// <summary>
/// Begins an operation to accept a connection request from the client.
/// </summary>
/// <param name="acceptEventArg">The context object to use when issuing 
/// the accept operation on the server's listening socket.</param>
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
    if (acceptEventArg == null)
    {
        acceptEventArg = new SocketAsyncEventArgs();
        acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
    }
    else
    {
        // Socket must be cleared since the context object is being reused.
        acceptEventArg.AcceptSocket = null;
    }

    this.semaphoreAcceptedClients.WaitOne();
    Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg);
    if (!willRaiseEvent)
    {
        this.ProcessAccept(acceptEventArg);
    }
}

Then this code gets called once a connection is actually accepted (see last line):

  /// <summary>
        /// Process the accept for the socket listener.
        /// </summary>
        /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0)
            {
                Interlocked.Increment(ref this.numConnectedSockets);
                Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",
                    this.numConnectedSockets);
            }

            // Get the socket for the accepted client connection and put it into the 
            // ReadEventArg object user token.
            SocketAsyncEventArgs readEventArgs = this.readWritePool.Pop();
            readEventArgs.UserToken = e.AcceptSocket;

            // As soon as the client is connected, post a receive to the connection.
            Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs);
            if (!willRaiseEvent)
            {
                this.ProcessReceive(readEventArgs);
            }

            // Accept the next connection request.
            this.StartAccept(e); // <==== tail end recursive?
        }

Look at the last line. It calls the top function again. How does this not overflow the stack by ping-ponging back and forth between these 2 functions? It seems to be tail end recursion, but this isn't Haskell so I don't see how this would work.

It was my understanding that these weren't fired in threads but where just executed one at a time by the cpu.

From stackoverflow
  • Look at the code:

    if (!willRaiseEvent)
    {
        this.ProcessAccept(acceptEventArg);
    }
    

    Although I don't yet understand the whole mechanism, willRaiseEvent == true will clearly end the recursion, so I guess this happens so it's not endless recursion.

  • It all depends on the willCauseEvent flag, that when set to true breaks the recursion. That flag is probably set to true in case there's no connection pending.

  • Hard to determine from the context, but looks like the first only calls the second directly when

    Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg);    
    if (!willRaiseEvent)    
    {
    

    and thus I'm guessing most of the time it raises an event on completion (from a different callback thread)?

    (See also the 'stack dive' portion of

    http://blogs.msdn.com/mjm/archive/2005/05/04/414793.aspx

    which seems to be a similar kind of thing.)

  • ProcessAccept() always calls StartAccept() but the reverse is not true.

    In StartAccept(), ProcessAccept() is only called if willRaiseEvent is set to true. That's your exit from the infinite recursion right there.

    You always look for the possible exit points if you suspect infinite recursion (in either a single recursive function or one of your ping-pong ones, as you so eloquently put it :-).

  • If the AsyncAccept (or any AsyncXXX operation for that matter) cannot be satisfied immediately, then it will return true, indicating that the operation will complete asynchronously. When this happens, the callback-event will ultimately fire on a thread-pool thread. Even if it marshal's back to a UI thread (because it was initiated there), it will do so via a post.

    AsyncAccept is highly likely to return true, because unless there are socket connections truly pending (see backlog in Listen), you are waiting for a client to connect.

    Hence, StartAccept() will simply exit without calling ProcessAccept, and ProcessAccept when (and if) it fires, will probably be on a different thread.

Using C: How can I determine the sizes of the components of a floating point?

I am looking for suggestions on how to find the sizes (in bits) and range of floating point numbers in an architecture independent manner. The code could be built on various platforms (AIX, Linux, HPUX, VMS, maybe Windoze) using different flags - so results should vary. The sign, I've only seen as one bit, but how to measure the size of the exponent and mantissa?

From stackoverflow
  • Have a look at the values defined in float.h. Those should give you the values you need.

  • The number of bits used to store each field in a floating point number doesn't change.

                          Sign      Exponent   Fraction   Bias
    Single Precision    1 [31]     8 [30-23]      23 [22-00]         127
    Double Precision    1 [63]    11 [62-52]      52 [51-00]        1023
    

    EDIT: As Jonathan pointed out in the comments, I left out the long double type. I'll leave its bit decomposition as an exercise for the reader. :)

    Don Wakefield : Not true, for some values of true ;^)~ There exist a small number of platforms that do not use IEEE754. But for the most part you are of course correct.
    Jonathan Leffler : You missed out long double.
    Bill the Lizard : @Don: *Very* small values of true. :)
    Bill the Lizard : @Jonathan: Thanks, I edited my response. Long double was a pretty late addition to the standard, but it's worth at least a footnote.
  • Since you're looking at building for a number of systems, I think you may be looking at using GCC for compilation.

    Some good info on floating point - this is what almost all modern architectures use: http://en.wikipedia.org/wiki/IEEE_754

    This details some of the differences that can come up http://www.network-theory.co.uk/docs/gccintro/gccintro_70.html

  • As you follow the links suggested in previous comments, you'll probably see references to What Every Computer Scientist Should Know About Floating Point Arithmetic. By all means, take the time to read this paper. It pops up everywhere when floating point is discussed.

  • Its relatively easy to find out:

    Decimal or binary;

    myfloat a = 2.0, b = 0.0;

    for (int i=0; i<20; i++) b += 0.1;

    (a == b) => decimal, else binary

    Reason: All binary systems can represent 2.0, but any binary system will have an error term for representing 0.1. By accumulating you can be sure that this error term will not vanish like in rounding: e.g. 1.0 == 3.0*(1.0/3.0) even in binary systems

    Mantissa length:

    Myfloat a = 1.0, b = 1.0, c, inc = 1.0;

    int mantissabits = 0;

    do { mantissabits++; inc *= 0.5; // effectively shift to the right c = b+inc; } while (a != c);

    You are adding decreasing terms until you reach the capacity of the mantissa. It gives back 24 bits for float and 53 bits for double which is correct (The mantissa itself contains only 23/52 bits, but as the first bit is always one on normalized values, you have a hidden extra bit).

    Exponent length: Myfloat a = 1.0; int max = 0, min = 0;

    while (true) { a *= 2.0; if (a != NaN && a != Infinity && whatever) // depends on system max++; else break; }

    a = 1.0; while (true) { a *= 0.5; if (a != 0.0) min--; else break; }

    You are shifting 1.0 to the left or to the right until you hit the top or the bottom. Normally the exp range is -(max+1) - max. If min is smaller than -(max+1), you have (as floats and doubles have) subnormals. Normally positive and negative values are symmetric (with perhaps one offset), but you can adjust the test by adding negative values.

What is AppDomain?

What is an AppDomain? What are the benefits of AppDomains or why Microsoft brought the concept of AppDomains, what was the problem without AppDomains?

Please elaborate.

From stackoverflow
  • An AppDomain provides a layer of isolation within a process. Everything you usually think of as "per program" (static variables etc) is actually per-AppDomain. This is useful for:

    • plugins (you can unload an AppDomain, but not an assembly within an AppDomain)
    • security (you can run a set of code with specific trust levels)
    • isolation (you an run different versions of assemblies etc)

    The pain is you need to use remoting etc.

    See MSDN for lots more info. To be honest, it isn't something you need to mess with very often.

    rstevens : One little (but important) thing to mention: AppDomains do not cover threads.
  • AppDomains can be viewed as lightweight processes. They share many of the same characteristics of a process, e.g. they have their own copies of statics, assemblies and so forth, but they are contained within a single process. From the operating system's point of view a process is just a process no matter how many AppDomains it may contain.

    Unlike a process however, an AppDomain does not have any threads unless you explicitly create them. A thread can run code in any AppDomain.

    AppDomains are part of the same process and thus actually share the same managed heap. This is usually not an issue since the AppDomain programming model prevents implicit access between AppDomains. However, some references are actually shared between AppDomains such as type objects and interned strings.

  • Take a look at this - that might explain it:

    http://blog.flair-systems.com/2010/05/c-fastfood-what-appdomain.html

    When 10 users browse a page say (login.aspx) in a published website,
    

    ASP.Net Worker Process (w3wp.exe) creates 10 application domains to host the page assembly into it for each client, thus creates 10 appDomains.

    appDomain:
    
    assembly
    
    App_Web_Login.aspx.fdf7a39c.dll
    
    So, what’s the story?
    
    When run any application, the operating system hosts it in a process
    

    (p1) to be ran by the processor . and if the run another different application(OS hosts it into another process (p2)).if app1 wants to access an assembly (dll or exe) form app2, the accessing will be managed by OS which is slow.

    The another solution:-
    
    Host the assemblies you want into an application domain (which is a
    

    logical boundary you create to host many assemblies as you wish). the appDomain is managed by .net framework but process is managed by the operating system (which is slower)

    Operating system:
    
    Process1
    
    appDomain1
    
    assembly
    
    App_Web_Login.aspx.fdf7a39c.dll
    
    assembly
    
    DataAccessLayer.dll 
    
    appDomain2
    
    assembly
    
    App_Web_EmployeeData.aspx.fdf7a39c.dll
    

WPF Window Drag/Move Boundary

Hi everyone, just curious if you know of any way to setup a drag boundary for a window?

It would be nice to have these properties:

Me.MinLeft = 10
Me.MinTop = 10
Me.MaxLeft = 150
Me.MaxTop = 150

Those are made up properties, btw, which would be nice to have.

I know I could probably setup a timer to fire ever 10th of a second and check the left and top and then move it back if it's over. But it would be more elegant to have the window act like it hit a wall and can't go any farther, like moving to the edge of the screen or something similar.

Edit: There seems to be some confusion somewhere, the point I'm trying to make is in the paragraph above, dragging, not re-sizing.

From stackoverflow
  • There are dependency properties for WPF's Window for this purpose.

    Here they are:

    • Window.MaxWidth
    • Window.MaxHeight

    These properties will constrain the size of the Window, just like the WinForm's Form.

    ScottN : I'm speaking of dragging a window around the screen, not re-sizing it. Think of setting a region on the screen the window is only allowed to move round in, even though your screen is bigger. Like a drag container is best I can think of.
    ScottN : I'm sitting here reading this again and wondering if I asked the question wrong and how you could think I was speaking of window size and not dragging, I don't even mention the word "size" or "re-size" in my question...
    eriawan : Drag boundary? I think it's by default is draggable. Do you want drag handle like the ones in the Windows Forms?
    Drew Noakes : He wants to constraint the area within which a window can be dragged.
  • Maybe you could handle PreviewMouseMove (either the event or override the corresponding protected method) and set e.Handled = true whenever the mouse movement would cause the window to move outside the region you want to constrain it to.

    This seems like the most logical, WPF-like way of doing this.

  • Here is teh "magic" you need to create this functionality, all you have to do is set the Window_SourceInitialized method to the window's SourceInitialized event and insert you logic where the big comment is.

    I combined this code from several sources, so there could be some syntax errors in it.

    internal enum WM
    {
       WINDOWPOSCHANGING = 0x0046,
    }
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct WINDOWPOS
    {
       public IntPtr hwnd;
       public IntPtr hwndInsertAfter;
       public int x;
       public int y;
       public int cx;
       public int cy;
       public int flags;
    }
    
    private void Window_SourceInitialized(object sender, EventArgs ea)
    {
       HwndSource hwndSource = (HwndSource)HwndSource.FromVisual((Window)sender);
       hwndSource.AddHook(DragHook);
    }
    
    private static IntPtr DragHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
    {
       switch ((WM)msg)
       {
          case WM.WINDOWPOSCHANGING:
          {
              WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
              if ((pos.flags & (int)SWP.NOMOVE) != 0)
              {
                  return IntPtr.Zero;
              }
    
              Window wnd = (Window)HwndSource.FromHwnd(hwnd).RootVisual;
              if (wnd == null)
              {
                 return IntPtr.Zero;
              }
    
              bool changedPos = false;
    
              // ***********************
              // Here you check the values inside the pos structure
              // if you want to override tehm just change the pos
              // structure and set changedPos to true
              // ***********************
    
              if (!changedPos)
              {
                 return IntPtr.Zero;
              }
    
              Marshal.StructureToPtr(pos, lParam, true);
              handeled = true;
           }
           break;
       }
    
       return IntPtr.Zero;
    }
    
  • As I have no doubt that Nir's answer will work spending a little time implementing it, I was able to do what I wanted a little bit more elegant with this code:

    Private Sub myWindow_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged
    
        Dim primaryBounds As System.Drawing.Rectangle = Windows.Forms.Screen.PrimaryScreen.Bounds
        Dim windowBounds As System.Drawing.Rectangle = New System.Drawing.Rectangle(CInt(Me.Left), CInt(Me.Top), CInt(Me.Width), CInt(Me.Height))
    
        If (windowBounds.Left < 0) Then
            windowBounds = New System.Drawing.Rectangle(0, windowBounds.Top, windowBounds.Width, windowBounds.Height)
        ElseIf (windowBounds.Right > primaryBounds.Right) Then
            windowBounds = New System.Drawing.Rectangle(primaryBounds.Right - windowBounds.Width, windowBounds.Top, windowBounds.Width, windowBounds.Height)
        End If
    
        If (windowBounds.Top < 0) Then
            windowBounds = New System.Drawing.Rectangle(windowBounds.Left, 0, windowBounds.Width, windowBounds.Height)
        ElseIf (windowBounds.Bottom > primaryBounds.Bottom) Then
            windowBounds = New System.Drawing.Rectangle(windowBounds.Left, primaryBounds.Bottom - windowBounds.Height, windowBounds.Width, windowBounds.Height)
        End If
    
        Me.Left = windowBounds.Left
        Me.Top = windowBounds.Top
    
    End Sub
    

    This made the window being dragged stay within the primary screen (whole window), but you could easily change the bounds to whatever values you needed.

Common format for time zone in Java/J2me

We are developing a j2me app for syncing contacts to/from a server. we are storing the update and create time (long mill sec) with each contact for conflict resolution/sync calculations.

Now as the client and server app can be in different time zones , how one can store time with time zone in a standard format (to take care diff time zones and daylight savings) for calculations at client and server side.

From stackoverflow
  • I suggest you store all times in GMT+0 and convert the time only when you display it.

  • If you use System.currentTimeMillis() you don't have to worry about time zones, because it is in universal time. From System.currentTimeMillis() Javadoc:

    public static long currentTimeMillis()

    [...]

    Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

    The time zone UTC is Coordinated Universal Time, which is mostly GMT .

    starblue : Yes, time zones (including daylight savings time) are only taken into account for presenting dates to the user.

checkout svn+ssh with loginname

Hi
I want to checkout something out of an repository .. but wenn i type :

svn co svn+ssh://URL

i get asked for the password.I suppose he uses the username from my console which aren't the same.

So how can i checkout something with svn+ssh with a different loginname ?

From stackoverflow
  • Use --username:

    svn co --username fred svn+ssh://URL
    
  • SSH lets you select user in the connection URL:

    svn co svn+ssh://alabaster@URL
    

Maximum length of a valid email id

What is the maximum length of a valid email id

From stackoverflow
  • 320

    And the segments look like this

    {64}@{255}

    64 + 1 + 255 = 320

    You should also read this if you are validating emails

    http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

    Nathan : However according to this spec (for student loan data) http://www.nchelp.org/elibrary/ESC/CommonRecord-CommonLineDocumentation/CRC-Ver_1-3-0-PDF.pdf on page 20: "The e-mail length changed to reflect current ANSI standards. The E-mail address is a maximum length of 128 characters." Hmm.
    Nathan : Can you reference what RFC you got this from?
    Carl : Here's a lovely article dispelling various myths about email including "max len == 320". The limit is actually 254.
    Bob : Where is the lovely article?
    Dominic Sayers : He may mean this: http://www.dominicsayers.com/isemail
  • 64 for the local part (the account/name) and 255 for the domain. I think the @ sign will be counted extra so that sums to 320.

    But caution: this is only the length of the real address. An address may contain a display name. Such an address looks like first last <local@domain> and will often extend 320.

    Dominic Sayers : But you will be sending the email over SMTP, so the address has to fit into the forward-path field, which has a maximum length of 256 characters. Also note that it will have angle brackets round it in this field so that actual address (including the @) can be no more than 254 characters.
    Dominic Sayers : More here: http://www.dominicsayers.com/isemail
  • You may want to consult: RFC 821.

    I'm not sure if this RFC has been superseded by another RFC. According to my math it makes the longest email address 129 characters.

    user    -  64 characters
    domain  -  64 characters
    at-sign -   1 character
    ------------------------
    total   - 129 characters
    
    Tim Stewart : Here's an interesting article: http://www.eph.co.uk/resources/email-address-length-faq/
    Dominic Sayers : RFC 821 was suerseded by RFC 2821 which was then superseded by RFC 5321. This was back before either of us had a goatee. See http://www.dominicsayers.com/isemail
  • The original version of RFC 3696 did indeed say 320 was the maximum length, but John Klensin subsequently accepted this was WRONG.

    The maximum length is specified in RFC 5321: "The maximum total length of a reverse-path or forward-path is 256 characters"

    RFC 3696 was corrected here

    I note for the record that John Klensin may actually be wrong in his correction: a Path is defined as

    Path = "<" [ A-d-l ":" ] Mailbox ">"
    

    So the Mailbox element (i.e. the email address) has angle brackets around it to form a Path, so the Mailbox must be no more than 254 characters to keep the path under 256.

    I've now collated test cases from Cal Henderson, Dave Child, Phil Haack, Doug Lovell and RFC 3696. 158 test addresses in all.

    I ran all these tests against all the validators I could find. The comparison is here: http://www.dominicsayers.com/isemail

    I'll try to keep this page up-to-date as people enhance their validators. Thanks to Cal, Dave and Phil for their help and co-operation in compiling these tests and constructive criticism of my own validator.

    People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses.

    Álvaro G. Vicario : To sum up: the maximum length of an email address is **254** characters, as stated in http://www.dominicsayers.com/isemail/