Friday, May 6, 2011

What does it mean when "virtual" is in "class Foo : public virtual Bar" as opposed to "virtual void frob()"?

What does it mean when "virtual" is in "class Foo : public virtual Bar" as opposed to "virtual void frob()"?

For a given method there are 8 cases stemming from the presence or absence of virtual in the following three locations.

  1. A superclass's functions.
  2. The inheritance chain for this class.
  3. This classes functions.

I think I understand how numbers 1 and 3 interact but number 2 seems redundant. Is it? What am I not understanding?

From stackoverflow
  • That's virtual inheritance, you do it when you know you'll be doing multiple inheritance. That page goes into way more detail.

Basic yet thorough assembly tutorial (linux)?

I want to learn some practical assembly language having just learned the basic concepts in class. Are there any decent books or tutorials (nasm, etc) that would be recommended?

From stackoverflow
  • PC Assembly Language is my favorite resource on assembly programming. It's modern, free, and covers a variety of topics. It uses NASM and the examples are available for Linux (among several other systems).

  • I agree that PC Assembly Language is very good. Other good ones using GAS are:

    Johnd : Professional Assembly Language is a great book, I recommend it, too
  • I recommend the official Intel manuals. You can request the hard copy on Intel's website.

    See http://en.wikipedia.org/wiki/X86_assembly_language#External_links

    * Intel 64 and IA-32 Software Developer Manuals
    * AMD64 Architecture Programmer's Manual Volume 1: Application Programming (PDF)
    * AMD64 Architecture Programmer's Manual Volume 2: System Programming (PDF)
    * AMD64 Architecture Programmer's Manual Volume 3: General-Purpose and System Instructions (PDF)
    * AMD64 Architecture Programmer's Manual Volume 4: 128-Bit Media Instructions (PDF)
    * AMD64 Architecture Programmer's Manual Volume 5: 64-Bit Media and x87 Floating-Point Instructions (PDF)
    

    Some resources from my personal friend, Google:

    • Function calling convention:

    http://unixwiz.net/techtips/win32-callconv-asm.html

    http://www.delorie.com/djgpp/doc/ug/asm/calling.html

    • Brief tutorial

    http://www.csn.ul.ie/~darkstar/assembler/

    • Using SSE

    http://www.neilkemp.us/v4/articles/sse_tutorial/sse_tutorial.html

  • A side question: what is the point in learning assembly just for the heck of it? The thing is, it seems that it would be hard to find a practical application for it, because if you need "low-levelness" you can just write it in pure ol' C.

    Please note, that I am not trying to label your question is useless, on the contrary, I absolutely love coding in assembly languages, even though I haven't done very much of it (yes, sadly it is a bit of a platonic love), - precisely because, it seems, I am unable to find something practical, that can be done in assembly only (after all, if it can be done in C, why use assembly, then?).

    P.S. I am terribly sorry for adding this as an answer, it was too long for a comment :(

  • http://en.wikibooks.org/wiki/X86_Assembly

  • "what is the point in learning assembly just for the heck of it? "

    Because you get to learn HOW the CPU works and get a better understanding of the system. I would say understanding assembler is in itself practical.

  • I would recommend the assembly tutorials page at http://pickatutorial.com

    I hope it helps.

Is there any free java open source application that can monitor website status?

Anyone know any? I need to send in a http request and make sure the http response i got back is not http 500

From stackoverflow
  • You could use httpunit - web-centric unit testing

    John Munsch : But, he's not unit testing. He clearly says that he's monitoring here. Why wouldn't you use a monitoring tool like Big Sister, Hyperic, Monit, etc.?
  • I believe Hyperic HQ meets all of your criteria. It is open source, I believe it is written at least partially in Java, and it is designed to do all kinds of server monitoring.

    It should be able to handle not only the kind of monitoring you requested but other necessary monitoring like memory, CPU usage, and disk space on your servers as well.

  • http-unit or html-unit.

  • If you want to do this yourself, Apache HttpClient is an option:

    GetMethod get = new GetMethod("http://www.stackoverflow.com");
    try
    {
        int resultCode = client.executeMethod(get);
        if (resultCode == 500)
        {
         //do something meaningful here
    
        } // if
    } // try
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        get.releaseConnection();
    }
    
  • While you find it you can use this:

    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.io.IOException;
    
    public class SimplisticMonitor { 
    
        public static void main( String [] args ) throws IOException { 
    
            HttpURLConnection c = ( HttpURLConnection ) 
                          new URL( "http://stackoverflow.com" ).openConnection();
    
            System.out.println( c.getResponseCode() );
        }
    }
    

Rich Faces Tree Control for handheld device

Currently I have a rich tree which works as expected; however the tree itself is not appropriate for small devices where you use your finger for navigation. The arrow that represents the child nodes, and their expansion, is too small. Is there any way to change that graphic, or increase its size?

From stackoverflow
  • Try the icon attribute of the treeNode

  • I discovered that I have to change the style of rich-tree-node-handleicon-expanded and rich-tree-node-handleicon-collapsed.

    .rich-tree-node-handleicon-expanded {
    background-position: top left;
    background-repeat: no-repeat;
    width: 32px;
    height: 32px;
    }

    .rich-tree-node-handleicon-collapsed {
    background-position: top left;
    background-repeat: no-repeat;
    width: 32px;
    height: 32px;
    }

    ChrisAD : Did this solve it? It looks like it should. You can find all the information you need about editing the css here: http://www.jboss.org/file-access/default/members/jbossrichfaces/freezone/docs/devguide/en/html/tree.html

How do I switch panels inside a frame depending on a button action?

I have created an application that has a toolbar, menubar and content area. I have added the menu and toolbar to the application window, but I am stuck with displaying the panel in content area based on the button action (like add, display) which is clicked through the toolbar. Is this a right way to do this? Is there any better way to do this?

From stackoverflow
  • If I understand correctly, you want to have multiple JPanels, only one of which is shown at a time? If that's the case, it sounds like a CardLayout is what you need. You basically add all your JPanels to it with unique names, and then you can tell the CardLayout which of them to show.

    : thank you, this sounds like good idea and I will give it a try. I never thought of this, i was trying assign a Jpanal variable to a content area pane and then change the value of Jpanel variable on the basis of button pressed.
  • I think CardLayout is probably what you want, but if something like memory usage is a concern and you really want to remove and add a new JPanel/Component, you need to remove the old JPanel and add the new one (with proper constraints and/or index depending on the layout). You'll have to validate() the content pane after you make the switch.

probability and relative frequency

If I use relative frequency to estimate the probability of an event, how good is my estimate based on the number of experiments? Is standard deviation a good measure? A paper/link/online book would be perfect.

http://en.wikipedia.org/wiki/Frequentist

From stackoverflow
  • Probably a chi-squared test is what you want. See, for example, the wikipedia page on Pearson's chi-square test. Standard deviation isn't what you want, since that's about the shape of the distribution, not how accurate you estimate is of the actual distribution. Also, note that most of these things are about "normal" distributions, and not all distributions are normal.

  • I believe you are looking for the confidence interval for a sample proportion. Here are some resources that might be helpful:

    Confidence Interval for Proportion Tutorial
    Confidence Interval for Proportion Handout

    Basically your estimate improves inverse proportionally to the square root of the number of samples. So if you want to cut your error in half you are going to need four times as many samples.

  • You count the number of successes s in a sequence n of Yes / No experiments, right? As long as the single experiments are independent you are in the realm of the Binomial distribution (Wikipedia). Frequency of success f = s / n is an estimator of the success probability p and. The variance of your frequency estimate f is p * (1-p) / n for n draws.

    As long as p is not too close to zero or 1, and as long as you do not have "too small" a number of observations n, the standard deviation will be a reasonable measure for the quality of your estimate f.

    If n is large enough (rule of thumb n * p > 10), you can approximate by a normal distribution N(f, f * (1-f) / n), and standard deviation estimate is a good measure. See here for a more extensive discussion.

    This said the approximation with the standard deviation will not cut any ice if this needs to have some academic rigour (e.g. is a homework).

Fluent NHibernate Classes as code behind for Domain classes

Ok, so I want to create a code behind for non-aspx classes. I have mapping files (classes) that I want to show in project as a code behind for entites. Is there a way to do that in VS2008.

From stackoverflow
  • you can create a designer file by naming it Class.Designer.(vb or cs) and it will show up as a code behind for whatever class you're creating. One of the classes will have to be a partial class, however.

  • It sounds like you're talking about files showing up as nested in Solution Explorer. ASP.NET Codebehind files are just one example of that.

    What you want in the project file is something like this:

    <ItemGroup>
        <EmbeddedResource Include="Resources.resx">
          <Generator>ResXFileCodeGenerator</Generator>
          <LastGenOutput>Resources.Designer.cs</LastGenOutput>
          <SubType>Designer</SubType>
        </EmbeddedResource>
    </ItemGroup>
    <ItemGroup>
        <Compile Include="Resources.Designer.cs">
          <DependentUpon>Resources.resx</DependentUpon>
          <AutoGen>True</AutoGen>
          <DesignTime>True</DesignTime>
        </Compile>
    </ItemGroup>
    

    I believe it's the <DependentUpon> element that indicates the nesting.

  • I actually got this to work. Now all "Map" show as code behind classes for my entities, saves me lot of time when looking up the Mapping for the entity. Here is how it looks in the project file.

    <Compile Include="Entities\OrderMap.cs">
      <DependentUpon>Order.cs</DependentUpon>
    </Compile>
    

    We also created a template so that one can just right click, choose add NH entity and it gets saved to the project as shown above. Only problem right now is re-naming of the entity, one has to go in the project and manually change the name. But that does not happen that often and is a small trade off for gain in the productivity.

Linq to object: ToList can not convert to generic list

Dim tenItem = From t In _InvalidFeeList _
                      From i In ItemCount _
                      Where t.FeeCode <> i.FeeCode _
                      Order By t.Description _
                      Ascending Take (10)


        Dim feeList As List(Of AccessorialFee) = tenItem.ToList()

I am getting "Can not convert to System.generic.list" error. I look all over for this error and it seem like my code should work for example here

I don't get it. Can someone tell me where i got it wrong?

edit: I think i should explain what I'm trying to do here. I want to compare two object list and select the object from the InvalidFeeList if the FeeCode is not equal to the object in ItemCount FeeCode and take the first 10 objects from the InvalidFeeList.

From stackoverflow
  • _InvalidFeeList is not of type List(Of AccessorialFee)

    [Edit] Try this and add a breakpoint and a watch:

    Dim tenItem = (From t In _InvalidFeeList _
                          From i In ItemCount _
                          Where t.FeeCode <> i.FeeCode _
                          Order By t.Description _
                          Ascending Take (10)).ToList().GetType()
    
    Jack : You're correct. Thank
    Jack : I don't think that was it. I do have _InvalidFeeList declare as type of List(Of AccessorialFee)
    hypoxide : See edit above.
    hypoxide : We want to be sure that the tenItem list is actually an AccessorialFee list after the linq has executed.
  • The problem is that you've got two "From" clauses, so the result isn't just the type of the original collection. It's easy to fix though - just add a projection at the end:

    Dim tenItem = From t In _InvalidFeeList _
                  From i In ItemCount _
                  Where t.FeeCode <> i.FeeCode _
                  Order By t.Description _
                  Ascending Take (10) _
                  Select t  ' This is the new line '
    
    Dim feeList As List(Of AccessorialFee) = tenItem.ToList()
    

    EDIT: Are you trying to find items in _InvalidFeeList whose FeeCode isn't present in any item in ItemCount? If so, I suggest this change:

    Dim feeCodes = From i In ItemCount Select i.FeeCode
    Dim feeCodeSet = new HashSet(Of FeeCodeType)(feeCodes)
    
    Dim tenItem = From t in _InvalidFeeList
                  Where Not feeCodeSet.Contains(t.FeeCode)
                  Order By t.Description _
                  Ascending Take (10) 
    Dim feeList As List(Of AccessorialFee) = tenItem.ToList()
    

    As you can see, I didn't know the type of FeeCode, and VB is not exactly my strong point, but I hope you get the general idea. This suggestion is assuming you're using LINQ to Objects - if you're using LINQ to SQL I'm not sure of the best way to do it. Note that we no longer need the Select clause for tenItem as we're only dealing with a single collection now.

    Jack : That was it. Thank you.
    Jack : One problem, the selected t have the same feedcode as i in ItemCount. It didn't select the different object in _InvalidFeeList
    Jon Skeet : The same code as *which* i? You're effectively joining against *all* the values of i in ItemCount. If there are two different values for FeeCode in ItemCount, you'll get every t in _InvalidFeeList_, potentially multiple times. What are you really trying to do?
    Jack : Your assumption is correct. I'm trying to find the item whose FeeCode is not in any item in ItemCount. I'll try your suggestion. Thank a lot. I'll try to be more clear, next time.

Factory Pattern: Enums or Types?

When implementing a factory or simple factory, what would go against using a Type instead of an Enum to specify the class to instantiate?

For example

public class SimpleFactory
{
 public static ITest Create(Type type)
 {
  if (type == typeof(ConcreteTest1))
   return new ConcreteTest1();
  if (type == typeof(ConcreteTest2))
   return new ConcreteTest2();

  throw new Exception("Invalid type");
 }
}
From stackoverflow
  • Using an enum is more restrictive, which means that it is less likely that the user will try to use your factory with an unsupported type.

    I find that it's good to do everything possible when defining an API to discourage usage patterns that will cause exceptions to be thrown. Allowing "Type" in this case opens up millions of ways to call your function that will result in:

    throw new Exception("Invalid type");
    

    Using an enum would eliminate this. The only way an enum would throw would be if the user did something noticably wrong.

    ph0enix : I definitely agree! Compile-time constraints are much easier to enforce and easier to use.
  • if you want a fool proof factory you must create one concrete factory for each concrete type. This class doesn't follow open-closed principle: each time you got a new concrete type you've to re-edit this class.

    IMHO a better approach is using inheritance, one concrete factory class for each concrete type.

  • If you want to create by type, you could just use Activator.CreateInstance(Type t). Wrap it in a template method to limit it to your interface, something like Create<T> where T:ITest.

  • I would prefer to use a generic constraint, for the reason that having an enum just to specify what kind of object you want seems redundant to me, and with using a type as you've described you violate the Open/Closed principle. What I would do differently from what you have done there is constrain your type so that only allowable types can be passed in.

    I'll give an example in c# using generics.

    public class SimpleFactory
    {
     public static ITest Create<T>()
        where T: ITest, new()
     {
        return new T();
     }
    }
    

    Then you would implement IConcreteTest with both ConcreteTest1 and ConcreteTest2 and you could use your factory like this:

    ConcreteTest1 test1 = SimpleFactory.Create<ConcreteTest1>();
    
    ph0enix : How does passing the type to a generic method fix the problem? Doesn't that still require some advanced knowledge of T by the caller?
    Joseph : Yes, but in his example he already knows the type, he's passing it into the method. The only difference is that I'm using it as a generic instead so you can do something like SimpleFactory.Create();
    Rohit : He hasn't given the implementation of typeof, so we can't be sure he has advance knowledge of the types and can pass in to the call.
    Joseph : @Rohit implementation of typeof? typeof is a keyword (http://msdn.microsoft.com/en-us/library/58918ffs(VS.71).aspx) and he does have advance knowledge, otherwise he wouldn't have passed it in as a parameter
    ScottCate : and for sure you'll have advanced knowledge if you're asking about passing in an ENUM
  • I think the biggest concern that I would have is that the purpose of the factory is to allow client code to create a derived instance of an object without knowing the details of the type being created (more specifically, the details of how to create the instance, but if done correctly, the caller should not need to know any of the finer details beyond what is provided by the base class).

    Using type information extracted from the derived type still requires the caller to have some intimate knowledge about which type he wants to instantiate, which makes it difficult to update and maintain. By substituting an Enum type (or string, int, etc.), you can update the factory without having to update the calling code to be aware of the new derived types.

    I suppose one might argue that the type name could be read in as a string from a config file, database, etc., and the type information determined using Reflections (in .NET) or RTTI (in C++), but I think this is a better case for simply using the type string as your identifier since it will effectively serve the same purpose.

  • Factories are only useful if they perform configuration or initialization on your objects to put them in a valid state. I wouldn't bother with a factory if all it does is new up and return objects.

    I would create a factory for each class hierarchy. For example:

    public abstract class Vehicle {}
    public class Car : Vehicle {}
    public class Truck : Vehicle {}
    
    public class VehicleFactory
    {
        public Vehicle CreateVehicle<T>() where T : Vehicle
        {
            // Get type of T and delegate creation to private methods
        }
    }
    

Sort lexicographically?

I am working on integrating with the Photobucket API and I came across this in their api docs:

"Sort the parameters by name lexographically [sic] (byte ordering, the standard sorting, not natural or case insensitive). If the parameters have the same name, then sort by the value."

What does that mean? How do I sort something lexicographically? byte ordering?

The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.

Anyway, I'm writing the application in Python (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^

From stackoverflow
  • The word should be "lexicographic"

    http://www.thefreedictionary.com/Lexicographic

    Dictionary order. Using the letters as they appear in the strings.

    As they suggest, don't fold upper- and lower-case together. Just use the Python built-in list.sort() method.

  • This is similar to the Facebook API — the query string needs to be normalized before generating the signature hash.

    You probably have a dictionary of parameters like:

    params = {
      'consumer_key': "....",
      'consumer_secret': "....",
      'timestamp': ...,
      ...
    }
    

    Create the query string like so:

    urllib.urlencode(sorted(params.items()))
    

    params.items() returns the keys and values of the dictionary as a list tuples, sorted() sorts the list, and urllib.urlencode() concatenates them into a single string while escaping.

  • I think that here lexicographic is a "alias" for ascii sort?

    Lexicographic          Natural  
    z1.doc                  z1.doc    
    z10.doc                 z2.doc    
    z100.doc                z3.doc    
    z101.doc                z4.doc    
    z102.doc                z5.doc    
    z11.doc                 z6.doc    
    z12.doc                 z7.doc    
    z13.doc                 z8.doc    
    z14.doc                 z9.doc     
    z15.doc                z10.doc    
    z16.doc                z11.doc    
    z17.doc                z12.doc    
    z18.doc                z13.doc     
    z19.doc                z14.doc     
    z2.doc                 z15.doc    
    z20.doc                z16.doc    
    z3.doc                 z17.doc    
    z4.doc                 z18.doc    
    z5.doc                 z19.doc    
    z6.doc                 z20.doc    
    z7.doc                z100.doc    
    z8.doc                z101.doc    
    z9.doc                z102.doc    
    
  • Quote a bit more from the section:

    2 Generate the Base String:

    Normalize the parameters:

    • Add the OAuth specific parameters for this request to the input parameters, including:

      oauth_consumer_key = <consumer_key>
      oauth_timestamp = <timestamp>
      oauth_nonce = <nonce>
      oauth_version = <version>
      oauth_signature_method = <signature_method>
      
    • Sort the parameters by name lexographically [sic] (byte ordering, the standard sorting, not natural or case insensitive). If the parameters have the same name, then sort by the value.

    • Encode the parameter values as in RFC3986 Section 2 (i.e., urlencode). Create parameter string (). This is the same format as HTTP 'postdata' or 'querystring', that is, each parameter represented as name=value separated by &. For example, a=1&b=2&c=hello%20there&c=something%20else

    I think that they are saying that the parameters must appear in the sorted order - oauth_consumer_key before oauth_nonce before ...

Google Custom Search not indexing Dynamic Pages

I am trying to use Google Custom Search to provide search capabilities to an informational site.

About the site:

  • Content is generated dynamically
  • URL Access to content is search engine friendly (i.e. site.com/Info/3/4/45)
  • Sitemap (based on RSS feed) submitted and accepted by web master tools. It notes that no pages were indexed.
  • Annotations sucessfully submitted based on the RSS feed

Problem:

There are no results for any keywords that appear on the pages that were submitted.

Questions:

  • Why is Google not indexing the submitted pages?
  • What could I be doing wrong?
From stackoverflow
  • Custom Search with basic settings is principally same thing as standard search with site:your.website. Does standard search give you expected results?

    Note, that Google doesn't index pages immediately. It takes some time. Check if your site is already indexed.

  • Yeah it took about 2 weeks for Google to pick up all my pages after I submitted a site map. But you should see a few pages indexed after a couple days.

PHP XML Parser - ignoring nested/child tags

I've got a situation where I'm using an XML parser to extract data from a php://input.

The data being sent in looks like:-

<this>foo</this>
<that>bar></that>
<data><dong>zebras</dong><fong>monkeys</fong></data>

Now, the issue is that because the handler:-

      $xml_parser = xml_parser_create();

   xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
   xml_set_element_handler($xml_parser, "startTag", "endTag");
   xml_set_character_data_handler($xml_parser, "contents");

   $document = file_get_contents("php://input");       

   xml_parse($xml_parser, $document);

   xml_parser_free($xml_parser);

...is interpreting tags for me to decifer the contents to make it useful... It seems to be missing anything within i.e. I need to find out how i can get it to ignore the child/nested elements/tags and just bosh out the data whatever.

Any thoughts muchos help. I've not found much about this out there.

From stackoverflow
  • I'm not sure if I understood the question correctly, but

    <?php
    function contents($parser, $data) {
      echo $data;
    }

    $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); // xml_set_element_handler($xml_parser, "startTag", "endTag"); xml_set_character_data_handler($xml_parser, "contents"); // $document = file_get_contents("php://input"); $document = '<x><this>foo</this><that>bar</that><data><dong>zebras</dong><fong>monkeys</fong></data></x>'; xml_parse($xml_parser, $document); xml_parser_free($xml_parser);

    prints
    foobarzebrasmonkeys

    WiseDonkey : Hi Volkerk, Thanks for the response. What i need it to do it say foobarzebrasmonkeys i.e. withinn all contents is printed, almost as source, with tags.
  • WideDonkey, have you considered using the DOM instead? You can easily do :

    $dom = new DOMDocument();
    $dom->loadXML(file_get_contents('php://input'));
    
    $data = $dom->getElementsByTagName('data');
    $data = $data[0]->asXML();
    
  • Comment on Evert's answer: DOMNodeElement doesn't have a method asXML(), $data = $data[0]->asXML(); will not work with PHP-DOM. And SimpleXMLElement::asXML() will return the whole element's xml, i.e. <data>...</data>
    But you can modify the XML Element Structure Example to print the tags in your element handler functions when the counter is > 1

  • What I ended up doing was using SimpleXML to do:-

    $xml = new SimpleXMLElement($input);
    
    $whatIwant = $xml->bar->monkeys
    

    You can go down as many levels as you want such as test

    The $xml is the furthest out wrapper tag.

  • phpQuery gives you all the power of jQuery Selectors wrapped up in a PHP shell.

    phpQuery::newDocumentFileXHTML('my-xhtml.html')->find('p');
    

Updates on PIVOTs in SQL Server 2008

Is there a way to perform updates on a PIVOTed table in SQL Server 2008 where the changes propagate back to the source table, assuming there is no aggregation?

From stackoverflow
  • this is just a guess, but can you make the query into a view and then update it?

  • I don't believe that it is possible, but if you post specifics about the actual problem that you're trying to solve someone might be able to give you some advice on a different approach to handling it.

  • PIVOTs always require an aggregate function in the pivot clause.

    Thus there is always aggregation.

    So, no, it cannot be updatable.

    You CAN put an INSTEAD OF TRIGGER on a view based on the statement and thus you can make any view updatable.

    Example here

    brian : How could I use the INSTEAD OF trigger to update the original table?
    Cade Roux : Example here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=120679
  • I have similar problem. There is a timesheet table like this:

    TaskID Date Hours

    Since I want always to have this data filtered for one week, I would like to have table pivoted about date in the week:

    TaskID MONHours TUEHours WEDHours ... SUNHours

    This pivoted table should be presented to end user, where he could add,delete and modify hours, and also add new Tasks into that pivoted table.

    After he submit that data, data should be processed to original table.

    Any ideas will be really appreciated !!

  • This will only really work if the pivoted columns form a unique identifier. So let's take Buggy's example; here is the original table:

    TaskID    Date    Hours
    

    and we want to pivot it into a table that looks like this:

    TaskID    11/15/1980    11/16/1980    11/17/1980 ... etc.
    

    In order to create the pivot, you would do something like this:

    DECLARE @FieldList NVARCHAR(MAX)
    
    SELECT
        @FieldList =
        CASE WHEN @FieldList <> '' THEN 
         @FieldList + ', [' + [Date] + ']' 
        ELSE 
         '[' + [Date] + ']' 
        END
    FROM
        Tasks
    
    
    
    DECLARE @PivotSQL NVARCHAR(MAX)
    SET @PivotSQL = 
        '
         SELECT 
          TaskID
          , ' + @FieldList + '
         INTO
          ##Pivoted
         FROM 
          (
           SELECT * FROM Tasks
          ) AS T
         PIVOT
          (
           MAX(Hours) FOR T.[Date] IN (' + @FieldList + ') 
          ) AS PVT
        '
    
    EXEC(@PivotSQL)
    

    So then you have your pivoted table in ##Pivoted. Now you perform an update to one of the hours fields:

    UPDATE
        ##Pivoted
    SET
        [11/16/1980 00:00:00] = 10
    WHERE
        TaskID = 1234
    

    Now ##Pivoted has an updated version of the hours for a task that took place on 11/16/1980 and we want to save that back to the original table, so we use an UNPIVOT:

    DECLARE @UnPivotSQL NVarChar(MAX)
    SET @UnPivotSQL = 
        '
         SELECT
            TaskID
          , [Date]
          , [Hours]
         INTO 
          ##UnPivoted
         FROM
          ##Pivoted
         UNPIVOT
         (
          Value FOR [Date] IN (' + @FieldList + ')
         ) AS UP
    
        '
    
    EXEC(@UnPivotSQL)
    
    UPDATE
        Tasks
    SET
        [Hours] = UP.[Hours]
    FROM
        Tasks T
    INNER JOIN
        ##UnPivoted UP
    ON
        T.TaskID = UP.TaskID
    

    You'll notice that I modified Buggy's example to remove aggregation by day-of-week. That's because there's no going back and updating if you perform any sort of aggregation. If I update the SUNHours field, how do I know which Sunday's hours I'm updating? This will only work if there is no aggregation. I hope this helps!

How do I use reflection to determine the nested type of an array?

I have an instance of System.Type, for which "IsArray" returns true.

How can I determine the "nested type" of the array type?

i.e.

Type GetArrayType(Type t)
{
    if(t.IsArray)
    {
        //  What to put here?
    }
    throw new Exception("Type is not an array");
}
Assert.That(GetArrayType(typeof(string[])), Iz.EqualTo(typeof(string));
Assert.That(GetArrayType(typeof(Foo[])), Iz.EqualTo(typeof(Foo));
From stackoverflow
  • t.GetElementType()
    

    Reference.

    Paul Hollingsworth : Excellent! thanks!
    swilliams : I aim to please :).

WPF - Bind image property to Image control

Suppose I have string Name and Image Photo as properties of a class in my DataContext. I need to bind them to controls is a DataTemplate.

I thought this would work but it doesn't:

<Image Source="{Binding Photo}"/>

Why not? Should I my Photo have another type? (BitmapImage perhaps?)

How can I bind an Image control to an Image property?

Thanks!

Edit: As usual, after clicking submit I saw that the error is very clear: there's no converter from Image to ImageSource. How would my converter be to convert Image to ImageSource?

From stackoverflow
  • Yes, if I make my property BitmapImage it all works just fine. Sorry for the stupid question.

    Arcturus : There are no stupid questions! :) Hope it solved your problem!
  • It doesn't really makes sense to have a data property of type Image, since Image is a control (if you really want to do that you could bind to Photo.Source). You should use an ImageSource instead (or a BitmapImage, like you did, since BitmapImage inherits from ImageSource).

    Gustavo Cavalcanti : I agree Thomas. I started with type Image because for no good reason. :) It wasn't a good idea at all.

How can i create this time-table with stable time format?

How can i get result "My Dream Table Result"

CREATE TABLE #temp(
[count] int,
[Time] nvarchar(50) )
DECLARE @DateNow DATETIME,@i int

SET @DateNow='00:00'
set @i=1;


     while(@i<1440)
       begin
      set @DateNow=DATEADD(minute, 1, @DateNow)
      insert into #temp ([count], [Time]) values(0,@DateNow)
      set @i=@i+1
       end
SELECT [count],CONVERT(VARCHAR(max), [Time], 104) as [Time] from  #temp
drop table #temp




Table Result:

Count---------Time
0-------------Jan 1 1900 12:01AM
0-------------Jan 1 1900 12:02AM
0-------------Jan 1 1900 12:03AM
0-------------Jan 1 1900 12:04AM

But i don't like thsi table Time format is not ok. i need this table

My Dream Table Result:

Count---------Time
0---------------12:01
0---------------12:02
0---------------12:03
0---------------12:04
.
.
.
.
.
0--------------22:01
0--------------22:02
0--------------22:03
0--------------22:04
From stackoverflow
  • @DateNow is a DateTime so will have the Date Compoent as well

    select right(left(convert(nvarchar, @DateNow, 121), 16), 5)
    

    will give you just the time component for putting in yoru Nvarchar column

    while(@i<1440)
    begin
        set @DateNow=DATEADD(minute, 1, @DateNow)
        insert into #temp ([count], [Time]) values(0, right(left(convert(nvarchar, @DateNow, 121), 16), 5))
        set @i=@i+1
    end
    SELECT [count], [Time] from  #temp
    drop table #temp
    

    And for shits'n'giggles, here's how to do it without relying on a DateTime Object.

    CREATE TABLE #temp (
       [count] int,
       [Time] nvarchar(50) 
    )
    
    
    DECLARE @hour int, @min int, @i int
    SELECT @hour = 0, @min = 0, @i = 1
    
    WHILE (@hour < 24)
    BEGIN
        WHILE (@min < 60)
        BEGIN
         INSERT INTO #temp ([count], [time]) 
         VALUES (@i, REPLACE(STR(@hour, 2, 0), ' ', 0) + ':' + REPLACE(STR(@min, 2, 0), ' ', 0))
         set @min = @min + 1
         set @i=@i+1
        END  
        set @min = 0
        set @hour = @hour + 1
    END
    
    SELECT * FROM #Temp
    
    Phsika : You are ok. Thanks alot!!!
    Phsika : Can you look please my another question. Yhis question is related to this. http://stackoverflow.com/questions/839386/how-can-i-left-out-join-these-temp-default-data-and-another-table i need your help please!!!
  • SQL Server 2008 includes the concept of a time data type.

    Check this out:

    CREATE TABLE dbo.Table_1 ( testtime time(7) NULL, testdate date NULL, testdatetime datetime NULL ) ON [PRIMARY] GO

    insert table_1 (testtime, testdate, testdatetime) values (GETDATE(), GETDATE(), GETDATE())

    CREATE TABLE dbo.Table_2 ( testtime time(0) NULL, testdate date NULL, testdatetime datetime NULL ) ON [PRIMARY] GO insert table_2 (testtime, testdate, testdatetime) values (GETDATE(), GETDATE(), GETDATE())

    select * from Table_2 select * from Table_1

How to automate Photoshop?

I am trying to automate the process of scanning/cropping photos in Photoshop. I need to scan 3 photos at a time, then use Photoshop's Crop and Straighten Photos command, which creates 3 separate images. After that I'd like to save each of the newly created images as a PNG.

I looked at the JSX scripts and they seem to a lot of promise. Is what I described possible to automate in Photoshop using JavaScript or VBScript or whatever?

From stackoverflow
  • Have you tried using Photoshop Actions? I don't now about the scanning part, but the rest can all be done by actions quite easily.

  • I actually got the answer on the Photoshop forums over at adobe. It turns out that Photoshop CS4 is totally scriptable via JavaScript, VBScript and comes with a really kick-ass Developer IDE, that has everything you'd expect (debugger, watch window, color coding and more). I was totally impressed.

    The answer to my question is here: http://forums.adobe.com/message/1939870

What's the difference between TAPI and TSAPI

I have a C++ program that uses the Microsoft TAPI interface to collect call events from a Cisco Call Manager PBX. To get the Cisco events I downloaded the TSP from the call manager and then my TAPI code just works.

Can I do the same thing with an Avaya AES server? I see that Avaya uses TSAPI rather than TAPI, but I couldn't see what difference that would make to my program.

From stackoverflow
  • One is just "telephony" and the other is "telephony services". The difference is similar to that between the phone on your desk (TAPI) and PBX in your company's comms closet (TSAPI), with the exception that since it's all in software you could write a program using TAPI to do much of what a PBX does. But I think you'll find it easier using TSAPI.

  • TAPI is a telephony API developed by Microsoft, TSAPI is a telephony API developed by the company that eventually became Avaya (AT&T -> Lucent -> Avaya). TAPI's design was oriented torward first party call control (i.e. phones), while TSAPI was oriented torward third party call call control (i.e. PBXes and central office switches). TAPI does have some limited support for dealing with the call audio, TSAPI has none. I'd be very surprised if you could find a TAPI TSP for Avaya AES, and you won't be getting it from Avaya if you do.

    If all you're interested in is call events, then you can do the same things with both APIs, but the code will be totally different. Most companies that have products that have to talk to both Avaya AES and Cisco Call Manager have created an generic CTI interface for their product and then write code modules (aka drivers) that translate the TSAPI and TAPI call events to their generic event format. In your case, depending on your OS, you can move your TAPI code into a separate DLL/shared library, then create a separate DLL/shared library that implements the same functions but using TSAPI instead of TAPI.

    Frotunately, a lot of the smaller PBX manufacturers use either TAPI or TSAPI based APIs for their CTI interfaces, so if you have to connect to a third PBX, chances are good that you can reuse one of the two modules.

.NET Sharepoint Create Directory

I can upload a file to sharepoint with the webclient as follows

using (System.Net.WebClient webclient = new System.Net.WebClient())
{
 System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(
     Encryptor.Decrypt(ConfigurationManager.AppSettings["username"]),
     Encryptor.Decrypt(ConfigurationManager.AppSettings["password"]),
     ConfigurationManager.AppSettings["domain"]);
 webclient.Credentials = credentials;

 string path = Path.Combine("http://sharepoint.domain.com/dir", filename);
 webclient.UploadData(path, "PUT", fileBytes);
}

But I don't know how to create directories if they don't exist.

Any ideas how I can do that?

Thanks, -c

From stackoverflow
  • The term "Directories" in a SharePoint site is deceptive. The 'directory' structure of a SharePoint webservice is a virtual structure that is located in the SharePoint databases. You need to identify what object in the SharePoint Object Model the 'directory' is for example: http://sharepoint.domain.com/dir is probably a SPSite, with in the site you can have a 'directories' that are SPFolders, SPLists, SPDocumentLibraries etc.

    So if by "create directories that don't exist" you mean in the SharePoint site directory structure, you wont be able to do with the WebClient. You have two options: the Windows SharePoint Services Object Model, and the SharePoint Webservices.

    The object model is certainly easier to use in my opinion but it will require you to run the app on the same server as your SharePoint server. The Webservices are a bit more work but it enables you to use them remotely.

    You will need to identify what kind of object you are trying to add (e.g. SPFolder, SPSite, SPList, SPDocumentLibrary ect.).

    There is ample documentation for using the object model located Here but if you want to use the webservices you will need to access them at the following locations:

    Administration Service       http://<server-url:port-number>/_vti_adm/admin.asmx
    Alerts Service               http://<server-url>/_vti_bin/alerts.asmx
    Document Workspace Service   http://<server-url>/_vti_bin/dws.asmx
    Forms Service                 http://<server-url>/_vti_bin/forms.asmx
    Imaging Service             http://<server-url>/_vti_bin/imaging.asmx
    List Data Retrieval Service http://<server-url>/_vti_bin/dspsts.asmx
    Lists Service                 http://<server-url>/_vti_bin/lists.asmx
    Meetings Service               http://<server-url>/_vti_bin/meetings.asmx
    Permissions Service         http://<server-url>/_vti_bin/permissions.asmx
    Site Data Service             http://<server-url>/_vti_bin/sitedata.asmx
    Site Service                   http://<server-url>/_vti_bin/sites.asmx
    Users and Groups Service       http://<server-url>/_vti_bin/usergroup.asmx
    Versions Service               http://<server-url>/_vti_bin/versions.asmx
    Views Service                 http://<server-url>/_vti_bin/views.asmx
    Web Part Pages Service       http://<server-url>/_vti_bin/webpartpages.asmx
    Webs Service                   http://<server-url>/_vti_bin/webs.asmx
    

    I suggest looking into the Lists or Document Workspace Service services.

    Hope that helps.

    Chad : That worked great, with two catches. 1. If you have subsites you need to include that in the URL so it tries creating the folder at the right place 2. You can only create one new directory at a time you can't create multiple levels at one time (ie. new/sub/folder)

How can I execute a set of .SQL files from within SSMS?

How could I execute a set of .SQL files (each does some data transformations) from within SQL Server Management Studio?

What other alternative are there for executing .SQL files in batch?

From stackoverflow
  • Use SqlCmd.exe.

    For example:

    sqlcmd -S myServer\instanceName -i C:\myScript.sql
    

    or to save output to a file:

    sqlcmd -S myServer\instanceName -i C:\myScript.sql -o C:\EmpAdds.txt
    
  • While SQLCMD.exe is the best way, SSMS also has a SQLCMD mode where you can execute a SQLCMD script.

    The ":r filename.sql" command is the SQLCMD script command to import and execute a sql script file. You know you are in SQLCMD mode because any lines that are SQLCMD script commands will appear with colored (gray I think) background.

    :r file1.sql
    :r file2.sql
    

Webbased MySQL interface better that phpMyAdmin

Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

From stackoverflow
  • Why don't you just use a client? They are a lot nicer in my opinion.

    I love SQLyog because it supports a lot of MySQL features (stored procedures) but I used to use HeidiSQL and it was nice as well.

    As for web based clients, I haven't got any suggestions unfortunately.

  • try checking these out http://www.webresourcesdepot.com/category/goodies/database/

    as a client, I recommend EMS Manager, as well as for Posgtres

    Gerry : Fantastic link, provides a range of web based interfaces for MySQL. Good work. :)
  • I know about SqlBuddy. It has a simpler interface that phpMyAdmin - but pma is much more powerful.

    There is also the VFront application. I have not tried it yet - so I cannot comment on it.

  • as a client I recommend Toad For Mysql (it is free)

  • As clients, the MySQL Query browser and Administrator are quite good. That has a number of different export facilities that are cool. If it needs to be web though, then you might be best sticking with the slow phpmyadmin.

  • Among non-web clients, I use Navicat for MySQL. The free version can do everything phpMyAdmin can

  • I'd like to suggest AeroSQL, it's an open source (GPL) web based MySql Manager built using PHP and ExtJS library.

    There is a demo, video and screenshots available.

    Project homepage: http://www.burlaca.com/aerosql/

    The key feature of the product is an intuitive management of the database content. The result of SELECTs is displayed in a grid as in traditional desktop applications. The grid is editable: you can update cells and save the changes to the backend database server.

  • I suggest phpadminer because it is lightweight and has only one php file, but you should continue with slow phpmyadmin.

Rails using named routes within helper (but with class methods)

Trying to use this method (gist of which is use self.method_name in the FunnyHelper, then call it as FunnyHelper.method_name in the view).

However this causes at least a couple of problems - view methods like h() and named routes get broken (they're ok with the module method def method_name but not within any class method def self.method_name).

Obviously I can avoid this by dropping the def self.method_name back to def method_name; anyone with any suggestions for how I can have my cake and eat it too?

From stackoverflow
  • If you really want to do this, you can use

    include ActionController::UrlWriter
    

    to get access to your named routes and

    # h is a private method 
    ActionController::Base.helpers.send :h, "<"
    

    for other view helpers. But I would not recommend it. In my opinion the design pattern that thoughtobt is suggesting here sucks and I would just use helper :blogs despite their complaint that it isn't explicit. That is true, sort of... but Rails in general and this part of Rails in particular is architected in a completely "non-explicit" way so trying to fight against that is going to be more trouble than it's worth, as you are discovering.

How do I generate and send a .zip file to a user in C# ASP.NET?

I need to construct and send a zip to a user.

I've seen examples doing one or the other, but not both, and am curious if there are any 'best practices' or anything.

Sorry for the confusion. I'm going to generating the zip on the fly for the web user, and sending it to them in the HTTP response. Not in an email.

Mark

From stackoverflow
  • I'm sure others will recommend SharpZipLib

    How do you intend to "send" it. .NET has built in Libraries for email via SMTP

    EDIT

    In that case you'll want to capture the output stream from SharpZipLib and write it directly to the Response. Just make sure you have the correct Mimetype set in the Response Headers (application/zip) and make sure you don't Response.Write anything else to the user.

    MStodd : It will be sent to the ASP.NET user over HTTP while on the page.
    Rich.Carpenter : I'm not an ASP developer, but would Server.Redirect("UrlToFile") accomplish that?
    MStodd : I don't want the file to be around after it's been sent to the user.
    Eoin Campbell : edited the answer
  • Sending a zip file (I'm assuming over email) is no different than attaching any file to an email to send it. How do the examples you've seen do it?

  • As I understand it, Windows does not expose the objects necessary to "send to a compressed folder". I believe this was a stipulation in their licensing agreement with the company who wrote it. If you have WinZip installed, you can utilize it from the command line to create .zip files.

    As far as sending it goes, I assume you mean via email, in which case normal SMTP functionality in Visual Studio should suffice.

  • I would second the vote for SharpZipLib to create the Zip file. Then you'll want to append a response header to the output to force the download dialog.

    http://aspalliance.com/259

    should give you a good starting point to achieve that. You basically need to add a response header, set the content type and write the file to the output stream:

    Response.AppendHeader( "content-disposition", "attachment; filename=" + name );
    Response.ContentType = "application/zip";
    Response.WriteFile(pathToFile);
    

    That last line could be changed to a Response.Write(filecontents) if you don't want to save to a temp file.

  • Agree with above, SharpZipLib , for creating .zip files in .NET, it seems a very popular option.

    As for 'send'ing, if you mean via SMTP/Email, you will need to use the System.Net.Mail name space. The System.Net.Mail.Attachment Class documentation has an example of how to send a file via email

    Scratch the above, by the time I posted this I see you meant return via HTTP Response.

  • DotNetZip lets you do this easily, without ever writing to a disk file on the server. You can write a zip archive directly out to the Response stream, which will cause the download dialog to pop on the browser.

    Example ASP.NET code for DotNetZip

    More example ASP.NET code for DotNetZip

    snip:

        Response.Clear();
        Response.BufferOutput = false; // false = stream immediately
        System.Web.HttpContext c= System.Web.HttpContext.Current;
        String ReadmeText= String.Format("README.TXT\n\nHello!\n\n" + 
                                         "This is text for a readme.");
        string archiveName= String.Format("archive-{0}.zip", 
                                          DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); 
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "filename=" + archiveName);
    
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(f, "files");            
            zip.AddFileFromString("Readme.txt", "", ReadmeText);
            zip.Save(Response.OutputStream);
        }
        Response.Close();
    

    or in VB.NET:

        Response.Clear
        Response.BufferOutput= false
        Dim ReadmeText As String= "README.TXT\n\nHello!\n\n" & _
                                  "This is a zip file that was generated in ASP.NET"
        Dim archiveName as String= String.Format("archive-{0}.zip", _
                   DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
        Response.ContentType = "application/zip"
        Response.AddHeader("content-disposition", "filename=" + archiveName)
    
        Using zip as new ZipFile()
            zip.AddEntry("Readme.txt", "", ReadmeText, Encoding.Default)
            '' filesToInclude is a string[] or List<String>
            zip.AddFiles(filesToInclude, "files")            
            zip.Save(Response.OutputStream)
        End Using
        Response.Close
    
    kape123 : By far the best ZIP library for C#
  • But DotNetZip only lets you save, so its sent and starts downloading only when all files have been added to the zip on the server. Whereas with SharpZipLib you can start streaming immediately, dynamically adding files, till the end.

    Cheeso : Seems like this should be a comment. It's true that DotNetZip wants must know the complete set of files to be in the zip, before writing the zip. That does not mean there is a zip constructed in memory. Do you have a need to delay the decision on which files to send to the browser, until after you started sending some of them? I can't see that being a very common scenario.
  • Commenting needs 50 reputation...
    Yes it should have been a comment, and Cheeso, thanks for your answer, I hereby second the vote for DotNetZip as easier to code, (no low level), clearer to read, and does exactly what was requested in the above question: Construct, and send the zip to the user, on the fly.

  • One concern is the size of the file that you will be streaming to the client. If you use SharpZipLib to build the ZIP in-memory, you don't have any temp files to cleanup, but you'll soon run into memory issues if the files are large and a number of concurrent users are downloading files. (We experienced this pretty frequently when ZIP sizes got to the 200 MB+ range.) I worked around this by the temp file to disk, streaming it to the user, and deleting it when then request completed.

  • DotNetZip creates the stream without saving any resources on the server, so you don't have to remember to erase anything. As I said before, its fast and intuitive coding, with an efficient implementation.

    Moshe