Wednesday, April 20, 2011

How to convert a double to hex?

Hello, How do I convert a ruby float/double to high endian order hex with high bytes and low bytes.

EXAMPLE:

start with 99.0

end up with

40 58 C0 00   00 00 00 00
high bytes    low bytes
From stackoverflow
  • The array class has a pack method:

    a = [99.0]
    s = a.pack("d")
    s
    => "\000\000\000\000\000\300X@"
    

    This gives you a byte string, but converting from that to hex for printing should be trivial.

    If you want to go the other way, the string class has an unpack method:

    s.unpack("d")
    =>[99.0]
    
  • Well, like Patrick said, it doesn't take a lot to convert past using Array\#pack.

    irb> [99.0].pack('G').split('').map { |ds| ds[0] }
    #=> [64, 88, 192, 0, 0, 0, 0, 0]
    irb> _.map { |d| "%02x" % d }
    #=> ["40", "58", "c0", "00", "00", "00", "00", "00"]
    irb> [99.0].pack('E').split('').map { |ds| ds[0] }
    #=> [0, 0, 0, 0, 0, 192, 88, 64]
    irb> _.map { |d| "%02x" % d }    
    #=> ["00", "00", "00", "00", "00", "c0", "58", "40"]
    

    So it depends whether you want to unpack it with the high-order byte in the zero index or the low order byte in the zero index:

          E     |  Double-precision float, little-endian byte order
          G     |  Double-precision float, network (big-endian) byte order
    

How does a string differ from an array of char pointers in C?

I was under the impression that they were the same thing. However, it looks to my like they are being treated differently here. The part I am confused about looks like this.

Foo* initFoo(char* name);

int main
{
  Foo* foo;
  char* player_name[25];
  scanf("%s", player_name);
  foo = initFoo(player_name);
}

Foo* initFoo(char* name)
{
  printf("\n%s", name);
}

The string prints out fine. However, I get a compiler warning that says: passing argument 1 of 'initFoo' from incompatible pointer type.

What am I missing about pointers?

From stackoverflow
  • A string is an array of characters. What you have here is an array of pointers to characters.

    ojblass : If you put the method to correct I will delete my answer.
  • char* player_name[25];  /* means an array of character pointers. */
    char  player_name[25];  /* will get rid of the warning */
    
  • To fix it change to:

    char player_name[25];
    
  • The line:

    char* player_name[25];
    

    allocates a 25 element array of pointers to char. A pointer to char is generally considered a string, so this declaration could be interpreted as an array of strings, but the memory for storing those strings does not exist yet. You would have to allocate those string separately.

    Assuming pointers are 4 bytes on your machine, this line would have the effect of allocating 25 x 4 = 100 bytes.

    In C, when you use an array name without a subscript, it "decomposes" into a pointer to the first element of the array.

    So... when this line is executed:

    scanf("%s", player_name);
    

    player_name points to 100 bytes of memory, enough room enough to hold 100 characters that are read in (well 99 characters plus a terminating NUL byte). The compiler is not protecting you from storing those characters in the memory that was allocated for 25 pointers.

    Finally:

    foo = initFoo(player_name);
    

    is passing the starting address of the array to the function initFoo(). The compiler knows this is probably wrong since initFoo() is supposed to take a pointer to chars, not at pointer to an array of char pointers, but it lets you do it anyway except for the warning. The printf() statement in initFoo() reinterprets that pointer as a char pointer, and you get the correct results!

    As others have said, it would be correct to change the one line to

    char player_name[25];
    

    which declares an array of 25 characters.

How can I get my text parsing regex to recognize a STOP token?

I have written a regular expression for text parser as following:

^\s*(?<Count>[0-9]+)\s*[x|X]\s*(?<Currency>[^\d\sN]?)(?<ParVal>\d+)(?<Type>[^Nn]?)\s.*$

to capture the pattern such as:

....
1 x 1p
1 x 3p 
....

It works well, however I don't know how to detect whenever 1 x 1p pattern is above/bellow the STOP line in regular expression (I'm just a regx newbie :-( )

....
1 x 1p    <= here
1 x 3p
STOP
1 x 1p     <= and here
....

Hope you can understood my problem.

From stackoverflow
  • That regex is being applied to one line at a time, so when you're looping over the lines, just check first if the line is "STOP", and if it is, break out of your loop. The check can't be done as part of the regex.

Ignore 'Security Warning' running script from command line

I am trying to execut a script from shared folder that I trust:

powershell -file "\\server\scripts\my.ps1"

But get security warning, and have to press 'R'

Security Warning Run only scripts that you trust. While scripts from the Internet can be useful, this script can potentially harm your computer. Do you want to run \server\scripts\my.ps1? [D] Do not run [R] Run once [S] Suspend [?] Help (default is "D"): d

Can I ignore this warning? Desired pseudo code is:

powershell -IGNORE_SECURITY_WARNING -file "\\server\scripts\my.ps1"
From stackoverflow
  • You want to set the execution policy on your machine using Set-ExecutionPolicy:

    Set-ExecutionPolicy Unrestricted
    

    You may want to investigate the various execution policies to see which one is right for you. Take a look at the "help about_signing" for more information.

  • Try this, edit the file with:

    notepad foo.ps1:Zone.Identifier
    

    And set 'ZoneId=0'

  • Did you download the script from internet?

    Then remove NTFS stream from the file using sysinternal's streams.exe on command line.

    cmd> streams.exe .\my.ps1
    

    Now try to run the script again.

  • This is touched on here: http://www.leeholmes.com/blog/PowerShellExecutionPoliciesInStandardImages.aspx and here: http://blogs.msdn.com/powershell/archive/2008/09/30/powershell-s-security-guiding-principles.aspx.

    Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

    If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...)

    Lee Holmes [MSFT]

    alex2k8 : Thank you! -ExecutionPolicy Bypass is exactly what I was looking for.

How to do a 'ExecuteNonQuery' in Castle Active Record

I have the following code to perform a database level operation through our active record ORM layer.

public static void Vacuum() {
  Execute(
    delegate(ISession session, object instance) {
      ISQLQuery query =
        session.CreateSQLQuery(@"
          VACUUM billableaddresses;
          ")
      query.List();
      return null;
    }, null);
}

Normally when I need to do a non-query like this (its very rare I admit) I simple put a select '1'; after the query which appeases Active Record enough to execute the query asa nonquery.

However, the postgres 'vacuum' command, must be run on its own and cannot be part of a multi statement query.

looking ISQLQuery interface, there doesnt seem to be a method to execute a nonquery, so I was wondering how this can be done?

From stackoverflow
  • For specific DB calls you can get a raw IDbConnection from

    ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof (object)).ConnectionProvider.GetConnection()
    
    Ash : Awesome. This is exactly what I was after, thanks.
    Mauricio Scheffer : ActiveRecord FAQ: http://using.castleproject.org/display/AR/FAQ

I have a linux box. How do I see how my html pages look as rendered in IE?

I have a linux box. How do I see how my html pages look as rendered in Microsoft Internet Explorer? How do I test javascript functionality in IE?

I don't want to install a VM and a copy of the Windows OS.

From stackoverflow
  • Your best friend as a Linux web developer: http://www.tatanka.com.br/ies4linux/page/Main_Page (IEs 4 Linux), which uses WINE to run different versions of IE

  • Check out this page to see how your page will look across browsers and OS'

    http://browsershots.org/

    To actually interact with your web site though I would suggest something like Wine or a VM like Xen.

    Also see this link: How to install internet explorer on Ubuntu or see this page IEs4Linux.

    Blorgbeard : Doesn't wine use Gecko, rather than reimplementing IE?
    Brian R. Bondy : You can run windows programs on Wine including IE.
    Eddie : If you run IE under Wine, then you are using IE, not Gecko.
  • I use linux at work and do web development that has to support IE6+ and Firefox2+.

    IE4Linux is not really good enough for properly testing IE browser rendering as it doesn't work exactly as IE does in Windows. You could use something like browsershots but I would recommend running Windows in a VM and test using that for IE testing. I've done that for awhile and it works great as long as you have a spare 512MB ram for XP.

    tpdi : Great suggestion, but my primary box these days is a netbook. Spare ram I do not have.
    SCdF : ouch, then I dunno dude. I've tried using IE4Linux before but I've had incorrect CSS, CTDs (from JS no lesS) and various rendering issues with it before. It might be good enough for a base santiy check with more detailed checks on XP done only so often.
  • Another Service similiar to browsershots but faster is http://ipinfo.info/netrenderer/. Otherwise - if you have a copy of windows lying around why not use a virtual machine? Suns virtualbox is nice enough: http://www.virtualbox.org/

Egg-chicken problem in OOP way

Hi Guys,

I have a chicken-egg problem. I would like too implement a system in PHP in a OOP way, in which two classes would play important roles: Database and Log. My idea was to build up the connection by the Database class, which would have public methods eg. runQuery(sUpdateQuery), doInsert(sInsert), etc. The Log class would writing logs through common methods just as like logMessage(message), logDatabaseQuery(sQuery) TO THE DATABASE. The problem comes now.

1: Inside the methods of the Database's class I would like to be able to use the Log class's logDatabaseQuery(sQuery)

2: This still would not be a big challenge if I would not like to use the Database class's doInsert(sInsert) method inside the logDatabaseQuery method.

I would like to keep it simple - and just use one instance of the database connection object, and from the loggeras well, if it is possible.

For many people Singleton model would be the first idea to choose, but I definitely would like to use different solution.

So there would be two classes which would use each-other's methods:

Database doInsert logDatabaseQuery

Log logDatabaseQuery doInsert

I would like to keep the Log methods separately (in the Log class), since later on it would have other methods for logging not just to the database, but to files or e-mails as well.

Any ideas, how this should / could be done in the nicest, OOP friendly way?

I was thinking about a common parent abstract class, or about using interfaces as well, but finally could not figure out the proper way :(

What I would like to know is a suggestion for a correct class hierarchy

From stackoverflow
  • Create an insert method overload that allows for inserts without logging, and have your logging class use that. Otherwise, your design is recursive by definition: Log all DB inserts by performing a DB insert.

  • add an optional parameter to doInsert $callerIsLogger=false, then everytime you need to doInsert() from your logger, provide the second parameter true, and your doInsert could check for this situation and not call the logger when is called by logger. What hierarchies? KISS methodology rocks :)

  • This is a good candidate for the Mediator Pattern. You would have an object that the logger and database would both invoke various methods on, and this mediator object would keep references to the logger and database and handle communication for you.

  • Create a Logger class that implements a interface ILogger. A new instance of the Logger class receives a Object that implements the interface ILoggingProvider that is used to output log messages.

    Create a Database class that implements the ILoggingProvider interface. A new instance of the Database receives a object that implements the ILogger interface that is used to log messages.

    public interface ILogger
    {
       void Debug(String message)
    }
    
    public interface ILoggingProvider
    {
       void Log(String message)
    }
    
    public class Logger : ILogger
    {
       private ILoggingProvider LoggingProvider { get; set; }
    
       public Logger(ILoggingProvider loggingProvider)
       {
          this.LoggingProvider = loggingProvider;
       }
    
       public void Debug(String message)
       {
          this.LoggingProvider.Log(message);
       }
    }
    
    public class Database : ILoggingProvider
    {
       private ILogger Logger { get; set; }
    
       public Database(ILogger logger)
       {
          this.Logger = logger;
       }
    
       public void DoStuffWithTheDatabase()
       {
          // Do stuff with the database
          this.Logger.Debug("Did stuff with the database.");
       }
    
       public void Log(String message)
       {
          // Store message to database - be carefull not to generate new
          // log messages here; you can only use the subset of the Database
          // methods that do not themselve generate log messages
       }
    }
    
    Mark Ransom : Doesn't that leave you with a recursion problem?
    Daniel Brückner : That is exactly what S.Lott pointed out. You cannot use logging everywhere in the Database class - so it would be good to explicitly seperate these parts.
  • It sounds like you have two different database accesses - logged (normal case) and unlogged (for the logging functions). Split the database class into two, a higher-level version for logged requests, and a lower-level version for unlogged requests. Implement the higher level database class using references to the logging and lower level database classes.

    Frank Crook : You can write the database class so that it may log activities if a logger object is available, and so that it won't log activities if a logger object isn't available. Writing two database classes isn't necessary.
    Mark Ransom : Sure, you COULD do it that way. But the question asked for an object-oriented solution that reused one instance of a database object, and I think this is the cleanest way to do so.
  • You could add another class that both the Database and Logger use to avoid getting into an infinite logging loop (and avoid the circular dependency as well).

    // Used only by Logger and DatabaseProxy
    class Database {
       function doInsert( $sql ) {
          // Do the actual insert.
       }
    }
    
    class Logger {
       function log($sql) {
         $msg_sql = ...
         Database.doInsert($msg_sql);
    }
    
    // Used by all classes
    class DatabaseProxy {
       function doInsert( $sql ) {
          Logger.log($sql);
          Database.doInsert($sql);
       }
    }
    

    You could dress it up a bit by having both Database and DatabaseProxy implement a common interface as well, and use a factory to provide the appropriate instance.

  • You have combined too many things together.

    The database can't really depend on a logger which depends on the database. It isn't good design.

    What you really have are two kinds of database access.

    Low-level access does "raw" SQL.

    The logger can depend on this lower-level class. It doesn't -- itself -- have raw SQL in it. It depends on a lower-level class.

    High-level access does application queries, it uses low-level access and the logger.

    Frank Crook : Putting "raw" SQL in your logger class is a great way to make a mess you'll have to clean up later. Just pass it to a database object and pass the database object to it.
    Javier : there's no requirement that the lower-level DB do only raw SQL. if you want, make an extra layer: 1:raw SQL, 2:OOP DB (uses 1), logger (uses 2), 3: logged DB (uses 2 and logger)
  • If you want to give the database object access to a logger, then you pass the logger to it. If you want to give your logger access to a database object, then you pass the database object to it.

    Check to see if those objects exist within the class before you use functions that are provided by them.

    Since PHP passes these objects by reference by default, you can do this with a single logger and database class for several objects.

    I'd also recommend you do all of your database writing at a single point in the logger. Just store everything in a temporary array and run your DB code when you deconstruct. Otherwise, you'll create a ton of overhead if you're writing to the database throughout your code.

    class Database {
        private $_logger = 0; //contains your logger
        /* The rest of your class goes here */
    
        //Add the logger to your class so it may access it.
        public function setLogger($logger) {
            $this->_logger = $logger;
        }
    
        //To check if we have a logger, we don't want to use one if we lack one.
        public function hasLogger() { 
            if($this->_logger) return true; 
            else return false;
        }
    }
    class Logger {
        private $_database = 0; //variable to hold your database object
        /* The rest of your class goes here */
    
        public function setDatabase($database) { //Same crap basically
            $this->_database = $database;
        }
    
        public function hasDatabase() {
            if($this->_database) return true;
            else return false;
        }
    
        public function doSomething { //This is new though
            if($this->hasDatabase()) { //Shows how you use hasDatabase()
                $this->_database->someDatabaseFunction();
            }
            else {
                //Whatever you'd do without a database connection
            }
        }
    }
    $database = new Database;
    $logger = new Logger;
    
    $database->setLogger($logger);
    $logger->setDatabase($database);
  • IMHO, the database class should not be interacting with the logger. I would be inclined to call the logger from the same part of the code that is calling the database class. Then the logger can use the database class to do its inserts.

  • Decouple Database from Logger. I would design the application to log from the middle tier and make the decision about which logger type to use at runtime not compile time. I.e. use a factory method to determine whether to log to db/xml/whatever.

    If the Data Layer does need to log (i.e. report a problem) have it throw an exception, catch it in the middle tier and then decide how to handle it there or hand it off to a diagnostics class and have that decide. Either way I'd keep the DAL as "blind/dumb" as possible and not have it making decisions about what is and what is not a loggable event.

    A common parent class is not a good idea. A logger is not a database[r]. And nor is a database a logger. Its not so much a chicken and egg problem as it is a cow and a pig problem. They are two different animals. There is no reason for Database to be aware of logger. I think you are forcing the abstraction. All i see is that a Logger has a Database.... if it's a db logger that is.

    You drive the data layer from the middle tier anyway, so when including exceptions and events, I cant see where you would lose fidelity in logging db related events.

     public interface ILoggingProvider
        {
           void Log(String message)
        }
    
        public static class Logger
        {
           public static ILoggingProvider GetLoggingProvider()
           {
              //factory to return your logger type
           }
    
           public void Log(String message)
           {
              Logger.GetLoggingProvider().Log(message);
           }
        }
    
        public class DBLogger : ILoggingProvider {
    
          void Log(string message) {
           Database db = new Database();
           db.doInsert(someLoggingProc);
         }
        }
    
        public class Database
        {
            runQuery(sUpdateQuery) 
            doInsert(sInsert)
        }
    
    ...
    
    
     public class Customer{
    
     public void SaveCustomer(Customer c)
     {
       try {
        // Build your query
        Database db = new Database();
        db.runQuery(theQuery);
       } catch (SqlException ex) {
        Logger.Log(ex.message);
       }
     }
    }
    
  • sounds like you adding a lot of complication to a simple problem purely for the sake of making it object oriented...

    ask yourself this, what are you really gaining by taking that approach?

    Javier : as much as i hate "OOP for the sake of OOP" (or any design style 'just because'), in this specific case, it's not a bad design, and well done can be much more maintainable than non-OOP sequential code (is there a name for that? no, 'imperative' is not)
    drhorrible : 'Procedural', I think is the word
  • You could make a second arg for your Database::insert() function:

    function insert($sql, $logThis = true) { ... }
    

    And then obviously when the logger calls it, make the second argument false.

    Alternatively, just check the function stack to see if the insert function was called from the Logging class.

    function insert($sql) {
        $callStack = debug_backtrace();
        if (!isset($callStack[1]) || $callStack[1]['class'] !== "Logger") {
            Logger::logSQL($sql);
        }
        // ...
    }
    
  • How I would do it:

    public interface ILogger
    {
        void LogWarning(string message);
        void LogMessage(string message);
    }
    
    public interface ILoggingProvider
    {
        void LogEntry(string type, string message);
    }
    
    public interface IDbProvider
    {
        void DoInsert(string insertQuery, params object[] parameters);
    }
    
    public class Logger: ILogger
    {
        private ILoggingProvider _provider = ProviderFactory.GetLogProvider();
    
        public void LogWarning(string message)
        {
            _provider.LogEntry("warn", message);
        }
    
        public void LogMessage(string message)
        {
            _provider.LogEntry("message", message);
        }
    
        public void LogEntry(string type, string message)
        {
            _provider.LogEntry(type, message);
        }
    }
    
    public class Database : IDbProvider
    {
        private Logger _logger = new Logger();
        public void DoInsert(string insertQuery, params object [] parameters)
        {
            _logger.LogEntry("query", insertQuery);
        }
    }
    
    public class DbLogProvider : ILoggingProvider
    {
        private IDbProvider _dbProvider = ProviderFactory.GetDbProvider();
    
        public void LogEntry(string type, string message)
        {
            _dbProvider.DoInsert("insert into log(type,message) select @type,@message",type,message);
        }
    
    }
    
    public static class ProviderFactory
    {
        public static IDbProvider GetDbProvider()
        {
            return new Database();
        }
    
    
        internal static ILoggingProvider GetLogProvider()
        {
            return new DbLogProvider();
        }
    }
    

    Although I would probably also make it look up a type from a config file rather than hardcoding them in the ProviderFactory class. The assumption here is that your code doesn't care how it is logged, that's up the administrator, and that all logging would be done one way during execution(which would my preference anyway). Obviously you could extend this to make a choice as to the log target when creating the logger and create the appropriate provider.

    Darren Clark : Same recursion problem. I almost answered a comment above. Yes, you need to separate into a non-logging DbProvider that just does the database access.

What is the purpose of ObservableCollection raising a PropertyChange of "Item[]"?

What is the purpose of ObservableCollection raising a PropertyChange of "Item[]"?

Is this something I should be doing if I have a class that implements INotifyCollectionChanged?

Do WPF controls use this PropertyChange of "Item[]" somehow?

From stackoverflow
  • Yes WPF and Silverlight controls use the PropertyChange event to update UI controls. This allows things like ListView's or DataGrid's to automatically update in response to their bound ObservableCollection - or other collection implementing INotifyCollectionChanged - changes.

    Edit: As far as implementation goes you generally shouldn't need to implement your own collection so don't need to worrk about INotifyCollectionChanged. For your classes that will be used in the ObservableCollection you need to implement INotifyPropertyChanged. This allows your objects to fire the PropertyChanged event whenever they are updated which will allow your UI control to automatically show the change.

    jyoung : I am confused. You say that WPF uses 'PropertyChange of "Item[]"', but I should implement 'CollectionChanged'.
  • ObservableCollection implements both INotifyCollectionChanged and INotifyPropertyChanged.

    INotifyPropertyChanged is used to indicate that a property of the ObservableCollection has changed, like the number of its elements ("Count") or an element accessible through the collection's indexer ("Item[]"). Additionally, ObservableCollection implements INotifyCollectionChanged to indicate which element has changed exactly and how.

    Have a look at the Mono implementation of ObservableCollection to see what the ObservableCollection does exactly. For example, here is the InsertItem method:

    protected override void InsertItem (int index, T item)
    {
        CheckReentrancy ();
    
        base.InsertItem (index, item);
    
        OnCollectionChanged (new NotifyCollectionChangedEventArgs (
            NotifyCollectionChangedAction.Add, item, index));
        OnPropertyChanged (new PropertyChangedEventArgs ("Count"));
        OnPropertyChanged (new PropertyChangedEventArgs ("Item[]"));
    }
    

    If you want to implement your own ObservableCollection-like collection class, it seems the proper way to implement both INotifyCollectionChanged and INotifyPropertyChanged.

jquery select text

<div>select this<strong>dfdfdf</strong></div>
<div><span>something</span>select this<strong>dfdfdf</strong></div>

how do i use jquery or just javascript to select the value of the div tag but not include any child elements

//output
select this
From stackoverflow
  • $("div").contents().each(function(i) {
        //the function is applied on the node. 
        //therefore, the `this` keyword is the current node.
        //check if the current element is a text node, if so do something with it
    });
    
    Chadwick : The function args are (i,node), and the test is on node.nodeName: $("div").contents().each(function(i,node) { if (node.nodeName == "#text") console.log(node.textContent); });
    geowa4 : the function is applied on the node. therefore, the `this` keyword is the current node.
  • Using XPath, you can select only the text node children of the div. Raw javascript below.

    var xpr = document.evaluate("//div/text()",document,null,
        XPathResult.STRING_TYPE,
        null);
    console.log(xpr.stringValue);
    
    > select this
    


    If you have text interspersed with tags:

    <div>select this<strong>dfdfdf</strong>and this</div>
    

    ...you can iterate over them (helper converts XPathResult to array)

    function $x(path, context, type) {
        if (!context) context = document;
        type = type || XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;
        var i,item,arr=[], xpr = document.evaluate(path, context, null, type, null);
        for (i=0; item=xpr.snapshotItem(i); i++) 
          arr.push(item);
        return arr;
    }
    
    var nodes = $x("//div/text()");
    nodes.forEach(function(item) {
        console.log(item.textContent);
    });
    
    > select this
    > and this
    

    (tested in FF, w/ firebug logging)

  • Plain JS version:

    function getDirectTextContent(element) {
        var text= [];
        for (var i= 0; i<element.childNodes.length; i++) {
            var child= element.childNodes[i];
            if (child.nodeType==3)                           // Node.TEXT_NODE
                text.push(child.data);
        }
        return text.join('');
    }
    

How to convert an IntPtr back into an object

All, this is a follow up from a previous question here: http://stackoverflow.com/questions/727942/c-formatting-external-dll-function-parameters

Here specifically is the code that I am trying to convert to C#:

FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)MapName, &PacketSize, pMapping, &PagePerSector);
// Allocate the mapping structure memory
pMapping = (PMAPPING)malloc(sizeof(MAPPING));
pMapping->NbSectors = 0;
pMapping->pSectors = (PMAPPINGSECTOR) malloc((Size) * sizeof(MAPPINGSECTOR));

// Get the mapping info
FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)(LPCTSTR)MapName, &PacketSize, pMapping, &PagePerSector);

The function "FILES_GetMemoryMapping" gets called twice, I'm guessing the first time to get the size of the struct, and the second to actually fill it.

the "pMapping" is a pointer to a struct in C++, In my C# code, I have pMapping as type IntPtr. The next line I can converted to :

pMapping = Marshal.AllocHGlobal(Marshal.SizeOf(new UM0516.Mapping()));

With (UM0516.Mapping) being the struct. Cool, so I've just allocated some space that IntPtr is pointing to. Now for the next line... "pMapping->NbSectors = 0;"

How am I suppose to go into the now allocated unmanaged memory space, type cast it as a (UM0516.Mapping) struct, and set one of its members? Then make sure i didn't screw with it too much so that the second time I call "FILES_GetMemoryMapping", it can now use this struct??

-- Ok, I've taken some advice and now have this:

I tried this and I get a "AccessViolationException was unhandled" exception on the first "FILES_GetMemoryMapping" call

Here is what I have:

string filepath = @"C:\blah.blah";
string MapFile = @"D:\blah.blah";
UM0516.Mapping myMapping = new UM0516.Mapping();
IntPtr pMapping = Marshal.AllocHGlobal(Marshal.SizeOf(myMapping));
Marshal.StructureToPtr(myMapping, pMapping, false);
ushort PacketSize = 0;
ushort size = 0;
string MapName = String.Empty;
byte PagePerSector = 0;

uint b7 = UM0516.FILES_GetMemoryMapping(MapFile, out size, MapName, out PacketSize, pMapping, out PagePerSector);

Do you think this exception is coming from the "pMapping" parameter? Could this come from anything else that I've passed in?

From stackoverflow
  • In order to get the IntPtr, what you'll want to do is create your structure, set any options that you may need to, allocate the memory like you already have, then call..

    System.Runtime.InteropServices.Marshal.StructureToPtr(yourStructVariable, pMapping, false);
    

    This will copy the data from your populated structure into your allocated memory.

    To copy data from the memory into a new structure named 'mapping', call...

    UM0516.Mapping mapping = (UM0516.Mapping)System.Runtime.InteropServices.Marshal.PtrToStructure(pMapping, typeof(UM0516.Mapping))
    

Is there a documented JavaScript API for Windows Media Player?

I want to use JavaScript to control an embedded Windows Media Player, as well as access any properties that the player exposes. I've found a few hacky examples online, but nothing concrete.

I really need access to play, pause, stop, seek, fullscreen, etc. I'd also like to have access to any events the player happens to broadcast.

Help would be wonderful (I already have a Flash equiv, just so you know), thanks!

From stackoverflow
  • Windows media player is exposed as an activex control that any scripting language running in the windows script host should be able to access. You should be able to use jscript to control it. Jscript is microsofts implimentation of java script. For information on what objects and methods are availble using jscript for windows media player se this link.

  • There is no open JavaScript library as far as I know for crossbrowser clientside handling of a WMP player. However, this link should make it quite easy for you to start your own little library. The code might need some updating and testing in modern browser versions but you have the basics there.

    The library your searching for would be a great idea for a Google Code project, I guess that while everyone today is using Adobe Flash with sIFR / swfobject or Microsoft Silverligt with sistr etc, there are not much interest to write clientside script controlling for WMP.

    ironkeith : Sadly I have to deal with a big old corporate client whose IT dept thinks that adding Flash or Silverlight to the OS image might cause conflicts. Hooray for client work... thanks for the link though, it looks helpful.
  • http://www.schillmania.com/projects/soundmanager2/ allows you to access play, pause, etc but it is flash based.

    Eric

  • There is an API in Microsoft's developer center, but it will only work if you embed windows media player using active-x.

    To "learn" more about the API, check out MSDN: http://msdn.microsoft.com/en-us/library/dd564034(VS.85).aspx

    Ron Harlev : The link is for Media Player in Microsoft Windows CE .NET 4.2 I don't think that is the operating system you really care about
  • The API requires ActiveX connectivity native to Internet Explorer, or can use a plugin for Firefox.

    Here's a sample page that might get you started.

    <html>
    <head>
      <title>so-wmp</title>
      <script>
    
        onload=function() {
          player = document.getElementById("wmp");
          player.URL = "test.mp3";
        };
    
        function add(text) {
          document.body
            .appendChild(document.createElement("div"))
            .appendChild(document.createTextNode(text));
        };
    
        function handler(type) {
          var a = arguments;
          add(type +" = "+ PlayStates[a[1]]);
        };
    
        // http://msdn.microsoft.com/en-us/library/bb249361(VS.85).aspx
        var PlayStates = {
           0: "Undefined", // Windows Media Player is in an undefined state.
           1: "Stopped", // Playback of the current media item is stopped.
           2: "Paused", // Playback of the current media item is paused. When a media item is paused, resuming playback begins from the same location.
           3: "Playing", // The current media item is playing.
           4: "ScanForward", // The current media item is fast forwarding.
           5: "ScanReverse", // The current media item is fast rewinding.
           6: "Buffering", // The current media item is getting additional data from the server.
           7: "Waiting", // Connection is established, but the server is not sending data. Waiting for session to begin.
           8: "MediaEnded", // Media item has completed playback.
           9: "Transitioning", // Preparing new media item.
          10: "Ready", // Ready to begin playing.
          11: "Reconnecting" // Reconnecting to stream.
        };
    
      </script>
      <script for="wmp" event="PlayStateChange(newState)">
        // http://msdn.microsoft.com/en-us/library/bb249362(VS.85).aspx
        handler.call(this, "playstatechange", newState);
      </script>
    </head>
    <body>
      <div id="page">
        <object id="wmp"
           classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6"
              type="application/x-oleobject">
        </object>
      </div>
    </body>
    </html>
    
  • Can you please tell whether there is a complete player for WMP “…

    ??

javax vs java package

Hi!

What's the rationale behind the javax package? What goes into java and what into javax?

I know a lot of enterprise-y packages are in javax, but so is Swing, the new date and time api (JSR-310) and other J2SE packages.

From stackoverflow
  • I think it's a historical thing - if a package is introduced as an addition to an existing JRE, it comes in as javax. If it's first introduced as part of a JRE (like NIO was, I believe) then it comes in as java. Not sure why the new date and time API will end up as javax following this logic though... unless it will also be available separately as a library to work with earlier versions (which would be useful).

    I believe there are restrictions on the java package - I think classloaders are set up to only allow classes within java.* to be loaded from rt.jar or something similar. (There's certainly a check in ClassLoader.preDefineClass.)

  • java packages are "base", and javax packages are extensions.

    Swing was an extension because AWT was the original UI API. Swing came afterwards, in version 1.1.

    Tom Hawtin - tackline : Swing was not part of 1.1. There was a version of Swing that ran on 1.1 as a library.
    duffymo : There's the key - "library", not part of the JDK. Do I have the version wrong? My javadocs suggest that JButton has been since 1.3, so perhaps my memory failed me.
  • The javax namespace is usually (that's a loaded word) used for standard extensions, currently known as optional packages. The standard extensions are a subset of the non-core APIs; the other segment of the non-core APIs obviously called the non-standard extensions, occupying the namespaces like com.sun.* or com.ibm.. The core APIs take up the java. namespace.

    Not everything in the Java API world starts off in core, which is why extensions are usually born out of JSR requests. They are eventually promoted to core based on 'wise counsel'.

    The interest in this nomenclature, came out of a faux pas on Sun's part - extensions could have been promoted to core, i.e. moved from javax.* to java.* breaking the backward compatibility promise. Programmers cried hoarse, and better sense prevailed. This is why, the Swing API although part of the core, continues to remain in the javax.* namespace. And that is also how packages get promoted from extensions to core - they are simply made available for download as part of the JDK and JRE.

  • originally javax was intended to be for extensions, and sometimes things would be promoted out of javax into java.

    One issue was Netscape (and probablu IE) limiting classes that could be in the java package.

    When Swing was set to "graduate" to java from javax there was sort of a mini-blow up because people realized that they would have to then modify all of their imports. Given that backwards compatibility is one of the primary goals of Java they changed their mind.

    At that point in time, at least for the community (maybe not for Sun) the whole point of javax was lost. So now we have some things in javax that probably should be in java... but aside from the people that chose the package names I don't know if anyone can figure out what the rationale is on a case-by-case basis.

How different is PostgreSQL to MySQL?

Hiya,

I've been asked to support and take on a PostgreSQL app, but am a MySQL guy - is this a realistic task?

From stackoverflow
  • I faced the same situation about a month ago.... I have been doing fine with postgres. There is a strong online community for postgres and you should be able to find help if you run into any trouble and learn stuff easily :)

  • How different is PostgreSQL to MySQL?

    That depends if you're talking about SQL only (which is mostly the same) or the stored procedures (which are quite different).

    is this a realistic task?

    Absolutely. PostgreSQL has very good documentation and community. There are also lot of ppl, who have experience with MySQL and PostgreSQL.

    "MySQL vs PostgreSQL wiki" — centers on "which is better", but gives you some idea of differences.

  • PostgreSQL has some nice features like generate_series, custom aggregate functions, arrays etc, which can ease your life greatly if you take some time to learn them.

    On the other hand it lacks some features of MySQL like using and assigning session variables in queries, FORCE INDEX, etc., which is quite annoying if you are used to these features.

    If you just use basic SQL, then you will hardly notice any difference.

  • You may want to take a look at these pages: Why PostgreSQL Instead of MySQL: Comparing Reliability and Speed in 2007, Why PostgreSQL Instead of MySQL 2009.

  • I didn't take very long to switch from MySQL to PostgreSQL back when I first started using PostgreSQL in anger at a previous company. I found it very nice and very refreshing (not that MySQL was bad) compared to MySQL which I had used previously. PostgreSQL was also a good stepping stone to Oracle which I use at my current company. I liked that it had a proper command line application like MySQL, but the configuration options are harder - but if you're not setting it up then there is no problem.

  • PostgreSQL compared to MySQL is as any other pair of DBMSs compared. What they have in common is non-functional, specifically the consequences of each being open source. In terms of features, use, and strengths they are no closer to each other than PostgreSQL is to Oracle or DB2 is to Sybase.

    Now on to your real question: you are a SQL guy, albeit one who has not yet had experience with PostgreSQL. This is a completely realistic task for you, and a good one since you'll expand your understanding of the varieties of DBMSs and gain a perspective on MySQL that you can't get from working solely within its sphere.

    As someone who was once in exactly the same position, my guess is that you'll quickly pick up PostgreSQL and might even hesitate to return to MySQL ;-).

  • If you're interested in the different flavors of SQL, here are a few resources (though some may be outdated):

  • We are trying to switch our application from mySQL to postgres. I wished we would have some kind of a subroutine (in VB6) were I can input the mySQl SQL query and get a string out containing the appropriate postgres query.

    Does anybody have a solution or is interested working with us on that?

    Thank you!

    Thomas

    outis : StackOverflow is a Q&A site, not a forum. This means that if you have a question, ask it separately; don't post it as an answer to another question. Even on forums, threadjacking is considered bad netiquette. Do a little lurking and read the FAQ to familiarize yourself with SO.

gmail javascript bookmarklet

If I load this in a new tab (FF3) it works. If I load it in the current tab it just prints the url.

I think it's actually a matter of loading it in an existing gmail tab. So say, make the bookmarklet, click it once, then click it again. That seems to be the way to recreate the problem.

Any idea what would cause this? I can think of a few workarounds, but I'm curious about how this works.

javascript:var%20t=new%20Date(),y=t.getFullYear(),m=t.getMonth()+1,d=t.getDate();document.location.href="http://mail.google.com/mail/#search/is%3Aunread+after%3A"+y+"-"+m+"-"+d

/* same code split up for readability */
javascript:
  var t = new Date(),
      y = t.getFullYear(),
      m = t.getMonth()+1,
   /* d = t.getDay(); I actually have this correct above, but not here.. oops */
      d = t.getDate(); 
  document.location.href="http://mail.google.com/mail/#search/is%3Aunread+after%3A"+y+"-"+m+"-"+d;

Any help?

Thanks :)

UPDATE:

when I remove the extra whitespace from this answer and covert the necessary spaces to "%20" (url encoding), it does nothing at all:

 /* this works. I was missing the final ")" altCognito wrote */
 javascript:void((function(){var%20t=%20new%20Date(),y=t.getFullYear(),m=t.getMonth()+1,d=t.getDate();window.location.href="http://mail.google.com/mail/#search/is%3Aunread+after%3A"+y+"-"+m+"-"+d;})())

I also experimented with some semicolon fiddling and other general syntax checks, but I'm not sure what I'm looking for. It works neither as a bookmarklet or when pasted straight into the address bar (for me anyway).

From stackoverflow
  • It is better practice to use window.location.href instead of document.location

    ThomasGHenry : I don't think that was it. I updated the question with new info. Thanks!
  • What you want is something that looks like this:

    javascript:void(
        (function() {
        var t = new Date(),
              y = t.getFullYear(),
              m = t.getMonth()+1,
              d = t.getDate();
          window.location.href="http://mail.google.com/mail/#search/is%3Aunread+after%3A"+y+"-"+m+"-"+d;
        })()
    )
    

    The key is the void((function() {... Your stuff here ... })())

    Note, that you also want to use getDate(), not getDay, as getDay returns the day of the week!

    ThomasGHenry : what is the meaning of this change anyway? why the void and the anonymous function call?

How should I change this declaration?

I have been given a header with the following declaration:

//The index of 1 is used to make sure this is an array.
MyObject objs[1];

However, I need to make this array dynamically sized one the program is started. I would think I should just declare it as MyObject *objs;, but I figure if the original programmer declared it this way, there is some reason for it.

Is there anyway I can dynamically resize this? Or should I just change it to a pointer and then malloc() it?

Could I use some the new keyword somehow to do this?

From stackoverflow
  • Use an STL vector:

    #include <vector>
    
    std::vector<MyObject> objs(size);
    

    A vector is a dynamic array and is a part of the Standard Template Library. It resizes automatically as you push back objects into the array and can be accessed like a normal C array with the [] operator. Also, &objs[0] is guaranteed to point to a contiguous sequence in memory -- unlike a list -- if the container is not empty.

    yves Baumes : "&objs[0] is guaranteed to point to a contiguous sequence in memory" But please be warnd: that's only ok when you are sure your vector is not empty (using empty() method for instance). Otherwise it could lead to Undefined behavior.
    Judge Maygarden : That's true and noted.
    aJ : if you know size in advance then Vector::reserve() would be helpful.
  • Using the STL is best if you want a dynamically sizing array, there are several options, one is std::vector. If you aren't bothered about inserting, you can also use std::list.

    jalf : That doesn't solve his problem. If he can change it to a pointer, he has plenty of options for resizing it. realloc won't let him resize the array while using the current declaration.
  • You're correct. If you want to dynamically instantiate its size you need to use a pointer.

    (Since you're using C++ why not use the new operator instead of malloc?)

    MyObject* objs = new MyObject[size];
    
    Tjofras : it should be, MyObject* objs = new MyObject[size]; right?
    Mel Green : oh, I think you're correct. I've gotten so used to C# it's tainted my C++ :)
  • Its seems - yes, you can do this change.
    But check your code on sizeof( objs );

    MyObj *arr1 = new MyObj[1];
    MyObj arr2[1];
    
    sizeof(arr1) != sizeof(arr2)
    

    Maybe this fact used somewhere in your code.

  • Or should I just change it to a pointer and then malloc() it?

    If you do that, how are constructors going to be called for the objects in on the malloc'd memory? I'll give you a hint - they won't be - you need to use a std::vector.

  • That comment is incredibly bad. A one-element array is an array even though the comment suggests otherwise.

    I've never seen anybody try to enforce "is an array" this way. The array syntax is largely syntactic sugar (a[2] gives the same result as 2[a]: i.e., the third element in a (NOTE this is an interesting and valid syntax but usually a very bad form to use because you're going to confuse programmers for no reason)).

    Because the array syntax is largely syntactic sugar, switching to a pointer makes sense as well. But if you're going to do that, then going with new[] makes more sense (because you get your constructors called for free), and going with std::vector makes even more sense (because you don't have to remember to call delete[] every place the array goes out of scope due to return, break, the end of statement, throwing an exception, etc.).

  • I have only seen an array used as a pointer inside a struct or union. This was ages ago and was used to treat the len and first char of a string as a hash to improve the speed of string comparisons for a scripting language.

    The code was similar to this:

    union small_string {
       struct {
          char len;
          char buff[1];
       };
       short hash;
    };
    

    Then small_string was initialised using malloc, note the c cast is effectively a reinterpret_cast

    small_string str = (small_string) malloc(len + 1);
    strcpy(str.buff, val);
    

    And to test for equality

    int fast_str_equal(small_string str1, small_string str2)
    {
       if (str1.hash == str2.hash)
          return strcmp(str1.buff, str2.buff) == 0;
       return 0;
    }
    

    As you can see this is not a very portable or safe style of c++. But offered a great speed improvement for associative arrays indexed by short strings, which are the basis of most scripting languages.

    I would probably avoid this style of c++ today.

  • Is this at the end of a struct somewhere?

    One trick I've seen is to declare a struct

    struct foo {
    /* optional stuff here */
    int arr[1];
    }
    

    and malloc more memory than sizeof (struct foo) so that arr becomes a variable-sized array.

    This was fairly commonly used in C programs back when I was hacking C, since variable-sized arrays were not available, and doing an additional allocation was considered too error-prone.

    The right thing to do, in almost all cases, is to change the array to an STL vector.

Can I read stored SMS entries on my Windows Mobile phone from a .NET CF application?

Looking at writing an application using the .NET Compact framework to extract SMS messages on my Windows Mobile phone. I basically want to be able to export the stored message in the inbox so that they could be imported to Excel or some other program for formatting and storage.

In my personal case, I have a Treo 700w. I've written some small apps under the Compact Framework before, but I can't find anything referencing where the text messages are stored. I have some 7000 messages stored in my phone and I'd like to extract them to free up memory. I may have to keep these messages around for legal reasons so I'd like to preserve them 'offline' as far as my phone is concerned.

Has anyone ever had to do this?

From stackoverflow
  • I don't believe the .NET Framework (compact or otherwise) includes an API for working with SMS which is done through CE MAPI. In other words you'll have to use interop, or write the app in C++. Or if you're lazy you can just use a wrapper. =)

  • If you are targeting WM6, you can use the Microsoft.WindowsMobile.PocketOutlook namespace to access SMS messages, particularly the SmsAccount class.

    David : Well, the phone I have is never going to see WM6 but my next one should. I may just end up delaying writing this application until I upgrade and leave the old phone 'as is' with the messages in it. Thanks for the tip!
  • how i can read sms in inbox in .net compact freamework for windowse mobile

  • i need your guide 4 read sms in inbox in .net freamework and windowse mobile

What is the point of a Data Transfer Object (DTO)?

Why should I use DTOs/Domain objects when I can just put all business classes in a class library, use them in the business logic, then also pass those same business objects on to boundary classes?

UPDATE: All are great points, thanks for the help. A follow up question:

Where do you typically place these DTOs? Alongside the Domain objects i.e. in the same namespace?

namespace MedSched.Medical
{
    public class MedicalGroup
    {
        //...
    }

    public class MedicalGroupDTO
    {
        //...
    }
}
From stackoverflow
  • DTOs are Data Transfer Objects, with Transfer being the key word. They are great when you want to pass your objects across the wire and potentially communicate with a different language because they are "light weight" (ie no business logic.)

    If your application isn't web service based, DTOs aren't really going to buy you anything.

    So deciding to use or not use DTOs should be based on the architecture of your application.

    Aaron : Makes sense - yes, the particular app in question is a highly-distributed app. Thanks for the input.
    Bob : Distributed in what sense? If you are using a remoting like technology, you can usually still serialize your Domain Objects and pass them across boundaries without any issues. Once you start getting into different platforms, DTOs usually make things easier.
  • There are times when the data you want to pass around doesn't map exactly to the structure the business objects, in which case you use DTOs.

    Ex: when you want to pass a subset of the data or a projection.

  • I can think of 2 basic scenarios for using DTOs:

    • You're creating your business object from data that's incomplete and will fail validation. For example, you're parsing a CSV file or an Excel file from where your business object is created. If you use data directly from these objects to create your business object, it is quite possible to fail several validation rules within the object, because data from such files are prone to errors. They also tend to have a different structure that you have in your final business object: having a placeholder for that incomplete data will be useful.

    • You're transporting your business object through a medium that is bandwidth intensive. If you are using a web service, you will need to use DTOs to simplify your object before transport; otherwise the CLR will have a hard time trying to serialize all your data.

    • The DTO's provide an abstraction layer for your domain model. You can therefore change the model and not break the contract you have for your service clients. This is akin to a common practice in database design where views and procedures become the abstraction layer for the underlying data model.
    • Serialization - you may over expose data and send bloated messages over the wire. This may be mitigated by using serialization attributes, but you may still have extra information.
    • Implicit vs. Explicit Contracts - by exposing domain objects you leave it up to the client to interpret their usage since they do not have the full model at their disposal. You will often make updates to domain objects implicitly based on the presence or removal of associations, or blindly accept all changes. DTOs explicitly express the usage of the service and the desired operation.
    • Disconnected Scenarios - having explicit messages or DTOs would make it easier for you to implement messaging and messaging patterns such as Message Broker, etc.
    • DDD - pure DDD demands that domain objects are externally immutable, and therefore you must offload this to another object, typically a DTO.