Thursday, March 31, 2011

PHPExcel: scientific notation of double/float

The problem is the following: We are creating an instance of a class testObject and fill a var with a double.

A class TestExcel extends from PhpExcel and when submitting the object testObject into the constructor we get a scientific notation of the var when we do a var_dump.

Can anyone help us out. My colleagues and I don't understand how it is possible that the content of an instance can be changed by extending the phpExcel class.

When we don't do the extension, the var_dump returns the correct notation. -- 200000 When doing the extension we get the scientific notation -- 2.0E+5

// instance of the testObject

$number = new testObject();
$number->setNumber((double)200000);

// contruct testExcelClass
$excel = new TestExcel($number);


// Class TestObject      
class testObject {

      private $number;

      public function setNumber($number){
          $this->number = $number;
      }

      public function getNumber(){
          return $this->number;
      }

}

// class test excell extends from phpexcel (http://www.codeplex.com/PHPExcel) 
class TestExcel extends PHPExcel  {

    private $number;

    public function __construct($number){
      parent::__construct();

      $this->number = $number;
      print_r($this->number); exit();

    }

}
From stackoverflow
  • you should probably set formatting of the cell to have the desired number format. i am not sure about the exact function, check the docs.

  • it seemed to be a problem in PHP 5.2.6 that displayed the wrong notation.

    php 5.2.8 solved this bug.

How to map Items which its SubItems are in the same Table with Nhibernate?

Hi,

I am trying to build a messaging system and for this i have the table definition below

Message

Id
From
To
Body
ParentId // Subcollection, i want to get Asnwers (Message.ParentId== Message.Id)
IsRead

and i have this in the Message.cs

IList<Message> Answers;

I have tried this but it gives me all the messages and all the answers in the main collection.

But i dont want answers to be seen like a message (like the main item).

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="RealEstate.Core" namespace="RealEstate.Core.Domain">
  <class name="Message" table="Message" lazy="true">
    <id column="id" type="Int64" name="Id">
      <generator class="native" />
    </id>
    <property name="From" column="[From]" type="Int64" />
    <property name="To" column="[To]" type="Int64" />
    <property name="Body" column="Body" />
    <property name="ParentId" column="ParentId" type="Int64" />
    <property name="SenderType" column="SenderType" type="Byte" />
    <property name="IsRead" column="IsRead" type="Boolean" />

    <bag name="Answers" lazy="true" cascade="delete">
      <key column="ParentId" />
      <one-to-many class="Message"/>
    </bag>

  </class>
</hibernate-mapping>

How can this mapping be done, they are in the same table ?

Thank you very much

From stackoverflow
  • Before attempting an answer, I'd strongly recommend that you search the NHibernate Users Group as there are tons of helpful NHibernate folks that lurk there answering all kinds of questions.

    But let me see if I can help here.

    Hmmm, I'm not totally sure I understand the question. You say:

    I have tried this but it gives me all the messages and all the answers in the main collection.

    But i dont want answers to be seen like a message (like the main item).

    Do you mean that the Answers collection contains all answers in the database?

    Can you post up more code, showing the query your running, and the class code?

    One potential problem you have with your scenario is that ParentId can be NULL in the database. This gives NHibernate problems when mapping a one-to-many.

    Try making the association bidirectional (documentation reference). That sometimes helps avoid a few traps.

    To do that, add this to your class

    public class Message {
      ///<summary>Reference to parent message</summary>
      public Message Parent {get;set;}
    
      //... rest of class
    

    Add this to your mapping:

    <bag name="Answers" lazy="true" cascade="delete" inverse="true">
       <key column="ParentId" />
       <one-to-many class="Message"/>
    </bag>
    
    <many-to-one name="Parent"/>
    

    The inverse=true will make NHibernate manage the relationship from the Parent property, not the collection. This is necessary because ParentId can be null.

    In your code, rather than using myMessage.Answers.Add( blah ); you can use answer.Parent = myMessage. Of course, you can write nice helper methods to make this more meaningful.

    someMessage.AddAnswer( someAnswer );
    

    Which looks like this:

    public void AddAnswer(Message answer)
    {
       answer.Parent = this;  
       if( ! this.Answers.Contains(answer) )
          this.Answers.Add(answer);
    }
    

    Hope this helps.

    Barbaros Alp : Thank you very much for your help, but this is exactly what i m searching for http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/05/14/how-to-map-a-tree-in-nhibernate.aspx thanks again
  • You want to map a tree ? Maybe this could help: how to map a tree in nhibernate

    Barbaros Alp : thank you very much

LINQ Query skips without exception. Why?

I have a method that gets a nested array as parameter:

Number[][] data

where Number is my very simple class that inherits from INotifyPropertyChange.

And then i have a statement like this:

double[] max = (double[])data.Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max());

When I'm trying to watch it in the debugger it just skips it and the whole method though no exception pops out.

What is the answer? And what is the better way to do it.

I can use loops, of course - but it looks so dirty and long. So LINQ is preferrable

P.S. I'm using VS2008 SP1

From stackoverflow
  • Usually this type of behaviour means that your source code files are not up to date. Try deleting all .bin and .pdb files from the output directory and rebuild.

  • Are you sure that the Select method returns an array? Casting + generics = code smell

    Try this:

    double[] max = data
      .Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max())
      .ToArray();
    


    Conversion Method - (ToArray) allocates a new array and populates it. Bound by the restrictions of methods.

    Down Casting - Allows you to change the type of the reference to an object instance. Only the actual instance type, or some type that the instance type inherits from are allowed. Anything else gives a runtime exception.

    Explicit Conversion Operator - uses the syntax of down casting, to achieve the effect of conversion. It's really a Conversion Method. This is an endless source of confusion for people trying to understand casting.

    Consider this code:

    // reference type is IEnumerable<string>, instance type is string[]
    IEnumerable<string> myArray =
      new string[3] { "abc", "def", "ghi" };
    // reference type is IEnumerable<string>, instance type is ???
    IEnumerable<string> myQuery = myArray
      .Select(s => s.Reverse().ToString());
    
    //Cast - works
    string[] result = (string[]) myArray;
    //Cast - runtime exception: System.InvalidCastException
    result = (string[])myQuery;
    //Conversion - works
    result = myQuery.ToArray();
    

    Why didn't you get a runtime exception in vs? I don't know.

    Aks1 : No it's not. It returns IEnumerable, but I thought that casting and ToArray() is doing the same thing - transforming IEnumerable to Array. Your method actually works, but what is the difference? And why this strange Visual Studio behavior?
    Aks1 : Yeah, I'm really thought that it will use conversion operator. Thx for answer)
  • Have you try to iterate through max ? I think this did not throw, because you have not iterated through the result of your request (Linq launch your request only after the first call to GetEnumerator.

    The ToArray method iterates throught the enumerable of your request, and copy every thing in an array. I think it's the difference.

Judy array for managed languages

Judy array is fast data structure that may represent a sparse array or a set of values. Is there its implementation for managed languages such as C#? Thanks

From stackoverflow
  • This is proving trickier than I thought. PyJudy might be worth a look, as would be Tie::Judy. There's something on Softpedia, and something Ruby-ish. Trouble is, none of these are .NET specifically.

  • It's worth noting that these are often called Judy Trees or Judy Tries if you are googling for them.

    I also looked for a .Net implementation but found nothing. Also worth noting that:

    The implementation is heavily designed around efficient cache usage, as such implementation specifics may be highly dependent on the size of certain constructs used within the sub structures. A .Net managed implementation may be somewhat different in this regard.

    There are some significant hurdles to it that I can see (and there are probably more that my brief scan missed)

    • The API has some fairly anti OO aspects (for example a null pointer is viewed as an empty tree) so simplistic, move the state pointer to the LHS and make functions instance methods conversion to C++ wouldn't work.
    • The implementation of the sub structures I looked at made heavy use of pointers. I cannot see these efficiently being translated to references in managed languages.
    • The implementation is a distillation of a lot of very complex ideas that belies the simplicity of the public api.
    • The code base is about 20K lines (most of it complex), this doesn't strike me as an easy port.

    You could take the library and wrap the C code in C++/CLI (probably simply holding internally a pointer that is the c api trie and having all the c calls point to this one). This would provide a simplistic implementation but the linked libraries for the native implementation may be problematic (as might memory allocation). You would also probably need to deal with converting .Net strings to plain old byte* on the transition as well (or just work with bytes directly)

  • Judy really doesn't fit well with managed languages. I don't think you'll be able to use something like SWIG and get the first layer done automatically.

    I wrote PyJudy and I ended up having to make some non-trivial API changes to fit well in Python. For example, I wrote in the documentation:

    JudyL arrays map machine words to machine words. In practice the words store unsigned integers or pointers. PyJudy supports all four mappings as distinct classes.

    • pyjudy.JudyLIntInt - map unsigned integer keys to unsigned integer values
    • pyjudy.JudyLIntObj - map unsigned integer keys to Python object values
    • pyjudy.JudyLObjInt - map Python object keys to unsigned integer values
    • pyjudy.JudyLObjObj - map Python object keys to Python object values

    I haven't looked at the code for a few years so my memories about it are pretty hazy. It was my first Python extension library, and I remember I hacked together a sort of template system for code generation. Nowadays I would use something like genshi.

    I can't point to alternatives to Judy - that's one reason why I'm searching Stackoverflow.

    Edit: I've been told that my timing numbers in the documentation are off from what Judy's documentation suggests because Judy is developed for 64-bit cache lines and my PowerBook was only 32 bits.

    Some other links:

    The last has comparison numbers for different high-performance trie implementations.

History visualization tools for version control systems?

Specifically, I'm looking for something that, given a single file, and an SVN history, will display insertions and deletions as a pretty animation.

That said: I figure that a list of version control visualizers might be a useful resource.

From stackoverflow
  • I am not sure about pretty, but codeswarm is certainly one of the most impressive "commit history visualization" tool I have ever seen.

    alt text

  • Most of the VCS have a web or GUI interface such as gitk, hgk and so on. It shows the various "branches" and "merges" along the life of the repo but if you want something prettier then codeswarm is your answer :)

  • In a more practical way, you may also consider SVN Time-Lapse View

    SVN Time-Lapse View is a cross-platform viewer that downloads all revisions of a file and lets you scroll through them by dragging a slider.
    As you scroll, you are shown a visual diff of the current revision and the previous revision.
    Thus you can see how a file evolved, and you can easily find the revision at which lines appeared, disappeared, or changed.

    (not big on "animation", but still, can be useful)

  • http://code.google.com/p/gource/ looks very pretty

In Ruby why does nil.id return 4?

This is has been bugging me for quite some time.

>> nil.id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 4

Why would nil.id be 4? (or nil.object_id if you want to be picky about deprecations)

From stackoverflow
  • This post seems to have some information about how object_id works.

    Keltia : This is a useful link, I don't know why it vwas downvoted. +1
    epochwolf : Down voted probably because the person felt that this belonged in the text of my question. Which would be a valid point but downvoting without a comment doesn't get that across :)
  • This is because nil is an object created when the language initializes, and that object's id happens to always be 4.

    For more information about why the id happens to be 4, see this blog post.

  • It happens because the id of every object had to somehow be represented in the C Ruby interpreter. Numbers got mapped to (number*2)+1, truthiness got 0, falseness got 2 and nil had 4 left. It´s just a weird implementation issue or leaky abstraction. You shouldn't worry about it unless you want to write a Ruby interpreter.

  • I'd always assumed it was a cool easter egg: In Japan 4 is the number of death.

Can I have nested try-catch blocks in C++?

Can I have nested try-catch blocks? For example:


void f()
{
    try
    {
        //Some code 
        try
        {
             //Some code 
        }
        catch(ExceptionA a)
        {
            //Some specific exception handling
        }
        //Some code
    }
    catch(...)
    {
        //Some exception handling
    }
}//f
From stackoverflow
  • Yes, you can.

  • Yes perfectly legal.

    Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller

  • As already stated, it is possible, but you have to see the 'fall-through'-scheme in this. If in the first try-catch-block your exception is caught, it will not get caught by the outer catch-block. However if it does not get caught by the inner catch-block, it will try to find a matching exception-handler in the outer catch-block.

    You can also explicitely raise the exception further to the next exception-handler by using throw; in your inner exception-handler.

    For example this code:

    try
    {
        try
        {
            throw std::runtime_error("Test");
        }
        catch (std::runtime_error& e)
        {
            std::cerr << "Inner Exception-Handler: " << e.what() << std::endl;
            throw;
        }
    }
    catch (std::exception& e)
    {
        std::cerr << "Outer Exception-Handler: " << e.what() << std::endl;
    }

    Will result in:

    Inner Exception-Handler: Test
    Outer Exception-Handler: Test

    This works because std::runtime_error is derived from std::exception. You should also note that in such a trivial example it is also possible to just write the catch-blocks after each other, but if you want to execute other code after the first catch-block you will have to nest them.

  • Its legal but its not all that useful unless you are throwing an exception from your inner catch(). For example, you might want to catch a system level exception but throw your own exception object for code clarity.

    MSalters : It IS useful if the outer catch handles a different set of exceptions
  • Yes, that's legal. As ouster said, one way to deal with it is to put the inner try-catch block in its own function and call that function from your outer try-catch block.

    Another way to handle it is with multiple catch blocks.

    void f()
    {
        try
        {
            //Some code that throws ExceptionA
            //Some code that throws ExceptionB
        }
        catch(ExceptionA ea)
        {
            //Some exception handling
        }
        catch(ExceptionB eb)
        {
            //Some exception handling
        }
    }//f
    

    The thing to be careful of here is the specificity of the exception types in your catch blocks. If ExceptionB extends ExceptionA in the example above, then the ExceptionB block would never get called because any ExceptionB that gets thrown would be handled by the ExceptionA block. You have to order the catch blocks in most specific to least specific order when dealing with Exception class hierarchies.

How to exclude a specific CSS file from an ASP.NET Theme?

I'm making a website that will have to render correctly on FF/IE6/IE7/Opera/Safari. IE6 came as a late requirement (when I had done all the other browsers) and it just has to be useable, not necessarily the same as on the other browsers. Now I'm tweaking it so that it's useable on IE6 as well.

To this end I've created another stylesheet in my theme called IE6_override.css. As you might have guessed, I want it to be applied only when the browser is IE6. Conditional comments would perfect for this.

The only problem is - ASP.NET renders a <link> tag for every CSS file that is in the theme's folder, thus including this file unconditionally on all browsers.

I would like to stick to themes because it's completely feasible that we might create more skins for our application later (if the customers desire that).

Is there any way how I can make ASP.NET exclude this specific .CSS file from its auto-including?

Added: Thank you for your answers! In the end I found a workaround. Due to some other styling problems I've asked about earlier, I'm forced to have a IE6-workaround Javascript as well. Thus I prefixed all my IE6-specific rules with a .ie6_dummy class selector and then removed it in JS upon page loading. :)

From stackoverflow
  • I don't think you can. We stopped using the App_Themes folder for exactly that reason. This also saved us having to prefix every css file with a number so they load in the right order.

  • Indeed it's not possible to exclude a specific CSS file. However, there seem to be several workarounds located here. I'd suggest reading through those and choosing an appropriate solution (if any).

  • There are a couple of posts out on the web which seem to address your problem - looking for "Conditional comments in asp.net themes" I came across these which look like they may help:

    1. How to take control of style sheets in ASP.NET Themes with the StylePlaceholder and Style control
    2. Conditional stylesheets in Themes - note that the design templates refered to have moved to here

    The first one will also address the media issue with theme stylesheets as well.

How would you design OO classes to handle cryptosystems and their keys

This a wider question than my previous one but related.

I want to implement oldish crypto systems in Ruby such as ADFGVX, VIC cipher and others, mostly for fun. These cryptosystems are built on top of more general systems like substitution (monoalphabetic such as Caesar or polyalphabetic like Vigenere) and transposition (simple, double). My question is really how would you create a hierarchy of classes to handle both cryptosystems and keys.

Something like Vigenere < Substitution < SimpleCipher or something else? How about keys? Some substitution keys are condensed before use ("ARABESQUE" becomes "ARBESQU") whereas most transposition keys are not and so on.

Right now, I have a very basic design doc (I said basic) and as I think about it, I can't seem find a satisfying way for this, so I come here for your wisdom.

Implementation will be in Ruby but unless the design must use multiple inheritance, it is not about Ruby itself.

Proof of concept (not yet runnable and possibly wrong) here in Mercurial.

Thanks.

From stackoverflow
  • Think about the class signatures. Every crypto algorithm is going to have two methods, encrypt() and decrypt(), and you have to consider block and streaming ciphers (ie, many algorithms want data in fixed size blocks.)

    Once you're below that level, though, the methods are going to look fairly radically different, and there's not a whole lot of shared behavior at that level.

    So I suspect what you want is more of a module or mixin structure, not inheritance. Just because you have a taxonomy, it doesn't mean that taxonomy should be an inheritance hierarchy.

    There's a lot of good discussion on this sort of thing; look for talk about whether Ostrich < Bird. See, Birds fly() ... except for Ostriches.

    Keltia : Thanks Charlie, I guess I always forget about mixins. Although it this case, I have the feeling that there is code to share because the building blocks are mostly the same for these old systems (subst, transp, checkerboards and so on).
    Charlie Martin : Yup, could well be. You might think then about if you need a module that provides crypto algorithms and contains or mixes in cryptographic primitives. Have a look at the Cryptol language: http://galois.com/technology/communications_security/cryptol

How do you turn off or replace the default ModelState error message in Asp.net MVC?

I have a controller action which has a nullable DateTime as one of the parameters which comes from a textbox on my form. I noticed that if the user were to type in "blah" in that textbox then I will get a Null value back for the DateTime param and a model error is automatically added. In this case the ModelState error that is added is "The value 'blah' is not valid".

My problem is that my site supports multiple languages and so I need to localize this error. Normally I just validate and add the ModelState errors myself but in this case I can't seem to get rid of it. If I add another ModelState error for the same textbox it does not show up.

From stackoverflow
  • I would remove that particular textbox from the whitelist you pass to TryUpdateModel/Update model and validate it "by hand," rather than having it get validated by the framework. Alternatively, you could try iterating through the ModelState Error collection, find the one you want to remove, and delete it -- say using RemoveItem once you figure out which one you want to get rid of.

    EDIT: If you are using the default ModelBinder, you could implement your own. I was assuming that since you were generating your own model errors, you were using TryUpdateModel/UpdateModel.

  • I could call ModelState.Clear(); at the start of the action. But, I'm not sure I like having to do that in each action.

  • You could make the DateTime parameter nullable. Then if nothing is supplied the error will not be added to ModelState.

    public ActionResult Method(Datetime? date)
    {}
    

    rather than

    public ActionResult Method(Datetime date)
    {}
    
  • I have to strongly disagree with all of the answers you have received so far. None of them actually answer the question you asked, which is how to localize the MVC error messages. You could spend a lot of effort working around this single instance of the problem, and still have the same problem with the 50 other cases of MVC error messages if you don't actually localize your application. They are defined in MvcResources.resx, which is found in the Resources folder of the MVC source code (or just browse the assembly with Reflector). In particular, you are looking for the Common_ValueNotValidForProperty resource. You would localize these messages by providing a localized satellite assembly, in the same way that you localize any .NET application. The specifics of internationalization/localization in .NET applications are outside of the scope of this answer, but there are many books on the subject. Doing this in MVC is no different than doing it in any other application, except that, in most cases, localizations of the framework are already available. MVC is still in beta, so it is, as far as I know, English-only, at the moment. Presumably, that will change after release.

  • Hi having same problem the errors are being added by the framework and I'm using EntLib VAB. The issue is thate the properties are nullable and if the vallue "abc" is added into an int the message is automatically added to the modelstate and therefore shows up in validationsummary. I'm on MVC 2 RC2 and am wondering how to go about disabling the default behavior and adding my own messages and not the default ones. Like I said making it nullable does not seem to work.

Why is two-way binding in silverlight not working?

According to how Silverlight TwoWay binding works, when I change the data in the FirstName field, it should change the value in CheckFirstName field.

Why is this not the case?

ANSWER:

Thank you Jeff, that was it, for others: here is the full solution with downloadable code.

XAML:

<StackPanel>
    <Grid x:Name="GridCustomerDetails">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="300"/>
        </Grid.ColumnDefinitions>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="0" Grid.Column="0">First Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="0" Grid.Column="1" Text="{Binding FirstName, Mode=TwoWay}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="1" Grid.Column="0">Last Name:</TextBlock>
        <TextBox Margin="10" Grid.Row="1" Grid.Column="1" Text="{Binding LastName}"/>

        <TextBlock VerticalAlignment="Center" Margin="10" Grid.Row="2" Grid.Column="0">Address:</TextBlock>
        <TextBox Margin="10" Grid.Row="2" Grid.Column="1" Text="{Binding Address}"/>

    </Grid>

    <Border Background="Tan" Margin="10">
        <TextBlock x:Name="CheckFirstName"/>
    </Border>

</StackPanel>

Code behind:

public Page()
{
    InitializeComponent();

    Customer customer = new Customer();
    customer.FirstName = "Jim";
    customer.LastName = "Taylor";
    customer.Address = "72384 South Northern Blvd.";

    GridCustomerDetails.DataContext = customer;

    Customer customerOutput = (Customer)GridCustomerDetails.DataContext;
    CheckFirstName.Text = customer.FirstName;

}
From stackoverflow
  • Your Customer type has to support INotifyPropertyChanged in order for the binding to know when your FirstName property value has changed.

    This tutorial may help you in getting your code to work.

    carlmon : You could also derive from `DependencyObject` and make `FirstName` a dependency property. Jeff's solution is more appropriate, but you have the two choices.
    Jeff Yates : @carlmon: Good point, that is an alternative approach to get this working.
  • Just noticed that the link to the tutorial in Jeff's answer is broken. Here's the new one: http://www.silverlight.net/learn/tutorials/databinding-cs/

What are some CSS bugs in IE?

I've found some references to bugs or issues in IE's interpretation of CSS, but the information seems rather scattered. I'd like to have a pointer to a comprehensive overview, if such an overview exists.

edit: it's already something that Microsoft is willing to list IE's CSS problems (thanks mouviciel->sanchothefat), but they're not going to offer workarounds, obviously. So workarounds would be nice too.

Thanks

From stackoverflow
  • I find myself constantly referring to this page:

    http://www.webcredible.co.uk/user-friendly-resources/css/internet-explorer.shtml

  • Check out Quirks Mode. It is a great resource for CSS compatibility across browsers.

  • You may find some answers by consulting this SO question.

  • For dropdownlists:

    <select>
        <option value="1">1</option>
        ...
        <option value="N">N</option>
    </select>
    

    CSS border styles do not work:

    If you'll try:

    select
    {
        border: solid 1px #0000ff;
    }
    

    nothing will happen.

    Also a submit button will expand its width proportionally to the button text, until you give it the style:

    input[type="submit"]
    {
    overflow:visible;
    }
    

    As well as many other funny things. :)

    dfa : input[type="submit"] is not working on IE8
    User : @dfa: Just checked it again, everything is working, in both IE8 and compatibility mode.
  • I find the best policy to avoid pain is to follow these rules:

    1. Build in a more-compliant and developer-friendly browser like firefox first, test thoroughly in IE (and safari/chrome(webkit) and opera) later
    2. Use a strict doctype- avoid quirks mode, since quirks are by definition not standard
    3. Use a reset style sheet
    4. Use a javascript framework like jQuery or Prototype - they can hide some javascript and DOM incompatibilities.
    5. Use good semantic layout- it's more likely to degrade nicely for a mis-behaving browser
    6. Accept that it won't be perfect and don't sweat the really small variances

    Follow those rules I don't have as many problems in the first place.

  • Me, I use the "Internet Explorer Exposed". Very in-depth resource.

  • quirksmode has already been posted, but I'll add On having layout, which explains one of the principles underlying many of IE's oddities.

  • I swear by PositionIsEverything.

    They maintain a list of bugs/oddities in most browsers. Check out their exhaustive list of Internet Explorer bugs, I hope you find it comprehensive enough.

Project Server Error when trying to update a timesheet

I am trying to integrate MS CRM 4.0 and Project Server. I have a custom workflow from CRM that is trying to update timesheets and create line entries. When the code hits the QueueUpdateTimesheet project server then gets a Failed and Blocking Correlation with the error

There has been an error processing a timesheet for which you are/were responsible. Check your approvals list to locate the offending timesheet if one exists. The error condidtion may be related to the fact that Timesheets are a state driven feature; therefore, the allowable values for processing are dependent upon the existing value which for this transaction was 0. Refer to the documentation to determine which status transitions are allowable and submit the transaction. TimesheetIncorrectMode Queue GeneralQueueJobFailed

Anyone have any idea how to fix this? Thanks

From stackoverflow
  • I had the same problem... try to restart the message queue service. It work for me ...

  • Hi

    I had the same problem. Did you resolve it ?

How to use a BGL directed graph as an undirected one (for use in layout algorithm) ?

Hi

I am working on a directed graph (actually a bidirectional one) with Boost.Graph. I'd like to use the layout algorithms that exist (either Kamada-Kawai or Fruchterman-Reingold) but they only accept undirected graphs as parameters.

What is the simplest way to use these layout algorithms ? More generally, what's the right way to lure an algorithm into thinking that a directed graph is actually undirected ?

Thanks, Benoît

From stackoverflow
  • Are you sure that Fruchterman-Reingold algorithm only accepts undirected graphs? I tried to run the little example from the Boost documentation using a bidirectional graph instead of an undirected one, and it compiled and ran just fine.


    To answer your question, I'm not sure there is any facilities built into the BGL to convert a directed graph to an undirected one. The only solution I found is creating a new graph and adding all the edges from the original one:

    typedef adjacency_list<vecS, vecS, bidirectionalS> BidirectionalGraph;
    typedef adjacency_list<setS, vecS, bidirectionalS> UndirectedGraph;
    // UndirectedGraph uses a set to avoid parallel edges
    
    BidirectionalGraph bdg;
    // use bdg
    
    // create an undirected graph with the edges of the first one
    typedef graph_traits<BidirectionalGraph>::vertex_iterator vi_beg, vi_end;
    tie(vbeg, vend) = vertices(bdg);
    
    UndirectedGraph ug(std::distance(vbeg, vend));
    
    typedef graph_traits<BidirectionalGraph>::edge_iterator ei, ei_end;
    
    for (tie(ei, ei_end) = edges(bdg) ; ei != ei_end ; ++ei)
    {
        add_edge(source(*ei,bdg), target(*ei,bdg), ug);
    }
    

    However, I guess this solution might raise some performance issue when dealing with huge graphs. There may be a better way to achieve your goal, but I'm not an expert in BGL, so that's all I can give you :-)!


    As Benoît pointed in a comment, the BGL provide a function copy_graph that copies all the vertices and edges of a graph into another one. Therefore, the code above can boil down to this:

    #include <boost/graph/copy.hpp>
    
    Bidirectional bdg;
    // use bdg
    
    // create an undirected graph with the vertices and edges of the first one
    UndirectedGraph g;
    copy_graph(bdg, g);
    
    Benoît : The documentation says it is not designed for this, but i guess i should have tried ! I am still interested in the answer though, because such a need will probably come back up
    Benoît : Thanks. That's all i came up with as well. I just hoped there would be some kind of adapter for that. Anyway. I'll mark your answer as "accepted" as soon as you'll have used copy_graph :-)
    Luc Touraille : You're right, I totally missed this function! I edited my answer to include that.

Using Awstats for generating usage statistics for a Liferay portal

Has anyone tried to use Awstats for generating usage statistics for a Liferay portal?

Can you share your experience on how to do it?

Aside from Awstats and Google Analytics, are there any other alternatives for generating statistics for a Liferay portal? (I can't use Google Analystics since it's a restricted internal portal)

From stackoverflow
  • I have never used a Liferay portal, but setting up AWstats is dead easy. Assuming you are running Apache on Debian, just apt-get install awstats and copy the default config file in the /etc/awstats/ to a new file for your vhost. All you need to edit are the LogFile, SiteDomain, HostAliases and DirData folders. And you need to enable mod_perl, obviously.

    I recently set it up on my own site, and found this post by Sami Dalouche to be really helpful. I also blogged about how to set it up for Nginx logs.

  • Your best bet would be to use Awstats to parse the web server logs (Apache, IIS or whatever it is running on). If Liferay creates it's own logs, you can configure Awstats to parse custom log formats. See here for tips on reading custom logs:

    http://awstats.sourceforge.net/docs/awstats_faq.html

  • As a side note, there shouldn't be a great deal of issue using Google Analytics internally (if I understand your scenario correctly). If the users when visiting your internal-only webpage have access to the internet, the Google Analytics code should still fire and log a stat. (As the code is running on the client - its only them than need access to the internet). We use this setup where I work to monitor user stats for our Intranet just fine.

    With regards to AWStats. I've had quite a large amount of success with it parsing the Apache log files. The extra info in GA is quite useful though at times to grasp your demographic and average settings for user pc's.

Removing all \n\r characters from a node XSLT?

Hi

wondered if you could help me please? I have node in xml that is as followed

$LOG: 08880xbpnd $
fhdsafidsfsd
df
sd
fsd
f
sd
fsd

I was wondering is there anyway to make all the text go on to one line so that it then can be passsed through to a javascript function? so it would turn out like this

$LOG: 08880xbpnd $fhdsafidsfsddfsdfsdfsdfsd
From stackoverflow
  • The normalize-space() XPath function should do what you want.

    Dimitre Novatchev : Unfortunately, the normalize-space() function (used in the answer of andynormancx) does more than deleting newlines. It deletes all leading and trailing whitespace and it replaces any group of inner contigious whitespace with a single space character. A better solution is to use translate()
    andynormancx : Fair enough, but on the plus side the questions example didn't have any whitespace ;)
  • Unfortunately, the normalize-space() function (used in the answer of andynormancx) does more than deleting newlines.

    It deletes all leading and trailing whitespace and it replaces any group of inner contigious whitespace with a single space character.

    In many cases we want to deleteonly one type of a white-space character (as in the current case -- new lines (CR+LF is automatically normalized on reading by the XML parser to just LF).

    The correct and safe way to do so is by using the standard XPath translate() function:

    translate(., '&#xA;', '')
    

    returns a string obtained from the string-value of the current node in which any newline character is deleted.

    Here is an example:

    <xsl:stylesheet version="1.0" 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
      <xsl:template match="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="text()">
        <xsl:value-of 
         select="translate(.,'&#xA;','')"/>
      </xsl:template>
    </xsl:stylesheet>
    

    When the above transformation is applied on this source XML document:

    <t>
    $LOG: 08880xbpnd $
    "embedded    blanks    must    stay"
    df
    sd
    fsd
    f
    sd
    fsd
    </t>
    

    The result is on one line only, as required, and all embedded spaces are left intact:

    <t>$LOG: 08880xbpnd $"embedded    blanks    must    stay"dfsdfsdfsdfsd</t>
    
    andynormancx : +1 definitely a better solution, if you need the inner whitespace preserved.

SSH, entered command but it didn't execute, can't type anything

I used the command tar -x file.tar.gz and, for one reason or anything it failed. Then I get stuck being able to type anything in, but not being able to run any more commands. Pressing enter just gives me a new line. I don't know how to break out of it either (escape etc doesn't work). The only way I can get back working is to close putty and reconnect.

Is there a way to get it back to normal so I can keep going because it's irritating closing it all the time.

From stackoverflow
  • Try hitting CTRL+C :) This will cancel/kill/stop the running command!

    But the best way to untar is to use -v to verbose the output :

    tar -zxvf yourfile.tar.gz
    

    With that, you'll perhaps see that your file just take more time than you thought unarchiving ;)

    damnitshot : Ooo thankyou very much :D
  • If you want to quit it, press CTRL+c. If you want to keep it but being able to write more commands while it's working, press CTRL+z and bg. Then it will work in the background.

  • Ctrl-C can be used to send a break to the executable that's hanging, but it's up to the application to handle it. Ctrl-Z will break you out of the running executable, but you'll need to then manually kill the process.

    What you're doing wrong is you're not gunzipping the archive.

    Try this

    tar -zxf file.tar.gz

  • Your command failed because it is trying to read stdin. This is because you never told it the name of the tar file with an "f" option.

  • A good Idea would be to use GNU screen. That way, when a command hangs, you can open another screen and take a look at the system (e.g. top to see if tar is still working) or you could kill the process by pressing (strg+a) + k to hard-kill the running process within the screen-session. Screen also has the nice feature that your processes keep running even though your SSH-connection died. It's a lifesaver!

  • Your tar invocation is waiting for input on the command line as the others pointed out. You may also use Ctrl-D to indicate EOF to the tar process.

Does the word "Webservice" imply a specific format?

Bare with me if this question is plain stupid...

When I talk to an developer from the Microsoft ASP.NET world and he uses the word "Webservice", does that word in every case imply a specific data format (XML? SOAP?)?

Or is it just anything you can call via http(s)?

From stackoverflow
  • The term Webservice itself is language-agnostic.

    This is a decent overview.

  • In my view, it can be anything that's over http/https, and intended for calling by an application rather than a user's browser.

    In particular, REST and SOAP are quite different about how they pass arguments in and get results back

  • If an Asp.Net developer says WebService, you can pretty much bet that they are talking about XML/SOAP.

    However this is not universally true. I think it's just fine to call anything a WebService if 1) the data source is available via the web or 2) it is a web address that can provide back information given a set of inputs.

    For example, StackOverflow.com allows for screen scraping of the User pages in order for 3rd party applications to be built. It's not specifically XML/SOAP but I would consider it a Web Service (format #1)

    Martin Brown : I think it would also need to have a response that was in a defined format designed to be easily read by a piece of software. I'm not sure scrapping a sites HTML counts.
    JaredPar : @Martin, I believe it does as long as the web site specifically supports such an action. They are offering a format (not well defined but still a format) by which you can garner data about a site.
  • In my experience this completly depends upon who you are talking to. For some ASP.Net developers this is only SOAP for others it includes other things like REST. If you are planning on using the term in a specification it would be a good idea to be a bit more specific.

  • I can only agree with Paul, anything queried over the web, using the http(s) protocol and not browser oriented. But any web service should also have the functionality of being discovered (WDSL and so on).

ASP.NET: generate property value when adding control to page

Context: ASP.NET 3.5 / C#

Hi,

I created a user control

public partial class MyControl : UserControl
{
    // EDIT: example first used "UniqueId" as property name, which was wrong.
    public Guid MyId { get; set; }
    // ...
}

and this example usage

<uc1:MyControl 
    ID="myControl" 
    MyId="443CBF34-F75F-11DD-BE2F-68C555D89123"
    runat="server" />

Steps:

  • Add this control to a web form (aspx)

Expected result:

  • the HTML for the user control is added, a unique value (corresponding to Guid.NewGuid()) for MyId is set in the ASPX HTML at design-time as the MyId attribute value.

Actual result:

  • the HTML for the user control is added, a unique value for MyId is not set in the HTML at design time for the MyId Attribute value.

If this is not possible:

  • Workaround 1: Would it be possible to achieve this using a server control? How?
  • Workaround 2: is it possible to achieve this using a UserControl design-mode task?

Clarification:

  • persisting the property value is not an issue, since it never changes for a control intance and is automatically set by ASP.NET through the control declaration in the aspx page.
  • the MyId attribute does not need to be rendered at runtime.

Gr B!

From stackoverflow
  • You have a couple problems here, but first I will answer your questions about the workarounds.

    1. No you are already using a server control.
    2. No design-mode is to just make the lives of the developer easy, it doesn't effect anything else

    You have two problems here. There is already a property called UniqueID I don't know if you were trying to overload that, but the question wasn't clear. The second problem is that your UniqueID essentially not getting stored anywhere. Try the following code:

    public Guid UniqueId {
        get { return (Guid)ViewState["MyUserControlUniqueId"]; }
        set { ViewState["MyUserControlUniqueId"] = value; }
    }
    

    That will store the GUID in the ViewState so that you can retrieve it on post backs.

    Update: Given your comment you need to override/use this method to add attributes to the rendered content.

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.addattributestorender.aspx

    Bernard Vander Beken : Hi Nick, I had renamed the original property to UniqueId for the example code, it was not my intention to override UniqueId. ViewState is not my issue, the goal is to make the new GUID appear in the generated HTML.
    Nick Berardi : See comment above.
    Bernard Vander Beken : Thanks for the update, I was not clear enough. My goal is to have a different GUID in the *ASPX* design time HTML every time a control is dragged to a web page by the page designer. The attribute does not need to be added to the rendered HTML.
  • If I understand your question correctly, you are exposing a property on your user control called MyId. This allows you to set the property wherever you put that control.

    What you also want, is for the rendered HTML to also include this attribute and value.

    If that's the case, the property MyId is not passed through to the HTML, it's only because the user control has MyId as a property that it's visible in the designer.

    In your user control you will have defined the markup that gets rendered. So for example if you have:

    <asp:Panel runat="Server" Id="myControlDiv">Some other content</asp:Panel>
    

    You can then in your controls prerender event (or wherever else you choose) put

    myControlDiv.Attributes.Add("MyId", SomeGuid.ToString())
    

    Which will then get output in the HTML as

    <div id="generatedID" MyID="443CBF34-F75F-11DD-BE2F-68C555D89123">Some other content</div>
    
    Bernard Vander Beken : tnx for your reply. "What you also want, is for the rendered HTML to also include this attribute and value." I can see why you got this impression now, but this was not my intention. By HTML I meant the design time HTML in the aspx.
  • So you just want a unique ID generated that you only ever use in design time?

    Why not override Object.GetHasCode();

    And then exposure this as a property?

  • Did you ever figure this out?

    Bernard Vander Beken : No, I never did and learned to live with it ;)
  • Custom Design-time Control Features in Visual Studio .NET

C#, Linq2SQL: Creating a predicate to find elements within a number of ranges

Lets say I have something called Stuff in my database, with a property called Id. From the user I get a sequence of selected Range objects (or rather I create them from their input) with the Ids they want. A stripped down version of that struct looks like this:

public struct Range<T> : IEquatable<Range<T>>, IEqualityComparer<Range<T>>
{
    public T A;
    public T B;
    public Range(T a, T b)
    {
        A = a;
        B = b;
    }
    ...
}

So one could for example have gotten:

var selectedRange = new List<Range<int>>
    {
        new Range(1, 4),
        new Range(7,11),
    };

I then want to use that to create a predicate to select only things which have a value between those. For example, using the PredicateBuilder, I can for example do that this way:

var predicate = PredicateBuilder.False<Stuff>();
foreach (Range<int> r in selectedRange)
{
    int a = r.A;
    int b = r.B;
    predicate = predicate.Or(ø => ø.Id >= a && ø.Id <= b);
}

and then:

var stuff = datacontext.Stuffs.Where(predicate).ToList();

Which works! What I would like to do now, is to create a generic extension method to create those predicates for me. Kind of like this:

public static Expression<Func<T,bool>> ToPredicate<T>(this IEnumerable<Range<int>> range, Func<T, int> selector)
{
    Expression<Func<T, bool>> p = PredicateBuilder.False<T>();
    foreach (Range<int> r in range)
    {
        int a = r.A;
        int b = r.B;
        p = p.Or(ø => selector(ø) >= a && selector(ø) <= b);
    }
    return p;
}

Problem here, is that it crashes with a NotSupportedException because of the selector(ø) call: Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.

I guess that is understandable. But is there any way to get around this? What I would like to end up with is so that I could just do:

var stuff = datacontext.Stuffs.Where(selectedRange.ToPredicate<Stuff>(ø => ø.Id));

Or even better, create something that returns an IQueryable so that I could just do:

var stuff = datacontext.Stuffs.WhereWithin<Stuff>(selectedRange, ø => ø.Id); // Possibly without having to specify Stuff as type there...

So, any ideas? I would really like to get this working, cause if not I will get A LOT of those foreach blocks of code, creating predicates...


Note 1: Of course, would be nice if I could expand to more than int, like DateTime and such, but not sure how that ends up with using the >= and <= operators... Does CompareTo work with linq-to-sql? If not there is no problem creating two. One for int and one for DateTime, since that is mostly the types this will be used for.

Note 2: It is going to be used for reporting, where the user is going to be able to narrow down what comes out, based on different things. Like, I want this report for those people and those dates.

From stackoverflow
  • The use with generics is problematic, since C# doesn't support operators on generics - meaning you'd have to write the expression manually. And as we've already seen, string works differently. But for the rest, how about something like (untested):

    (edited for multiple ranges)

        public static IQueryable<TSource> WhereBetween<TSource, TValue>(
            this IQueryable<TSource> source,
            Expression<Func<TSource, TValue>> selector,
            params Range<TValue>[] ranges)
        {
            return WhereBetween<TSource,TValue>(source, selector,
                (IEnumerable<Range<TValue>>) ranges);
        }
    
        public static IQueryable<TSource> WhereBetween<TSource, TValue>(
            this IQueryable<TSource> source,
            Expression<Func<TSource, TValue>> selector,
            IEnumerable<Range<TValue>> ranges)
        {
            var param = Expression.Parameter(typeof(TSource), "x");
            var member = Expression.Invoke(selector, param);
            Expression body = null;
            foreach(var range in ranges)
            {
                var filter = Expression.AndAlso(
                    Expression.GreaterThanOrEqual(member,
                         Expression.Constant(range.A, typeof(TValue))),
                    Expression.LessThanOrEqual(member,
                         Expression.Constant(range.B, typeof(TValue))));
                body = body == null ? filter : Expression.OrElse(body, filter);
            }            
            return body == null ? source : source.Where(
                Expression.Lambda<Func<TSource, bool>>(body, param));
        }
    

    Note; the use of Expression.Invoke means it will probably work on LINQ-to-SQL but not EF (at the moment; hopefully fixed in 4.0).

    With usage (tested on Northwind):

    Range<decimal?> range1 = new Range<decimal?>(0,10),
                    range2 = new Range<decimal?>(15,20);
    var qry = ctx.Orders.WhereBetween(order => order.Freight, range1, range2);
    

    Generating TSQL (re-formatted):

    SELECT -- (SNIP)
    FROM [dbo].[Orders] AS [t0]
    WHERE (([t0].[Freight] >= @p0) AND ([t0].[Freight] <= @p1))
    OR (([t0].[Freight] >= @p2) AND ([t0].[Freight] <= @p3))
    

    Just what we wanted ;-p

    Svish : How would that work with a whole series of Range objects?
    Marc Gravell : You could do the same with OrElse... I'll update...
    Svish : And what is this "x" in your param?
    Marc Gravell : An expression parameter needs to be named. If we had written the lambda by hand, it would be the "x" in "x => x.Val < 1 && x.Val > 2" - it simply relates to the row being processed. Maybe call it "row" if it would bother you less ;-p
    Svish : aha. cool. no, no, I just didn't know what it was for :p Would what you now changed it with work with an IEnumerable> as well as a Range[] ?
    Svish : and a foreach, instead of the for(int i... stuff?
    Marc Gravell : yes - foreaach would do the job... (another update coming)
    Svish : It works :D Thank you! This was fun... :D
  • You are getting that error, because everything for LINQ to SQL needs to be in the form of an Expression. Try this

    public static Expression<Func<T,bool>> ToPredicate<T>(
        this IEnumerable<Range<int>> range, 
        Expression<Func<T, int>> selector
    ) {
        Expression<Func<T, bool>> p = PredicateBuilder.False<T>();
        Func<T, int> selectorFunc = selector.Compile();
        foreach (Range<int> r in range)
        {
            int a = r.A;
            int b = r.B;
            p = p.Or(ø => selectorFunc(ø) >= a && selectorFunc(ø) <= b);
        }
        return p;
    }
    

    Notice that I compile the selector before using it. This should work with out a hitch, I have used something like it in the past.

    Svish : How I then use the selector? In other words, what do I replace `selector(ø)` with in `p = p.Or(ø => selector(ø) >= a && selector(ø) <= b);`?
    Svish : No, I get the same `Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.` when doing that =/