Monday, April 25, 2011

Checking Download size before download

Hi

I need some way to check the size of a download without having to download the entire file. I am using C# and the System.Net.WebClient to do the downloads.The check needs to run in a asp.net webservice.

Thanks

From stackoverflow
  • Make a HEAD (rather than GET or POST) request to just get the response headers, this should include the content-length header with the information you need.

  • Use HTTP method HEAD to retrieve Content-Length: header.

    HEAD / HTTP/1.1
    Host: www.example.com
    
    HTTP/1.1 200 OK
    Date: Wed, 18 Mar 2009 11:21:51 GMT
    Server: Apache/2.2.3 (CentOS)
    Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
    ETag: "b80f4-1b6-80bfd280"
    Accept-Ranges: bytes
    Content-Length: 438 
    Connection: close
    Content-Type: text/html; charset=UTF-8
    
    RC1140 : Hi you can use the code at this page to actually get the details (for anyone that needs the info) http://www.eggheadcafe.com/tutorials/aspnet/2c13cafc-be1c-4dd8-9129-f82f59991517/the-lowly-http-head-reque.aspx
    Jim Mischel : Assuming that the Content-Length header is there. You'd be surprised how many sites don't supply that information, and how many don't even support HEAD.
    RC1140 : What would you use as an alternative
    vartec : Actually in these cases there is no alternative. Luckily these are rather rare cases. For example if you download stuff from one of these servers, your browser instead of giving you normal progress bar and ETA, gives you indeterminate progress bar or spinner.
  • You can also use the HTTP RANGE header to download only the stuff you want.

    It would be really simple to build a HttpRangeStream that supports seek and read on a remote HTTP resource, if the remote server is HTTP 1.1 and correctly supports RANGE headers.

I am looking for a content addressing data structure

I'm trying to design a data structure that allows efficient extraction of entries from a part of their content.

Let's say I am looking for an entry that matches this: [ x 2 3 x x ]

If [ 0 2 3 4 5 ] or [ 3 2 3 7 8 ] are in my data structure, they should be returned by my find function.

I wrote such a data structure where I compare the "pattern" against all entries of the data structure, but of course it takes way too much time. I have few ideas about how to do this a faster way but they are quite heavy to implement. Does something like this already exists? If not, how would you do this?

From stackoverflow
  • What you're trying to implement looks a lot like tuple space.

    Ben : Yes it is actually what I want to do but I need I wanted a hint for implementing it. I guess I'll to look at the code! Thanks
    vartec : Let me guess. Distributed programming class homework? ;-)
    Ben : Nop ! that is real work :/
    vartec : Oh, then why not use already available solutions?
    Ben : Well I have specific needs but I simplified a bit the problem to ask my question. Available solutions are not exactly what I want, but they are a good start for implementation, I am on it.
  • Well, a Suffix tree could do it in O(1), but it would take a LOT of memory.

    j_random_hacker : +1. Assuming you have multiple entries, what you really want is called a generalised suffix tree, which is formed by concatenating all the entries together, using distinct (unique) separator symbols between each. Suffix arrays are a (theoretically) slower but much more memory-efficient alternative.
    j_random_hacker : P.S.: Suffix trees and arrays rock, but they are *hard* to implement. If you can't find an existing implementation, give yourself a solid 2 weeks to try to understand Ukkonnen's or McCreight's original papers on linear-time construction algorithms.
    Darius Bacon : How specifically does it do it in O(1)? You can retrieve all the entries containing a particular substring in O(length(substring)), if that's what you mean. I think the given problem does not restrict the known bits to be a single contiguous substring, either.
    Vilx- : I think it does restrict it to a single contiguous substring, but yes, it's not very clear on this. As for O(1) - well, it depends on how you look at it. The Big O in this case depends only on the length of the substring, not the amount of entries in the dictionary.
    Vilx- : Clasically when one talks about searching/sorting algorithms he measures the Big O in respect to the number of entries, not the length of them. From that point of view it's O(1).
  • The first thing that comes to mind is to have a hash table for each position in the tuple. For searching you intersect the results for all the positions with a specified value.

    dmeister : To hash each item is a starting point, but for large answer sets the intersection takes time and consumes memory. Consider also to hash each subset of a specific window size.
  • You might take a look at the RETE algorithm. This general problem came up in the AI systems of the 70s; Chapter 14 in Paradigms of AI Programming covers it. (IIRC there's mainly elaborations of starblue's answer and decision trees.)

Can a request be handled and ended prematurely, early in the pipeline?

I have an HttpModule that has bound an event handler to EndRequest.

Is there any way to handle the request inside the event handler? Meaning, I don't just want to run code and keep the request moving -- I want to stop it dead in its tracks, return a 200 Status Code, and call it a day, without it request continuing to the next step in the pipeline.

From stackoverflow
  • HttpContext.Current.ApplicationInstance.CompleteRequest();

    Deane : This looks interesting, but will this kill the request entirely? I appears that ti just skips the rest of the pipeline and goes straight to EndRequest. However, that's where I'm at already (that's the event I bound my handler to), and doesn't it still to provide a response?
    Robert C. Barth : This will end all further processing of the request. Your handler is not the only handler in the pipeline, so this will cancel further processing of other handlers after yours and send the response immediately to the client.

jQuery-UI Theming - CSS Sizing Differences

When using the jQueryUI samples on the website (theme browser) things look great. But, when I put the code and theme into my application, the sizing is way out of whack (I'm trying to utilize the Redmond theme).

Any ideas as to why these samples look so different? In the application I've built, there is only 1 CSS reference which is for the Redmond theme... These images below are exactly how they were rendered to the browser.

My Application:
alt text

jQuery UI Sample:
alt text

My Application Code:

<div>
    <asp:TextBox ID="txtDateSample" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" language="javascript">
    $(function() {
        $('#<%= txtDateSample.ClientID %>').datepicker({
            showButtonPanel: true,
            showOn: 'button',
            buttonImage: '../Graphics/Icons/calendar.png',
            buttonImageOnly: true
        });
    });
</script>

Firebug View of Div:

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"/>
From stackoverflow
  • This used to happen to me. It is because some of your styles are inadvertently affecting the calendar div. Get Firebug and check out what styles are being applied to the calendar. Then edit the theme to override anything your styles are doing.

    EDIT:

    The part you are looking for is not the HTML generated, although that is important, it is more of what styles are actually being applied:

    Firebug Style Tab

    You will see styles that are being applied while styles that have been assigned but are not being applied will be shown struck out. You will probably see some of your styles in this window. They are most likely the culprit. Fix them by making them more specific and your calendar should be good to go.

    RSolberg : I wonder if that is why they provide the "edit theme" functionality. Modified the font size and that seemed to do the trick.
    Paolo Bergantino : Ah, good. I guess my edit was for nothing then. :)
    RSolberg : Thanks. I'll look at this again later tonight. I believe it was the font size setting on the theme. 1.1em vs. small.
  • When things are smaller than you expect, a good assumption would be that some kind of percentage/proportional sizing is happening recursively, i.e. that you've got

    .foo {width: 80%;}
    

    somewhere and that has been applied twice or more, meaning that your width ends up at 80% of 80% of 80%.

In Haskell how do you extract strings from an XML document?

If I have an XML document like this:

<root>
  <elem name="Greeting">
    Hello
  </elem>
  <elem name="Name">
    Name
  </elem>
</root>

and some Haskell type/data definitions like this:

 type Name = String
 type Value = String
 data LocalizedString = LS Name Value

and I wanted to write a Haskell function with the following signature:

 getLocalizedStrings :: String -> [LocalizedString]

where the first parameter was the XML text, and the returned value was:

 [LS "Greeting" "Hello", LS "Name" "Name"]

how would I do this?

If HaXml is the best tool, how would I use HaXml to achieve the above goal?

Thank!

From stackoverflow
  • I've never actually bothered to figure out how to extract bits out of XML documents using HaXML; HXT has met all my needs.

    {-# LANGUAGE Arrows #-}
    import Data.Maybe
    import Text.XML.HXT.Arrow
    
    type Name = String
    type Value = String
    data LocalizedString = LS Name Value
    
    getLocalizedStrings :: String -> Maybe [LocalizedString]
    getLocalizedStrings = (.) listToMaybe . runLA $ xread >>> getRoot
    
    atTag :: ArrowXml a => String -> a XmlTree XmlTree
    atTag tag = deep $ isElem >>> hasName tag
    
    getRoot :: ArrowXml a => a XmlTree [LocalizedString]
    getRoot = atTag "root" >>> listA getElem
    
    getElem :: ArrowXml a => a XmlTree LocalizedString
    getElem = atTag "elem" >>> proc x -> do
        name <- getAttrValue "name" -< x
        value <- getChildren >>> getText -< x
        returnA -< LS name value
    

    You'd probably like a little more error-checking (i.e. don't just lazily use atTag like me; actually verify that <root> is root, <elem> is direct descendent, etc.) but this works just fine on your example.


    Now, if you need an introduction to Arrows, unfortunately I don't know of any good one. I myself learned it the "thrown into the ocean to learn how to swim" way.

    Something that may be helpful to keep in mind is that the proc/-< syntax is simply sugar for the basic arrow operations (arr, >>>, etc.), just like do/<- is simply sugar for the basic monad operations (return, >>=, etc.). The following are equivalent:

    getAttrValue "name" &&& (getChildren >>> getText) >>^ uncurry LS
    
    proc x -> do
        name <- getAttrValue "name" -< x
        value <- getChildren >>> getText -< x
        returnA -< LS name value
    
    Tim Stewart : Thank you very much for a very informative answer!
    Paul Johnson : There is a HXT tutorial at http://www.haskell.org/haskellwiki/HXT, but it is relentlessly point-free, so understanding how this relates to the arrow do-notation (as in the example above) is not easy.
  • FWIW, HXT seems like overkill where a simple TagSoup will do :)

  • Here's my second attempt (after receiving some good input from others) with TagSoup:

    module Xml where
    
    import Data.Char
    import Text.HTML.TagSoup
    
    type SName = String
    type SValue = String
    
    data LocalizedString = LS SName SValue
         deriving Show
    
    getLocalizedStrings :: String -> [LocalizedString]
    getLocalizedStrings = create . filterTags . parseTags
      where 
        filterTags :: [Tag] -> [Tag]
        filterTags = filter (\x -> isTagOpenName "elem" x || isTagText x)
    
        create :: [Tag] -> [LocalizedString]
        create (TagOpen "elem" [("name", name)] : TagText text : rest) = 
          LS name (trimWhiteSpace text) : create rest
        create (_:rest) = create rest
        create [] = []               
    
    trimWhiteSpace :: String -> String
    trimWhiteSpace = dropWhile isSpace . reverse . dropWhile isSpace . reverse
    
    main = do
      xml <- readFile "xml.xml"  -- xml.xml contains the xml in the original question.
      putStrLn . show . getLocalizedStrings $ xml
    

    The first attempt showcased a naive (and faulty) method for trimming whitespace off of a string.

    ephemient : TagSoup happily accepts malformed input -- which you might actually like :) -- unfortunately IMO this solution is harder to read. Minor nit: I'd have expected something more like `trimWhiteSpace = dropWhile isSpace . reverse . dropWhile isSpace . reverse`; yours is more like `removeAllWhiteSpace`.
    Tim Stewart : Thanks ephemient. I should have had some better sample data. :) I'll have to make sure that isSpace gets rid of newlines because I had some newlines embedded in my XML.
    ephemient : Just try for yourself: type `Data.Char.isSpace '\n'` into GHCi. Yes, newlines are, and have always been, whitespace. My nit wasn't about that, more along the lines of your `trimWhiteSpace " a b c " == "abc"` which is non-intuitive to me. Or maybe I'm strange.
    Tim Stewart : You're absolutely right. I want to keep those internal spaces. Thanks.
  • Use one of the XML packages.

    The most popular are, in order,

    1. haxml
    2. hxt
    3. xml-light
    4. hexpat

Age from Date of Birth using JQuery

I need to calculate if someone is over 18 from their date of birth using JQuery.

var curr = new Date();
curr.setFullYear(curr.getFullYear() - 18);

var dob = Date.parse($(this).text());

if((curr-dob)<0)
{
    $(this).text("Under 18");
}
else
{
    $(this).text(" Over 18");
}

There must be some easier functions to use to compare dates rather than using the setFullYear and getFullYear methods.

Note: My actual reason for wanting to find a new method is length of the code. I have to fit this code into a database field that is limited to 250 chars. Changing the database is not something that can happen quickly or easily.

From stackoverflow
  • You could use the Date object. This will return the milliseconds between the two dates. There are 31556952000 milliseconds in a year.

    function dateDiff(var now, var dob) { return now.getTime() - dob.getTime(); }

    Garry Shutler : Surely there aren't that many milliseconds every year. Dates are hard.
    Jon Erickson : that is not always true (leap years)
  • $(this).text(((new Date().getFullYear()-Date.parts($(this).text()))>=18)?"Over 18":"Under 18");
    

    Better? :D

    Parrots : This only seems to use the year field for calculation, won't take into account months/days of current date and the DOB. So with this someone born in Dec 1991 would come back as over 18 in Jan 2009, which isn't true (they'd be 18 in Dec 2009).
    Sudhir Jonathan : yes... it won't take into effect the months and days.. using a library would be useful if you want the full functionality, like in the first answer. Still can be built, though it might be difficult inside of 250 characters.
  • You can remove the separate variable for DOB and collapse the if statement. The below code comes in at 165 characters:

    var check = new Date();
    check.setFullYear(check.getFullYear() - 18);
    $(this).text((new Date("3/6/2009").getTime() - check.getTime() < 0)?"Under 18":"Over 18");
    

    This will still keep the logic needed to deal with leap-years.

  • You might find the open source Datejs library to be helpful. Specifically the the addYears function.

    var dob = Date.parse($(this).text());
    if (dob.addYears(18) < Date.today())
    {
        $(this).text("Under 18");
    }
    else
    {
        $(this).text(" Over 18");
    }
    

    In a more terse fashion:

    $(this).text(
        Date.parse($(this).text()).addYears(18) < Date.today() ?
        "Under 18" :
        " Over 18"
    )
    
    RSolberg : +1 - seems much easier to ready that others. I'm using this library and its been a big help.
  • Date.prototype.age=function(at){
        var value = new Date(this.getTime());
        var age = at.getFullYear() - value.getFullYear();
        value = value.setFullYear(at.getFullYear());
        if (at < value) --age;
        return age;
    };
    
    var dob = new Date(Date.parse($(this).text()));
    
    if(dob.age(new Date()) < 18)
    {
        $(this).text("Under 18");
    }
    else
    {
        $(this).text(" Over 18");
    }
    

Theme a CCK input form in Drupal 6

In my template.php file I've this:

function myadmintheme_theme(&$existing, $type, $theme, $path) {
  return array(
    'node_form' => array(
     'arguments' => array('form' => NULL),
     'template' => 'ccktype',
    ),
  );
}

And I've a ccktype.tpl.php in the same dir:

<b>works!</b>

But is not working, if I enter to node/add/ccktype I don't get the "works!" message.. I tried everything!

any help would be appreciated

From stackoverflow
  • First of all, see that Drupal's not caching your module. Go to Administer > Site Configuration > Performance, and clear all caches.

    If that doesn't work, try renaming the file to node-add-ccktype.tpl.php.

    br1 : thanks, but is not work... it's strange, isn't it?
    Seb : Yeah, I really don't know... I had problems with that theme hook as well. Sorry I can't help anymore :(
  • The theme function you need to override is ccktype_node_form, not node_form. All node forms maintained by the node module get mapped to the node_form function for building, but they still have unique form ids.

    br1 : I tried that also, but didn't work. I forgot to say that in the "Administration theme" y check "Use administration theme for content editing" (that is obvious).
    br1 : hey, I didn't notice this, but there is a very little change in the style when I use ccktype_node_form :D It is not printing "WORKS!", but is better than nothing ;D
    br1 : hey, now works! I love you!!! xD
  • This is the solution:

    function myadmintheme_theme($existing, $type, $theme, $path) {
      return array(
        'ccktype_node_form' => array(
         'arguments' => array('form' => NULL),
         'template' => 'ccktype',
        ),
      );
    }
    

    thanks a lot Eaton!

    Seb : Glad you solved this! If Eaton helped you, then please mark his answer as correct; that will help others find this problem is solved and will grant Eaton reputation points for having helped. :)
  • Thanks so much for this! I spent a ton of time looking on the stupid Drupal site and tried about 20 things that didn't work.

    Ugh!

Problem in dynamic grid view

I ve a grid view created dynamically. And each cell of the grid view has textboxes that are created dynamically.. The values for the textbox comes from an xml file and the IDs of the Text Boxes come from database.

The problem is, the values(to be displayed in text box) are getting assigned when i check using break points but not getting displayed in the output.

From stackoverflow
  • You need to post code, but... Here's a guess: if the values are not in the output, then they are probably being assigned after the ASP.NET Render event. You need to set the values when you create the controls.

Calculate previous week's start and end date

What is the best way to calculate the previous week's start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).

I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.

From stackoverflow
  • DayOfWeek weekStart = DayOfWeek.Monday; // or Sunday, or whenever
    DateTime startingDate = DateTime.Today;
    
    while(startingDate.DayOfWeek != weekStart)
        startingDate = startingDate.AddDays(-1);
    
    DateTime previousWeekStart = startingDate.AddDays(-7);
    DateTime previousWeekEnd = startingDate.AddDays(-1);
    

    Read: Backtrack one day at a time until we're at the start of this week, and then subtract seven to get to the start of last week.

  • Using DayOfWeek would be a way of achieving this:

        DateTime date = DateTime.Now.AddDays(-7);
        while (date.DayOfWeek != DayOfWeek.Monday)
        {
            date = date.AddDays(-1);
        }
    
        DateTime startDate = date;
        DateTime endDate = date.AddDays(7);
    
  • You can skip the while loop and use

    DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
    

    This assumes you're using Monday as the first day of the week.

    Austin Salonen : To answer the question, startOfWeek should be named sundayOfLastWeek. "DateTime mondayOfLastWeek = date.AddDays(-(int)date.DayOfWeek - 6);"
    bstoney : Thanks for the correction Austin Salonen
    Henryk : Nice one liner approach. I think the following would then work regardless of which day its run on: mondayOfLastWeek = DateTime.Now.AddDays( -(int)DateTime.Now.DayOfWeek - 6 ); sundayOfLastWeek = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek);
  • using Fluent DateTime http://fluentdatetime.codeplex.com/

            var dateTime = 1.Weeks().Ago();
            var monday = dateTime.Previous(DayOfWeek.Sunday);
            var sunday = dateTime.Next(DayOfWeek.Sunday);
    

Dealing with morally and legally objectionable requests from management

This question was originally posted with a similar title to this but was changed as the subject was not a moral issue.

However it was a good topic for a wiki question.

There are times when you are asked to implement features which you are not comfortable with, perhaps some mass emailing program, or something which access data on a PC which is not really its to access. I would put these as morally objectionable. However there is a line when this becomes also illegal, INAL so I won't give examples.

Is it a developers’ job to know the law enough to call on these? Is it right to say no to a request on the basis of it being illegal? Can you and should you get legal advice if you are not sure? Who is liable for the effects of code you right?

Their are a lot of questions there, but in short how do you handle situations where you think that code you are asked to write may be on the wrong side of the law?

edit:

Are developers really responsable for what their code does? This seems like making a machine operator at smith and western responsible for what any guns he produces do.

From stackoverflow
  • In my country a programmer is responsible for the code he writes. If our boss asks us to perform something illegal it is our obligation to say no.

    Nobody can force you to make a crime.

    Chris Lively : This is the same in the US. There are situations where a company can be held liable for the crimes of the employees, but that requires a pretty good paper trail. For the most part you can be held personally responsible for what you do.
    Austin Salonen : and without a good paper trail, you will be held personally responsible for what you do.
    David Thornley : Unless you're an executive, of course. Who from Sony is serving hard time for the rootkit affair? However, the world is what it is, and the worker bees have to look out for themselves.
    Jeremy French : So "just following orders", is not an excuse for a coder. I suppose we go with DNS' answer if your company says that it isn't illegal
    Sergio : Jeremy French: I once was in that position. My boss asked me to do something I though it was illegal (log personal information without user consent), I talked with my boss and he assured me it was legal, so i did it but cleaned all the records that could indicate that I did that (just in case).
    User : What country you are in?
    Sergio : SO sucks: Portugal
  • You really need to talk to a lawyer first in such a situation. There is no other option or advice worth considering. For simple questions, lawyers won't charge thousands, and getting real advice is worth it, if you really think it might be a crime.

    Jeremy French : Should you or your company get the lawyer?
    : Well I suppose both the company and you would NEED the attorney, but since the company is asking you, and you want to be protected, don't worry about what the company is going to do, just get the help you need.
    David Thornley : Look. If you want legal protection, pay the lawyer. That way, you're the client and the lawyer has responsibilities towards you. Never trust a lawyer paid by somebody you don't trust.
    Erik Forbes : David - I wish I could upvote comments.
  • simple question:

    but in short how do you handle situations where you think that code you are asked to write may be on the wrong side of the law?

    simple answer: don't do it.

    No one (in the US anyway) can force you to do something against your will. Which means that if you perform an illegal/immoral activity, you're responsible...here's a good starting point via wikipedia: http://en.wikipedia.org/wiki/Causation_(law)

    There's legal liability and moral responsibility...the more important aspect is moral - you can only sell your soul once

    Jeremy French : isn't it a little more complicated. If you write code that could do something illegal, but may also have legitimate uses. Say you write something that will mass mail from the database sould you make sure that it can only mail those with opt in, or is that the responsibility of the operator.
    meade : same response. If you make guns easy enough to use by children - you may not intend for children to use them, but you provided the means. The level of potential damage should determine the level of safe guards put into place.
  • Simple answer: Go talk to a lawyer if you're not sure what the laws are where you live. Asking legal advice on a web site that isn't a "get your free legal advice here from real attorneys you can verify through the Bar Association in the jurisdiction in which you live" is just being foolish.

    If someone here tells you, "No, do whatever your boss says. You're not legally liable or responsible." and you listen, and then end up being sued or worse, you're not going to feel really good about the choice to ask here, are you?

    Laws are specific to a jurisdiction. What you might be held liable for in San Diego, CA could be totally different in New York, NY, and most likely will be vastly different than Paris, France or Berlin, Germany. However, the person whose advice you decided to follow might be basing it on the laws where they live, or what they read somewhere and believed, or simply talking out of their backsides. Do you really want to trust your wallet (or your physical freedom) on that?

    Ask programming questions on programming sites. Address questions about that funny feeling in your chest or the lump on the side of your neck to your physician. And direct legal questions to an attorney licensed in the area that has jurisdiction.

  • The answerers here seem a bit idealistic. Not everyone can afford to go to a lawyer, and not doing something doesn’t really put you in good stead with your employer, especially if they think it is legal. So just refusing to do it could result in you begin fired.

    Personally I think a good first step is to talk to the people requesting the work, explain that it may not be legal and ask them to check it. I would imagine that companies have easier access to lawyers than most developers.

    Now if your company is not willing to take legal advice then you may have to go it alone, but this could still make life difficult for you at work.

    I should imagine some shady companies, would object to you asking or even raising the issue as that makes their own deniability more difficult.

Runtime creation of generic Func<T>

I need to implement the method:

object GetFactory(Type type);

This method needs to return a Func<T> where typeparam 'T' is the 'type'.

So, my problem is that I don't know how to create a Func<?> at runtime using reflection. Activator.CreateInstance doesn't work because there are no constructors on delegates.

Any Ideas?

From stackoverflow
  • I think the usual approach would be to make the "dumb" version be the thing that you spoof at runtme, and then provide a helper extension method to provide the type-safe version on top of it.

    Craig Wilson : So, this is in the bowels of an IoC container, and I have to return the object as a strongly typed dependency, not necessarily knowing that what was requested was a Func (it could be a Uri or string).
  • You use Delegate.CreateDelegate, i.e. from a MethodInfo; below, I've hard-coded, but you would use some logic, or Expression, to get the actual creation method:

    using System;
    using System.Reflection;
    class Foo {}
    
    static class Program
    {
        static Func<T> GetFactory<T>()
        {
            return (Func<T>)GetFactory(typeof(T));
        }
        static object GetFactory(Type type)
        {
            Type funcType = typeof(Func<>).MakeGenericType(type);
            MethodInfo method = typeof(Program).GetMethod("CreateFoo",
                BindingFlags.NonPublic | BindingFlags.Static);
            return Delegate.CreateDelegate(funcType, method);
        }
        static Foo CreateFoo() { return new Foo(); }
        static void Main()
        {
            Func<Foo> factory = GetFactory<Foo>();
            Foo foo = factory();
        }
    }
    

    For non-static methods, there is an overload of Delegate.CreateDelegate that accepts the target instance.

    Craig Wilson : Mark, I don't actually know what T is. If I knew what T is, this would be easy.
    Marc Gravell : You mean within the non-generic method? I'll update...
    Craig Wilson : I modified the question to better state my problem.
    Craig Wilson : Not exactly what I needed , but this pushed me down the right path. Thanks for your help.
    Marc Gravell : 'twas the best I could do given the available information...
    Daniel Earwicker : Oooh, was playing with reflection the other day and wondered if there was a way to describe a generic type definition in code, and now I know: List<>, which presumably can only appear inside typeof?
    Marc Gravell : @Earwicker: correct; you simply omit all the type-args - for example, KeyValuePair<,> instead of KeyValuePair
  • you could create Expression objects instead of a func, and compile() the expression to get a Func delegate.

Java: What is the best way to find elements in a sorted List?

I have a

List<Cat>

sorted by the cats' birthdays. Is there an efficient Java Collections way of finding all the cats that were born on January 24th, 1983? Or, what is a good approach in general?

From stackoverflow
  • Collections.binarySearch().

    Assuming the cats are sorted by birthday, this will give the index of one of the cats with the correct birthday. From there, you can iterate backwards and forwards until you hit one with a different birthday.

    If the list is long and/or not many cats share a birthday, this should be a significant win over straight iteration.

    Here's the sort of code I'm thinking of. Note that I'm assuming a random-access list; for a linked list, you're pretty much stuck with iteration. (Thanks to fred-o for pointing this out in the comments.)

    List<Cat> cats = ...; // sorted by birthday
    List<Cat> catsWithSameBirthday = new ArrayList<Cat>();
    Cat key = new Cat();
    key.setBirthday(...);
    final int index = Collections.binarySearch(cats, key);
    if (index < 0)
        return catsWithSameBirthday;
    catsWithSameBirthday.add(cats.get(index));
    // go backwards
    for (int i = index-1; i > 0; i--) {
        if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday()))
            catsWithSameBirthday.add(cats.get(tmpIndex));
        else
            break;
    }
    // go forwards
    for (int i = index+1; i < cats.size(); i++) {
        if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday()))
            catsWithSameBirthday.add(cats.get(tmpIndex));
        else
            break;
    }
    return catsWithSameBirthday;
    
    Jake : Collections.binarySearch() return a single element and makes no guarantees about elements which are considered identical.
    Michael Myers : Maybe that will teach me to read the question before answering. :)
    fred-o : Also, Collections.binarySearch() is only efficient for random access lists.
    Jake : Must have index < 0, but yeah: this is the general idea.
    Michael Myers : @Jake: Good point, that wouldn't have worked very well. I fixed the code.
  • Binary search is the classic way to go.

    Clarification: I said you use binary search. Not a single method specifically. The algorithm is:

    //pseudocode:
    
    index = binarySearchToFindTheIndex(date);
    if (index < 0) 
      // not found
    
    start = index;
    for (; start >= 0 && cats[start].date == date; --start);
    end = index;
    for (; end < cats.length && cats[end].date == date; ++end);
    
    return cats[ start .. end ];
    
    Jake : Collections.binarySearch() return a single element and makes no guarantees about elements which are considered identical.
    Mehrdad Afshari : I didn't say you should use `Collections.binarySearch` method. Binary search to find the index of a single element. All other elements with equal birthdays are beside the element found. You can get all of them with a single loop. It's a classic.
    slim : @Mehrdad - update the answer to reflect this and you'll earn an upvote.
  • Unless you somehow indexed the collection by date, the only way would be to iterate over all of them

    Mehrdad Afshari : It's sorted by date. What else would you possibly call an index!?
    Jake : I doubt that is the *only* way. Certainly you can imagine a "low level" algorithm that does this very efficiently by finding the first occurrence of Cats with a given birthday and proceeding linearly from there.
    Mehrdad Afshari : Jake: whatever algorithm you find first element will be O(n) unless you're doing some binary search. Asymptotically fastest algorithm is to binary search and linearly find the start and end after that.
  • If you need a really fast search use a HashMap with the birthday as a key. If you need to have the keys sorted use a TreeMap.

    Because you want to allow multiple cats to have the same birthday, you need to use a Collection as a value in the Hast/TreeMap, e.g.

          Map<Date,Collection<Cat>>
    
  • Google Collections can do what you want by using a Predicate and creating a filtered collection where the predicate matches dates.

    Jake : Does it filter the Collection in O(n)?
    basszero : I assume it would have to since it would apply the predicate to each element. A binary search (like the upvoted answer) is best if the list is sorted.

How can I determine my root calling assembly's version number at runtime? (.NET)

Example:

MyProgram.exe is executed. It calls MyClassLibrary1.dll which calls MyClassLibrary2.dll. How can I determine from within MyClassLibrary2.dll what the assembly version of MyProgram.exe is?

Is this possible?

Thanks.

From stackoverflow
  • System.Reflection.Assembly.GetEntryAssembly().GetName().Version
    
    vg1890 : Thanks! As an aside - do you have any tips on getting familiar with the framework so this type of stuff is just second nature?
    Mehrdad Afshari : @vg1890: MSDN was the best resource I could learn from. It takes time and experience with the framework. There is a "CLR via C#" book that teaches about the CLR internals. I haven't read it but I have heard many good reviews about it.
  • EDIT My answer will only work if the DLL has a reference to the actually EXE which would be rather odd to do.

    Try the following

    typeof(SomeTypeInMyProgram).Assembly.GetName().Version
    

    This will return a Version structure that you can use to analyze the version of MyProgram.exe.

    Mehrdad Afshari : How can you do that? It'll be a circular reference, I think.
    Andrew Hare : It works just fine - any type object will have a reference to its own assembly, from there you can determine anything about that assembly including its version.
    Mehrdad Afshari : The problem is it's not its own assembly. MyProgram depends on MyClassLibrary1 which in turn depends on MyClassLibrary2. To detect the version of MyProgram from MyClassLibrary2 in this way, you should have it available at compile time.
    Dave Van den Eynde : But MyClassLibrary2 needs a reference to MyProgram.exe for this to work.
    Dave Van den Eynde : @Mehrdad: indeed.
    JaredPar : @Mehrdad, doh. Forgot about that.
    Mehrdad Afshari : @JaredPar: Is it really possible? Since you don't have the EXE available at compile time (it should be built *after* the DLL) and the DLL requires the EXE to build. I'm curious if it's possible can make it work with a dummy EXE or something :-?
    JaredPar : @Mehrdad, it's certainly possible to reference an EXE. You can use asmmeta files to get around the circular dependencies.
    Mehrdad Afshari : @JaredPar: Thanks for the point. Yeah. I have done it with Reflector.exe before. I haven't had worked with `asmmeta` files before, but it seems the basic strategy is to have some dummy assemblies to resolve references at compile time.

Is it safe to pass function pointers as arguments to dll functions and invoke them from inside of the dll?

I would like to pass some (dll or not) function pointers as arguments to some dll functions and call them from inside of the dll. I wonder if it is safe because I have found an information on http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.cbcpx01/fpref.htm that:

In DLL code, it is assumed that a function pointer points to a function descriptor. A function pointer call is made by first obtaining the function address through dereferencing the pointer; and then, branching to the function entry. When a non-DLL function pointer is passed to DLL code, it points directly to the function entry. An attempt to dereference through such a pointer produces an undefined function address. The subsequent branching to the undefined address may result in an exception.

Does this rule apply to Visual Studio and other compilers as well?

What precisely I am trying to do is to solve the problem of memory allocation and deallocation between various dll and non-dll functions. My idea is to pass two function pointers - for common allocation and deallocation functions - to every dll in some initialization (e.g. Initialize(&malloc, &free)) and then do all memory management using these common and thus always compatible functions.

From stackoverflow
  • It's not true. DLL code treats function pointers in exactly the same way as non-DLL code. If that were not the case, one could not use standard library functions like qsort() (which expects a function pointer argument) within a DLL.

  • Passing function pointers to a DLL has been done for generations.

    All the callback functions used in GUI programming (for example progress bars update) use function pointers.

    When developing using WIN32, is there a reason you want to use function pointers to malloc/free? Why are you not simply using malloc/free directly?

    That is how I have always done it in the past. Not that this guarantees it's the correct way.
    In fact, you might take that as an indication that it's the worst possible way :)

    Michal Czardybon : "Why are you not simply using malloc/free directly?" - because using 'free' in one DLL on memory 'malloced' in a different DLL most often causes crashing.
    Benoit : I fail to see how providing a level of indirection would fix that, unless you have your own memory management. I haven't run across issues of crash when malloc/free from different DLLs as long as you don't do a double free.
    Michal Czardybon : http://msdn.microsoft.com/en-us/library/ms235460.aspx The additional level of indirection provides access to single, shared (between all dlls) functions for memory management.

Parsing buffer in C++ using OOP and STL

I want to use OOP and STL etc to parse a buffer.

My Buffer contains

ABCDXXXX333$$$$YYYY

I need to separate ABCD XXXX 333 $$$$ YYY and move them to struct. I have their offset defined in one of the rule table and how many elements are in the buffer. A few of the fields are delimited also.

  • Any suggestions what STL features I can use?
  • Any sample code will work, I will build on top of it.

I will be using this on an AIX (Unix) Box.

From stackoverflow
  • You can use cin.peek () to see if its a character you want to get (note this will not remove it from the stream). Perhaps three classes / functions to extract what they take using this technique and stopping when they reach a character they shouldn't hold.

  • You would probably have your class which contains all the data have a static function which creates the object given your serialized string. How it works depending on your data. You say you have defined offsets for fields, but also say they are delimited. This poses a problem as both need to be handled differently.

    Simple case for your example:

    class DataContainer
    {
        using namespace std; // FIXME Is this legal?
    
        public:
            DataContainer(string part1, string part2, string part3, string part4, string part5) :
                m_part1(part1), m_part2(part2), m_part3(part3), m_part4(part4), m_part5(part5)
            {
            }
    
            static DataContainer readFromStream(istream &stream)
            {
                DataContainer ret;
                char tmp[16];
    
                stream.get(tmp, 4);
                ret.m_part1 = string(tmp, 4);
    
                stream.get(tmp, 4);
                ret.m_part2 = string(tmp, 4);
    
                stream.get(tmp, 3);
                ret.m_part3 = string(tmp, 3);
    
                stream.get(tmp, 4);
                ret.m_part4 = string(tmp, 4);
    
                stream.get(tmp, 3);
                ret.m_part5 = string(tmp, 3);
    
                return ret;
            }
    
        private:
            DataContainer()
            {
            }
    
            string m_part1, m_part2, m_part3, m_part4, m_part5;  // Put these in an array if they belong in an array.
    };
    

    Note: I have inlined all my functions. You should probably put your functions in their own .cpp file.

    Use it like so:

    DataContainer dc = DataContainer::readFromStream(std::cin);
    

    This reads your data from cin (stdin) and puts the data structure in dc.

    If you already have the data read, you can use STL iterators (which are basically pointers to elements of a container) quite easily. You can also use classic indexing, which is simpler for your given case. For example:

    static DataContainer readFromBuffer(string buffer)
    {
        DataContainer ret;
        ret.m_part1 = string(buffer, 0, 4);
        ret.m_part2 = string(buffer, 4, 4);
        ret.m_part3 = string(buffer, 8, 3);
        ret.m_part4 = string(buffer, 11, 4);
        ret.m_part5 = string(buffer, 15, 3);
        return ret;
    }
    
    puetzk : Better yet, use ret.m_part*.assign(buffer,start,len), which avoids creating, copying, and destroying a temporary. And no, the compiler would not be allowed to optimize it out, since it can't see how to combine the constructor and operator =
    : I am confused, I am new to c++ One can define Datacontainer class and then assign ret to that class type ?
    strager : @unknown, I'm sorry, I forgot to include 'static' in my example. I will include sample usage.
    : What this statement do ? DataContainer(string part1, string part2, string part3, string part4, string part5) : m_part1(part1), m_part2(part2), m_part3(part3), m_part4(part4), m_part5(part5)
    strager : @unknown, That's call an initialization list. See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6
    : I could not get how the stuff will get put in to data structure ? I am thinking in terms of plain C. Also I never came across Constructor using some Variables followed by ':' an dthen followed by variable list. What is that ?
    strager : @unknown, Again, that's called an initialization list. It's not in C. If you need a C solution I can post one. If you need a non-OOP one with C++, I can post that too. I think it is best to learn OOP when learning C++ and not stick to C-style code. (Pick up a good C++ book if you please.)
  • If "buffer" is made of char then:

    string abcd = string(buffer,0,4);
    string xxxx = string(buffer,4,8);
    etc.
    
  • Read a line at a time with std::getline(), which stuffs the line into a std::string (your buffer). Then use std::string methods to parse the data according to your data format. Or use something like Lex/Yacc when you have a real grammar to deal with and the std::string methods are getting to hard to read sober.

  • I would really recommend using a regular expressions for your problem, boost::regex is available for C++.

    Regular expression will protect you against a lot of technical problems that generally turn into nasty security problems.

Where to put my siteLanguage parameter (cross cutting concern?)

In my project every page is translatable in several languages. For that purpose, I pass a sitelanguage parameter to each action. My custom base controller class catches this "siteLanguage" parameter and takes care of the further translation logic.

This works allright, only thing is now I have to add a string called sitelanguage to every action procedure signature just so my base controller can catch it. I don't do anything with this parameter in my actual action logic.

Is there a better way of doing this?

From stackoverflow
  • I'd put the site language in the session, and make the controller give it to the views, or maybe, just maybe, allow the views to retrieve it from there.

    I'd suggest Culture and CurrentCulture etc, but of course those don't work if you are an English speaking person who logs on from France. I typically tie the language with the users' preferences in the database, though I appreciate your site may not require a logon as such.

Is there an attribute to mark the class or method to be thread safe in .NET?

In .NET how can I know if a class or method is thread safe or not? Is it by default not thread safe?

From stackoverflow
  • This is no attribute for this: you have to read the documentation for each item your are interested in. You can't make something thread safe simply by adding an attribute to it. That's like taking an orange and putting a sticker on it that says, "Apple".

    Of course, the same thing is true for serialization and it didn't stop them there, but still: no attribute. Read the docs.

    Richard : All static methods and properties are assumed to be thread safe by default (i.e. unless documented otherwise), for instance methods the assumption is that they are not.
    JoshBerke : Assuming a method is not thread safe when it is causes no harm, assuming one is thread safe when its not can be nasty. Your better off to assume nothing is thread safe unless indicated.
  • I got my back on Joel Coehoorn on this one, would be easy to 'fake' such claims.

    Why not add the threadsafe text in the function description

    Joel Coehoorn : I wouldn't worry so much about 'faking' it. But concurrency is hard: it would be very likely that a bug has slipped through and that attribute is just incorrect.
    Jim Mischel : But if the attribute is incorrect, it's likely that the documentation (if any) would be just as incorrect.
  • There is no use case scenario of making a class synchronized, as far as method is concerned you use following coding style:

    using System.Runtime.CompilerServices;
    [MethodImpl(MethodImplOptions.Synchronized)]   
    void MyMethod()   
    {   
    DoSomething();   
    }
    
    Marc Gravell : The problem is; that still doesn't imply that the method is thread-safe -because another thread could be calling a different method that *doesn't* have the [MethodImpl], thus trashing each-other. Likewise even if all fields are readonly, fields on child objects could be mutable, and cause problems.
  • It is possible to make all access to your object serial via IContributeObjectSink/IContextAttribute although this will suffer from a large performance hit since it will require your object to subclass MarshalByRefObject,context creation overhead, etc...