Wednesday, March 16, 2011

What do Colleges now teach in BS in Computer Science?

20 years I was taught languages (Pascal, Basic, LISP), data structures and algorithms, and math classes. I would like to know what is being taught in the last 10 years?

Are there courses on process and life cycle?

Are there Microsoft .Net and Java specific courses?

Are there business application development and enterprise computing courses?

From stackoverflow
  • I finished my degree 2 years ago. We covered languages (Java, C, Eiffel, Lisp, Prolog), data structures, interface design, statistics, and math. There were theory courses as well (OS basics, machine language). You had some choice courses, so you could take some business courses, but it wasn't mandatory. Nor was the interface design course, but it did cover building business applications, and was a fairly popular choice.

    York University Computer Science Department

  • 15-10 years ago, in addition to the topics you mentioned, I took courses in operating systems, networks, computer graphics, AI, theory of computation, and human-computer interaction. Java just came about at the end of my undergrad years, and .Net did not exist yet. There were no business application development courses of any kind.

  • You could just pick your favorite university's web site and look at their degree plans and course catalog.

    Here's my school. And their course catalog.

  • Lots of math, Data Structures, Digital Systems, Computer Architecture, Analysis of Algorithms, general programming language concepts, OS, Software Engineering, and some other specialties as electives. These include things like AI, image processing, graphics, etc.

  • My school had required courses on general computer science topics, computer organization (i.e., how processors work and interact with memory, etc.), programming language theory, algorithms and data structures, and basic operating systems design. Electives included compiler optimization, graph theory, graphics, networks, and security, among others. Required math courses included calculus, discrete math, and probability and statistics.

    We were taught to program in Java on Red Hat Linux, although some courses utilized C and C++ as well; the programming language theory course used Haskell.

    We had only very basic instruction on the software development process and life cycle. But this is a good thing -- that's software engineering stuff, and computer science is not software engineering. We barely had time to scratch the surface of CS, so SE would've just been too time-consuming. (That said, seniors did take a course that involved the development of a software project using extreme/agile programming techniques.)

    Adam Jaskiewicz : I had pretty much the same courseload and languages, save that the Programming Languages course used Scheme rather than Haskell, and "computer organization" was called "computer architecture" and involved writing some basic stuff in MIPS assembly and making a simple 16 bit CPU in a logic simulator.
    mipadi : Yeah, the computer organization course I was also based on MIPS32, and we did similar stuff.
  • I finished my degree alittle more then a year ago. While obviously I can't speak for all programs. The curriculum I had was very similar to yours.

    C++ for most courses including data structures in C++. AI in prolog and python. I had an operating systems course where we used Java, my database course also used Java and JDBC. However, most .net and java specifics I have learned outside of school. My program really focused on CS theory and mathematics.

  • Obviously I can't speak for everyone, but this is from my own experience. I graduated in May 2007 with a BS in Computer Science.

    Several languages are still taught. My school focused on one language (Java) to teach to new students, but you learned more languages as you advanced. One course in particular was a survey of programming languages and different paradigms (OO, functional, and procedural languages are taught).

    There was a Software Engineering course that touched on processes. Lifecycle is taught from the beginning, since you can't get far without it.

    There were business application development courses that used VB.NET as a platform. There were also a few enterprise computing courses that used J2EE.

    There were also courses in

    • Algorithms and Data Structures
    • Operating Systems
    • Client-Server Programming
    • Network Administration
    • Database Design
  • Purdue University, taught C,C++,Java as primary languages and exposed us Scheme, Smalltalk, Ada, and Prolog.

    We also got to choose our own languages for certain project and classes, I usually would choose python or ruby.

    Also, learning and using Linux was mandatory.

    The classes offered were fairly standard: Data Structures, Networking, Artificial Intelligence, Database, Algorithms, Web Application Development, User Interface Design, Operating Systems, Compiler Construction, and Language design.

  • A lot will depend on what country you're in, and what school you go to.

    Certainly the basics are taught everywhere that I know of:

    • introductory programming
    • algorithm analysis
    • data structures
    • large project class
    • discrete math
    • programming languages

    Beyond that, it's largely up to the institution as to how math-/theory-/business-/practical-heavy they want to be. And whether it's a BS or BA.

  • http://www.gmu.edu/catalog/courses/cs.html

  • Rather than just say it, I'll let my school's CS and SE departments speak for themselves:

  • Many colleges and universities now follow the IEEE/ACM Model curriculum:

    http://www.acm.org/education/curricula-recommendations

    Cheers,

    -Richard

  • U of Idaho CS degree, Fall 08

Best free tool to build an exe from Java code?

I've used JSmoothGen in the past, but recently we've seen a number of machines that refuse to run the .exes that it generates. It also seems not to be actively maintained so heavily any more.

Are there any alternatives that are more actively maintained and more reliable?

From stackoverflow
  • The gnu compiler gcj

    jsight : I'm looking for more of a wrapper than a full to .exe compiler. I already know there isn't one of those that is fully compatible (though GCJ is much better than it used to be).
  • I use Launch4J which supports Windows, Mac and Linux. I suggest forgoing the somewhat flaky GUI tool and just writing the (short, readable) config file yourself.

    jsight : Perfect... thanks!
  • I found this article to be very informative http://www.excelsior-usa.com/articles/java-to-exe.html.

    Someone already mentioned Launch4j, however, I found Jsmooth to be alittle better. They are both very similar, but I would mess with both to see which you prefer.

    EDIT: Sorry, I somehow skimmed over your mention of Jsmooth in your question. If Jsmooth isn't working for you, then I would go for Launch4j. I still recommend that article.

  • This question is a duplicate of How can I convert my java program to an .exe file? in my eyes.

    PhiLho : Well, there is "best" and "free" added in the title... But it is nice to link to another resource.
  • It is also not entirely necessary to make an .exe. On Windows, at least, .jar files are executable so long as there is a Java runtime installed and the .jar extension has been set up on the machine.

    [NOTE: I just discovered that something that has broken the file association, which had previously worked for me. It now only works when I am administrator, and the JAR icon even disappears otherwise. I assume that some recent install has messed with that and the candidates are (1) OpenOffice.org 3.0, (2) WinRAR, or (3) a Java update download. However, the following all work when the association is made to work.]

    The "program" Clicker.jar runs as a Java application when (1) I double-click on it in a Windows Explorer window, (2) When I create a console shell where I am in the same directory and I perform the command ">Clicker.jar" (3) when I send a shortcut to my desktop and double-click on it, and (4) when I put the full path in the Windows XP Run ... box.

    I don't know that these will be found in a PATH search, and I normally wouldn't arrange that anyhow.

  • http://sourceforge.net/projects/javaround

    HTH

Is JSON validation a best practice?

Is it a best practice to validate JSON?

With both a JSON schema proposal and a JavaScript implementation of a JSON Schema validator, this practice would seem relatively frictionless to implement. So, is it a no-brainer that should be part of any robust application? Or do you employ other preferred strategies to handle bad JSON?

From stackoverflow
  • On the server, validation of data coming from outside is a must.

    In the browser, it is redundant from a security POV, if you can vouch that the JSON is generated by server code you control and that any data it depends on has been validated on the server. Even so it can still be useful for debugging.

    happyappa : How are you validating on the server side? I'm kicking my JSON out from PL/SQL, sending it back to a receiving DOJO component. I could see by the JSON references above how to do the validation on the client side...but the server side isn't as clear.
    moonshadow : I mean validate on the server data received from the outside world. If you're bothering to marshall it as JSON in that direction. I'm thinking here of security; for debugging data flowing the other way, validation in the client is good enough. Unhelpfully, I roll my own validation code, I'm afraid.
  • My 2c on this is that:

    (a) Yes, obviously incoming data should be validated, but

    (b) The best place to do this is NOT with Json data as is, but with actual business logic objects, iff data binding is used. JSON validation makes only sense if you handle "raw" JSON, but most services (at least in Java) use data binding first and then operate on biz logic objects, not on data format (which often is almost an implementation detail)

  • I would recommend inclusion of json validation as part of a service perimeter solution. This pattern is described at http://bit.ly/5sSzen

In C#, is accessing the current object's properties through this.XYZ considered poor style compared to just XYZ

Is it a simple case of just never using the this.XYZ construct?

From stackoverflow
  • It's only considered poor style if it violates your style guidelines. Sometimes using this is necessary to qualify a member variable over a local variable:

    public MyType(int arg)
    {
        this.arg = arg;
    }
    

    This problem can also be mitigated with style guidelines. For example, prefix members with "_":

    public MyType(int arg)
    {
        _arg = arg;
    }
    

    HTH, Kent

  • I wouldn't say it's poor style - but it's not particularly idiomatic.

    My almost sole use of this.foo is when copying parameters into fields:

    public Person (string name, string occupation)
    {
       this.name = name;
       this.occupation = occupation;
    }
    
    Will : You don't preface your fields with underscores?
    Jon Skeet : Nope. I never have in my personal code. I've worked at places which do, and I've worked at places which don't. I don't care much any more. What scares me is that I just subconsciously used "brace at end of line" which is the Google style rather than my personal style. Editing...
    Charles Bretana : in general, (except for in initializers - cctors) I always set the public properties, not the private fields, in constructors... so the ctor parameter is lowerCase, and the property is UpperCase... (no need for this.) Name = name;
    Jon Skeet : Charles: That doesn't work when the field is readonly so the property has no setter...
  • I've never heard of it being a style issue. I used to do it all the time to get intellisense, but then I started using ctrl-j, then I just found myself remembering my object's properties without having to use a crutch.

    Probably because my objects have become less complex as I gain more experience...

  • I always use this. for global variable. This way, I can clearly know that I am using a global variable without having to use prefix like "_".

    Kent Boogaart : Yes, because it's so much easier to prefix with "this." than with "_" ;)
    Daok : well, it's clearer in my opinion. And the Intellisense is there... it's part of the Framework.. so why not.
    Daok : I have to add that if you do it all the time and not only for parameter passing to global than it's become easy to follow a code because it's always the same. not "sometime" it's used for global and some time not... but it's just my opinion.
    Kent Boogaart : Yep, makes sense. I haven't yet worked on a project that required prefixing with "this." so don't have any experience having to do so on a regular basis. Was just poking fun...
    Daok : No problem, I think it's really just an opinion and they aren't any good answer.
  • The MS tool StyleCop insists on the this.XYZ (or should that be this.Xyz) variant when analysing source code.

    Kent Boogaart : That's just based on its default rules. You can customize the rules to suit your organization or team.

Looking for an XSLT community

I do a lot of XSLT programming. I also do Java, PL/SQL, JavaScript, and a few others. I can easily find communities of Java and JavaScript programmers via the web. PL/SQL is a little more difficult, but between OTN and AskTom, I do pretty well. But XSLT seems to be neglected to me. Where do you go for XSLT? I know about W3Schools, and its great, but I'm beyond tutorials.

While SO is a great community, it is telling that the tags for this question have a combined usage of a only 188.

From stackoverflow
  • not sure if it is still active, but you might find http://www.exslt.org/ interesting.

    dacracot : Latest news post on that site was over two years ago... 09/05/2006... but thanks.
  • Stackoverflow, of course!

    Altova has some impressive looking XML tools. I often see them listed in Google's results when I am looking for general XML help. A quick search on their site gave a decent looking list of XSLT docs.

    dacracot : Yeah, yeah... SO... I knew someone would say that. And I don't need a tool, I need a community.
    dacracot : Not saying that SO is just a tool, and its a great community, but it is not XSLT oriented, it anything and everything oriented. Altova's stuff is the tool I refer to.
    Jason Z : Stackoverflow is a community, and Altova's forums appear to meet the critera of a community as well.
    dacracot : I guess my point is that their forum for XSLT is labeled: "Creating, debugging and executing XSLT and XQuery stylesheets with Altova products"... sounds like a tool forum, hence the "with Altova products".
  • microsoft.public.xsl looks active. If newsgroups are your kind of thing.

    dacracot : Am I gonna get flamed there since I use Java and Oracle's XDK?
    Tomalak : Not, if you don't mention it. ;-) No, of course not. It is about XSL, not about Microsoft.
  • The xsl-list is really active, and a lot of the big names in XSLT (such as Michael Kay) participate.

  • The xsl-list is the mailing list dedicated to XSLT questions.

    XSLT questions are often submitted and answered:

    Hope this helped.

    Cheers,

    Dimitre Novatchev

Problem running a Jar file

I've compiled a java project into a Jar file, and am having issues running it.

When I run:

java -jar myJar.jar

I get the following error

Could not find the main class: myClass

The class file is not in the root directory of the jar so I've tried changing the path of the main class to match the path to the class file and I get the same issue.

Should I be flattening the file structure? if so how do I do this. I'm using Ant to build the Jar file if thats of any use.

UPDATE

Here is the contents of the jar and the relevant Ant sections, I've changed the name of the firm I work for to "org":

META-INF/
META-INF/MANIFEST.MF
dataAccessLayer/
dataAccessLayer/databaseTest.class
org/
org/eventService/
org/eventService/DatabaseObject.class
org/eventService/DatabaseObjectFactory.class
org/eventService/DbEventClientImpl$HearBeatMonitor.class
org/eventService/DbEventClientImpl.class
org/eventService/EmptyQueryListException.class
org/eventService/EventHandlerWorkItem.class
org/eventService/EventProcessor.class
org/eventService/EventTypeEnum.class
org/eventService/EventWorkQueue$MonitorThread.class
org/eventService/EventWorkQueue$PoolWorker.class
org/eventService/EventWorkQueue.class
org/eventService/FailedToLoadDriverException.class
org/eventService/IConnectionFailureListener.class
org/eventService/InvalidEventTypeException.class
org/eventService/JdbcInterfaceConnection.class
org/eventService/NullArgumentException.class
org/eventService/OracleDatabaseObject.class
org/eventService/ProactiveClientEventLogger.class
org/eventService/ProactiveClientEventLoggerException.class
org/eventService/PropertyMap.class
org/eventService/SQLServerDatabaseObject.class
org/eventService/TestHarness.class
org/eventService/Utilities.class

And the ant target:

<target name="compile" depends="init" description="compile the source ">
    <javac srcdir="src" destdir="bin" classpathref="project.class.path"/>
</target>
<target name="buildjar" description="build jar file" depends="compile">
    <mkdir dir="dist"/>
    <jar destfile="dist/myJar.jar" basedir="bin" includes="**/*.class" >
        <manifest>
            <attribute name="Main-Class" value="org.eventService.ProactiveClientEventLogger"/>
        </manifest>
     </jar>
</target>
From stackoverflow
  • In your manifest file, make sure you have the attribute Main-Class set to the name of the class containing your main() method. For example, if the package-qualified name of the class is my.cool.Class, then, in your JAR manifest, Main-Class should be set to my.cool.Class.

    Also made sure that you have a package declaration in your .java files (for example, in Class.java, make sure you have the proper package my.cool; declaration). Also, make sure your directory hierarchy is set up correctly (my.cool.Class should be in $SRC/my/cool/Class.java).

    Omar Kooheji : I've done all that... and it's still not working... Although I'd used slashed and not dots to deliminate them. it doesn't work with dots either...
    John Burton : The manifest files are very picky about capitalization, white space and so on. Make sure your lines are properly terminated too if the Main-Class line is the last one.
  • You should specify your main class during jar creation with full path, something like:

    <target name="jar" depends="compile">
         <delete file="myJar.jar"/>
         <delete file="MANIFEST.MF"/>
         <manifest file="MANIFEST.MF">
            <attribute name="Main-Class" value="my.package.myClass"/>
        </manifest>
    
        <jar destfile="myJar.jar"
               basedir="."
               includes="**/*.class"
               manifest="MANIFEST.MF" />
    </target>
    

Search an assembly for all child types?

I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?

I know this is a strange request but its something I'm playing with none-the-less.

From stackoverflow
  • Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)

    EDIT: As requested, here's an example - it finds everything in mscorlib which implements IEnumerable. Note that life is somewhat harder when the base type is generic...

    using System;
    using System.Collections;
    using System.Linq;
    using System.Reflection;
    
    class Test
    {
        static void Main()
        {
            Assembly assembly = typeof(string).Assembly;
            Type target = typeof(IEnumerable);        
            var types = assembly.GetTypes()
                                .Where(type => target.IsAssignableFrom(type));
    
            foreach (Type type in types)
            {
                Console.WriteLine(type.Name);
            }
        }
    }
    
    TheDeeno : Jon Skeet is everywhere! haha, thanks.
    Aaron Wagner : I'd love to see that code since I can't get Type.IsAssignableFrom() to work the way I'm understanding it. I'm on 3.5 sp1. Thanks!
    Aaron Wagner : Thank you Jon Skeet!
  • var a = Assembly.Load("My.Assembly");
    foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
    {
        // there you have it
    }
    
    Jon Skeet : No, that won't work - "is" checks whether an *object* implements an interface, and the instance of "Type" doesn't implement IMyInterface. That's why I suggested using Type.IsAssignableFrom.
  • Or for subclasses of a base class:

    var a = Assembly.Load("My.Assembly");
    foreach (var t in a.GetTypes().Where(t => t.IsSubClassOf(typeof(MyType)))
    {
        // there you have it
    }
    

Firefox style onclick arguments in IE

In firefox when you add an onclick event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example

document.body.onclick = handleClick;

function handleClick(e)
{
    // this works if FireFox
    alert(e.target.className);
}

Is there any way to approximate this in IE? i need to be able to detect which element is clicked from an event handler on the body element.

From stackoverflow
  • I think IE uses a variable called event. See if that works?

  • In IE it's

    e.srcElement
    
  • That is not the approved notation to add events to dom nodes.

    if (el.addEventListener){
      el.addEventListener('click', modifyText, false); 
    } else if (el.attachEvent){
      el.attachEvent('onclick', modifyText);
    }
    

    Is the recommended Notation for binding click events cross-browser friendly.

    See:

    Also, when an event is clicked, the callback function that is executed contains an object "this" which is the entity that was clicked.

    function foo() { 
       window.open(this.src, '_blank'); 
    }
    
    J-P : Obviously the Advanced event registration model has its benefits but for the most part people can just use the traditional notation. (One benefit of the traditional notation is that it plays nicer with screen readers)
  • Here is how would I do it in case I cannot use jQuery

    document.body.onclick = handleClick;
    
    function handleClick(e)
    {
        //If "e" is undefined use the global "event" variable
        e = e || event;
    
        var target = e.srcElement || e.target;
        alert(target.className);
    }
    

    And here is a jQuery solution

    $(document.body).click(function(e) {
      alert($(this).attr("class"));
    });
    
    J-P : In your jQuery example there is no point in passing the event.
    korchev : Yes, indeed. I am just passing it to show how it's done if needed.

C++ library integration to iPhone application

Thanks for your support, but will it(integration of exsisting C++ library with iPhone application) effect my application at the time of submision to Apple Store? Are there any chances of disapproval of application from Apple Store?

Thanks & Regards

Khushi

From stackoverflow
  • As long as your library is statically linked, you shouldn't have any problems with the approval process.

Checking an assembly for a strong name

Is it possible to check if a, dynamically loaded, assembly has been signed with a specific strong name? Is it enough / secure to compare the values returned from AssemblyName.GetPublicKey() method?

Assembly loaded =
    Assembly.LoadFile(path);

byte[] evidenceKey =
    loaded.GetName().GetPublicKey();

if (evidenceKey != null)
{
    byte[] internalKey =
        Assembly.GetExecutingAssembly().GetName().GetPublicKey();

    if (evidenceKey.SequenceEqual(internalKey))
    {
        return extension;
    }
}

Can't this be spoofed? Not sure if the SetPublicKey() method has any effect on a built assembly, but even the MSDN documentation shows how you can use this on a dynamically generated assembly (reflection emit) so that would mean you could extract the public key from the host application and inject it into an assembly of your own and run mallicious code if the above was the safe-guard, or am I missing something?

Is there a more correct and secure approach? I know if the revered situation was the scenario, i.e where I wanted to secure the assembly from only being called by signed hosts then i could tag the assembly with the StrongNameIdentityPermission attribute

Thanks

From stackoverflow
  • There's little point in testing the strong name after the assembly got loaded. An attacker could simply inject a module constructor in the assembly and execute any code desired. The .NET 3.5 SP1 version of the framework followed suit and is no longer verifying the strong name of assemblies that get loaded from trusted locations. Improving startup times by about 40%.

    Key point is: once an attacker compromises the machine to a point where he is able to inject an assembly in the probing path of your app, he won't bother doing it the hard way. He'd just replace your .exe

    TheCodeJunkie : Actually this is a situation where extensions (in the form of assemblies) can be added to the application i.e they are loaded from a directory using Assembly.LoadFile and I only want to be able to load extensions which have been signed with the same strong name as the host application.
    TheCodeJunkie : So this isn't a case of safe-guarding an entire system or application, but restricting whom is able to write extensions to the application itself. No strong name, sorry your extension will not be loaded
  • I'll answer my own question. There is no managed way to check the signature of an assembly and checking the public key leaves you vulnerable to spoofing. You will have to use p/Invoke and call the StrongNameSignatureVerificationEx function to check the signature

    [DllImport("mscoree.dll", CharSet=CharSet.Unicode)]
    static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool  pfWasVerified);
    
    Mehrdad Afshari : Whatever you do can leave you to spoofing as the attacker can easily circumvent the check in your assembly and reassemble the modified IL and resign the assembly with his own key.

Where is the Silverlight Calendar Control?

Just playing around with the now released Silverlight 2.0. I'm trying to put a simple Calendar in a control. However the project doesn't seem to know what I'm talking about:-

<UserControl x:Class="MyFirstSL2.Test"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
>
  <Grid Background="#FF5C7590">
    <Calendar />
  </Grid>
</UserControl>

Visual Studio 2008 just puts blue line under the Calendar saying the type Calendar not found. Do I need to add an assembly? Which one? Do I need to add another namespace to the Xaml?

From stackoverflow
  • I'm pretty sure there's no calendar control in Silverlight that is analogous to the ASP.Net control or the windows forms control. I'm pretty sure there's not a pre-packaged control like that for WPF, either.

    MojoFilter : Haha. Ok, so I guess there is one :)
    Rob Prouse : Microsoft has released one for WPF too. Check CodePlex.
  • The calendar control is an SDK control in the assembly System.Windows.Controls namespace -- look at %program files%\Microsoft SDKs\Silverlight\v2.0\Libraries\Client add a namespace to your xaml (after you add a reference):

    xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    

    Then to use:

    <basics:Calendar />
    

    Hope this helps!

    AnthonyWJones : Spot on. Thanks.
  • Anyone succeeded in embedding a XAML calendar control?

  • add a reference to

    C:\Program Files\Microsoft SDKs\Silverlight\v2.0\Libraries\Client

    system.windows.controls.dll

    Use Expressions Blend or VS2008 SP1 to add the control to the UI

  • Instead of trying to figure out how the toolkit allows for an embeded calendar control I created a custom control here http://slcalendarcontrol.codeplex.com/ check it out.

Can you have protected nested classes in C++?

I have a class that only really ever needed by classes in a certain class hierarchy. I wanted to know if it is possible to nest the class in the highest class's protected section and have all the other classes automatically inherit it?

From stackoverflow
  • "Inherit" is the wrong word to use since it has a very specific definition in C++ which you don't mean, but yes you can do that. This is legal:

     class A {
       protected:
       class Nested { };
     };
    
     class B : public A {
       private:
       Nested n;
     };
    

    And code that is not in A or something that derives from A cannot access or instantiate A::Nested.

    Kieveli : Hmm What happens if class B provides an accessor method for Nested n? Probably a compile error?
    MSalters : Actually, no. When declaring methods of B, name lookup also happens in the scope of class B. And in B scope, A::Nested is accessible. Hence, A::Nested& B::Get_n() is OK.
    Tyler McHenry : Hm, you're correct. A::Nested is accessible since B can return an A::Nested from a public function. B it's still not instantiable, so interestingly this leads to the situation where the caller is not allowed to store the return value of B::Get_n().

Select X Most Recent Non-Consecutive Days Worth of Data

Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.

From stackoverflow
  • I don't know the SQL Server syntax, but you need to:

    1) Select the dates (with time component truncated) in descending order

    2) Pick off top 5

    3) Obtain 5th value

    4) Select data where the datetime >= 5th value

    Something like this "pseudo-SQL":

    select *
    from data
    where datetime >=
    ( select top 1 date
      from
      ( select top 5 date from
        ( select truncated(datetime) as date
          from data
          order by truncated(datetime) desc
        )
        order by date
      )
    )
    
    Brian : I have a bad feeling that this mechanism will end up being less efficient that it should be.
    Tony Andrews : Me too - any ideas?
    Tomalak : Have a computed column for the TruncatedDate, and an index on it. Then selecting the DISTINCT TOP 5 ORDER BY should be a snap, and you can use the returned value right away to filter efficiently.
  • Following the approach Tony Andrews suggested, here is a way of doing it in T-SQL:

    SELECT
      Value,
      ValueDate
    FROM
      Data
    WHERE
      ValueDate >= 
      (
        SELECT 
          CONVERT(DATETIME, MIN(TruncatedDate))
        FROM 
          (
             SELECT DISTINCT TOP 5 
               CONVERT(VARCHAR, ValueDate, 102) TruncatedDate
             FROM 
               Event
             ORDER BY 
               TruncatedDate DESC
          ) d
      )
    ORDER BY
      ValueDate DESC
    
  • This should do it and be reasonably good from a performance standpoint. You didn't mention how to handle ties, so you can add the WITH TIES clause if you need to do that.

    SELECT TOP (@number_to_return)
         *   -- Write out your columns here
    FROM
         dbo.MyTable
    ORDER BY
         MyDateColumn DESC
    

Is there any general purpose breadcrumbs management library/code in .net?

I want to make a msdn style breadcrumbs navigation

From stackoverflow
  • Yes - look at the SiteMapPath and the other menu/site navigation controls in Visual Studio toolbox.

    suhair : I know that but it is too trivial!
    flesh : Actually there is quite a lot of configuration available to you using the controls in combination. If they are still too trivial, write your own.
    Stefan : If all you want is MSDN style breadcrumbs, the SiteMapPath et. al. should be more than enough.

Possible to import an image into AS3 without PHP?

In actionscript 3 is it possible to allow a user to upload an image into a flash movie at runtime without POSTing to a PHP script? I dont want to export the image or save it anywhere I just want to be able to display the image in the flash movie

fingers crossed

From stackoverflow
  • The flash developer at work, seems to believe that it is not possible. That said you don't have to use PHP, you could use any server side technology that allows uploading (ASP.NET, Python, etc)

    John Burton : It is possible in flash player 10 which is newly released
  • This feature has just been added in Flash Player 10 / Flash CS4, so if you can use that you can do it.

  • Yes, you can if you are targeting Flash Player 10. Use the FileReference.load() method. Once the file is loaded, you can access to the raw data as a ByteArray, using the data property. In flex you can pass that to an Image component. In plain Actionscript, you can use the Loader.loadBytes() method to the display the loaded image.

Can you hint return types in PHP 5.2.5?

I think my eclipse's ctrl+clicking links might benefit greatly...

Edit: I'm using eclipse PDT.

Edit 2: I'm very happy with the solution of putting docblocks before functions (and variables) with an @return or @var statement, I've just updated the documentation of my app and now eclipse is showing me what functions are available to what objects!

Awesome.

From stackoverflow
  • Short answer: no.

    Long answer: consider adding docblocks with @returns declarations.

    Dean : Nope, docblock didn't help.
    azkotoki : It works for me. What eclipse plugin are you using for php development?
    troelskn : It's @return -- not @returns
    Dean : Strange, after some time it did work. But I didn't see a "building" status bar at the bottom or anything like that. Thanks!
  • // [...]
    /**
     * Return the Request object
     *
     * @return Zend_Controller_Request_Abstract
     */
    public function getRequest()
    {
        return $this->_request;
    }
    // [...]
    

    works perfectly with Eclipse PDT. Which plugin do you use?

    MrSnowflake : How do you define the type of objects inside a returned array?
    Stefan Gehrig : I don't think that's possible with current Eclipse PDT or Netbeans.
    Stefan Gehrig : As far as I know at least the PDT team is looking at this issue.
  • The only way to hint return type in PHP is to use a good IDE like Eclispe PDT or Zend Studio with standard comment block. PHP simply can n not predict return type because it is dynamically typed language so type checking is done in the run time unlike for the statically typed languages like C#, JAVA and C++.

How to Query A DataGridView Using Linq

I have a DataGridView that I want to query using Linq (C# WinForm). I want to "count" rows where a certain criteria is met. For example,

variable1 = "count rows where ColumnBoxAge > 3 || < 5"

label1.Text = variable1

How to do this in C# WinForm using Linq?

From stackoverflow
  • I don't know if it could work but you can try this;

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 ||
         c.Field<int>("ageColumn") < 5).Count();
    

    Edit : Where instead of Select.

    MarlonRibunal : it's counting all rows in the dgv...not what I want. Shld be "count rows where BoxAge is between 3 and 5"...
    MarlonRibunal : Now that's working...(See Edit)
  • So your query is wrong! Try to put '&&' instead of '||';

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
         c.Field<int>("ageColumn") < 5).Count();
    

    Edit : Where instead of Select.

  • @yapiskan

    dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
         c.Field<int>("ageColumn") < 5).Count();
    

    .Where instead of .Select

    Thank you very much! I appreciate your help.

    yapiskan : Oops, sure it is!

Regex for parsing SQL parameters

If I have a query such as SELECT * from authors where name = @name_param, is there a regex to parse out the parameter names (specifically the "name_param")?

Thanks

From stackoverflow
  • This is tricky because params can also occur inside quoted strings.

    SELECT * FROM authors WHERE name = @name_param 
      AND string = 'don\'t use @name_param';
    

    How would the regular expression know to use the first @name_param but not the second?

    It's a problem that can be solved, but it's not practical to do it in a single regular expression. I had to handle this in Zend_Db, and what I did was first strip out all quoted strings and delimited identifiers, and then you can use regular expressions on the remainder.

    You can see the code here: http://framework.zend.com/code/browse/~raw,r=8064/Zend_Framework/trunk/library/Zend/Db/Statement.php

    See functions _stripQuoted() and _parseParameters().

    Jonathan Leffler : Not to mention parameter names appearing in SQL comments. Regexes are great, but not necessarily great for parsing jobs.
    Bill Karwin : Yes, good point about the SQL comments.
  • Given you have no quoted strings or comments with parameters in them, the required regex would be quite trivial:

    @([_a-zA-Z]+)       /* match group 1 contains the name only */
    

    I go with Bill Karwin's recommendation to be cautious, knowing that the naïve approach has it's pitfalls. But if you kow the data you deal with, this regex would be all you need.

ITemplate and DataGrid Column in Codebehind

I have a situation where I need to work with a datagrid and adding columns dynamically in PageInit as the grid has a few conditional requests that it must handle. I'm moving along easily with BoundColumns, and ButtonColumns, those are easy. The problem is with the creation of a TemplateColumn via code. I have found examples out there about creating a custom class that add controls dynamically by creating a class that uses an implementation of ITemplate. That works, however, I'm struggling with how to databind elements.

In my grid I would have used <%= DataBinder.Eval(Container.DataItem, "MyValue") %> or similar, but that isn't an option here. The Container when inside ITemplate doesn't have a data item property either, so I can't bind there. Anyone have advice or links that might help, I'm just not finding the right things in google.

From stackoverflow
  • You can attach an event handler to the DataBinding event of the controls you create in ITemplate.InstantiateIn as in this MSDN Article. The sender will be the control and the NamingContainer property will be the DataGridItem, which has a reference to the DataItem which you can use to get whatever data you need.

    Mitchel Sellers : Awesome! That is the article I was looking for. What a major PITA to get this done....

Setting up Alerts in SharePoint

Hi, i am running MOSS 2007 on a Windows 2003 box. I need to know what configuration must be done to get Alerts to work. SMTP and that stuff.

What am i missing because when i create my alert it creates it but it does not send the email to show me that something changed in my document library or on any document it self.

I did install the Email Services under Windows Components and the SMTP under IIS. In my SharePoint Central Admin i did change my settings in Outgoing and incoming email settings ( Under the Topology and Services section ).

What else am i missing?

Please Help Etienne

From stackoverflow
  • Did you setup the Web Application Outgoing E-mail Settings in your Central Administration? Y

    Etienne : Yes i did.........
  • I don't think this question is really appropriate for StackOverflow - its not a programming question, see the FAQ.

    But anyway - could be anti-virus or smtp relay rules stopping sharepoint sending smtp to your mail server. Try this tool to diagnose.

    http://www.simplecomtools.com/smtptesttool.html

    If that doesn't work then its MS support - the newsgroups are littered with the carcasses of people trying to resolve alert email problems!

    Etienne : Thank you for the reply but i undertand regards to the "its not a programming question" but then they must not allow SharePoint to be a Tag since most of SharePoint is configuration anyways!!
  • Has the SMTP server been configured to allow the MOSS server to relay mail to it?

  • Ensure that you have configured the SMTP server properly by configuring an account and associating to a mail client Outlook. Check the Servers outgoing and incoming capabilites from the mail client first.

    Ensure that you have subscribed to the alerts properly in a list

  • Etienne,

    It might be worth your while to repost this question over on ServerFault. This question seems like it would be more in keeping with their knowledge base.

    Etienne : Thanks, will do....as you can see i asked this question 6 months ago. So that was before ServerFault was there. :)
    Onorio Catenacci : @Etienne -- my answer was meant to be helpful - not a criticism.

How can I get the database name from a Perl MySQL DBI handle?

I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.

I don't think I can use:

$dbh->{Name}

because I call USE new_database and $dbh->{Name} only reports the database that I initially connected to.

Is there any trick or do I need to keep track of the database name?

From stackoverflow
  • You can ask mysql:

    ($dbname) = (each %{$dbh->selectrow_hashref("show tables")}) =~ /^Tables_in_(.*)/;
    

    Update: obviously select DATABASE() is a better way to do it :)

    Harry : Now that's a cool trick.
  • Try just executing the query

    select DATABASE();
    

    From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)

    Harry : Yes the query works: my ($dbname) = $dbh->selectrow_array("select DATABASE()");
  • When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL USE database_name will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.

  • FWIW - probably not much - DBD::Informix keeps track of the current database, which can change if you do operations such as CREATE DATABASE. The $dbh->{Name} attribute is specified by the DBI spec as the name used when the handle is established. Consequently, there is an Informix-specific attribute $dbh->{ix_DatabaseName} that provides the actual current database name. See: perldoc DBD::Informix.

    You could consider requesting the maintainer(s) of DBD::MySQL add a similar attribute.