Stack Overflow Post Examples

download Stack Overflow Post Examples

of 30

Transcript of Stack Overflow Post Examples

  • 7/27/2019 Stack Overflow Post Examples

    1/30

    I too get explorer crashes in Vista (I'm not in the 64Bit version though). I'm using Vista Super Saijen (or whatever they are calling the most expensive version). I'm not having any bugs with Tortoise.

    My explorer does, however, crash about every other day (sometimes multiple times a day if it's having an "off" day). I'm not positive it's being caused by TortoiseSVN though. From what I hear, the explorer just crashes a lot in Vista...

    Have you tried uninstalling Tortoise and using Windows for a day or two and seeing if it still crashes? Do you restart your computer at least once a day (Itseems the longer I go between restarts, the worse the crashes get)?

    ----------

    I may be old fashioned, but I prefer my text editor.

    I use emacs, and it has a fairly decent xml mode.

    Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able to deal with huge files, but some text editors may not be able to handle them. How big are we talking about?

    ----------

    I have a Ruby on Rails Website that makes HTTP calls to an external Web Service.

    About once a day I get a SystemExit (stacktrace below) error email where a call to the service has failed. If I then try the exact same query on my site moments later it works fine.It's been happening since the site went live and I've had no luck tracking downwhat causes it.

    Ruby is version 1.8.6 and rails is version 1.2.6.

    Anyone else have this problem?

    This is the error and stacktrace.

    A SystemExit occurred/usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in `exit'/usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in `exit_now_handler'/usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/inflector.rb:250:in `to_proc'/usr/local/lib/ruby/1.8/net/protocol.rb:133:in `call'

    /usr/local/lib/ruby/1.8/net/protocol.rb:133:in `sysread'/usr/local/lib/ruby/1.8/net/protocol.rb:133:in `rbuf_fill'/usr/local/lib/ruby/1.8/timeout.rb:56:in `timeout'/usr/local/lib/ruby/1.8/timeout.rb:76:in `timeout'/usr/local/lib/ruby/1.8/net/protocol.rb:132:in `rbuf_fill'/usr/local/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'/usr/local/lib/ruby/1.8/net/protocol.rb:126:in `readline'/usr/local/lib/ruby/1.8/net/http.rb:2017:in `read_status_line'/usr/local/lib/ruby/1.8/net/http.rb:2006:in `read_new'/usr/local/lib/ruby/1.8/net/http.rb:1047:in `request'

  • 7/27/2019 Stack Overflow Post Examples

    2/30

    /usr/local/lib/ruby/1.8/net/http.rb:945:in `request_get'/usr/local/lib/ruby/1.8/net/http.rb:380:in `get_response'/usr/local/lib/ruby/1.8/net/http.rb:543:in `start'/usr/local/lib/ruby/1.8/net/http.rb:379:in `get_response'

    ----------

    Sonic File Finder for when you have loads of files in your solutions and searching for them in the solution explorer becomes a pain in the wrist.

    You might also find DPack interesting. Several tools and enhancements rolled into one neat package.

    ----------

    You should look into DBUnit, or try to find a PHP equivalent (there must be one out there). You can use it to prepare the database with a specific set of data which represents your test data, and thus each test will no longer depend onthe database and some existing state. This way, each test is self contained andwill not break during further database usage.

    Update: A quick google search showed a DB unit extension for PHPUnit.

    ----------

    I'm looking for a good editor for both HTML and CSS. I currently use the Firebug Firefox extension, and this is a great tool, but I'm looking for something Ican use without necessarily firing up a browser. Ideally it would have a live preview of what I'm coding.

    Edit: As a student, I have access to MSDN. also, i have access to Windows, Ma

    c, and Linux. So any platform will do.

    ----------

    You're better off using prepared statements with placeholders. Are you usingPHP, .NET...either way, prepared statements will provide more security, but I could provide a sample.

    ----------

    Many years ago, to provide an age calculator gimmick on my website, I wrote a function to calculate age to a fract

    ion. This is a quick port of that function to C# (from the PHP version). I'm afraid I haven't been able to test the C# version, but hope you enjoy all the same!

    (Admittedly this is a bit gimmicky for the purposes of showing user profileson Stack Overflow, but maybe readers will find some use for it. :-))

    double AgeDiff(DateTime date1, DateTime date2) {
    double years= date2.Year - date1.Year;

    /*
    * If date2 and date1 + round(da

  • 7/27/2019 Stack Overflow Post Examples

    3/30

    te2 - date1) are on different sides
    * of 29 February, then our partial year is considered to have 366
    * days total, otherwise it's 365. Note that 59 is the day number
    * of 29 Feb.
    */
    double fraction =365
    + (DateTime.IsLeapYear(date2.Year) && date2.DayOfYear>= 59
    && (date1.DayOfYear < 59 || date1.DayOfYear> date2.DayOfYear)
    ? 1 : 0);

    /*
    * The onlyreally nontrivial case is if date1 is in a leap year,
    * and date2 is not. So let's handle the others first.
    */
    if (DateTime.IsLeapYear(date2.Year) == DateTime.IsLeapYear(date1.Year))
    return years + (date2.DayOfYear - date1.DayOfYear) / fraction;

    /*
    * If date2 is in aleap year, but date1 is not and is March or
    * beyond, shift up by a day.
    */
    if (DateTime.IsLeapYear(date2.Year)) {
    return years + (date2.DayOfYear - date1.DayOfYear
    - (date1.DayOfYear >= 59 ? 1 : 0)) / fraction;
    }

    /*
    * If date1 is not on29 February, shift down date1 by a day if
    * March or later. Proceed normally.
    */
    if (date1.DayOfYear != 59) {
    return years +(date2.DayOfYear - date1.DayOfYear
    + (date1.DayOfYear > 59? 1 : 0)) / fraction;
    }

    /*
    * Okay, here date1 is on 29 February, and date2 is not on a leap
    * year. What to do now? On 28 Febin date2's year, the ``age''
    * should be just shy of a whole number, and on 1 Mar should be
    * just over. Perhaps the easiest way is to a pointhalfway
    * between those two: 58.5.
    */
    return years + (date2.DayOfYear - 58.5) / fraction;
    }

    ----------

    The way I typically go about coding permission systems is having 6 tables.

    Users - this is pretty straight forward it is your typical users tableGroups - this would be synonymous to your departmentsRoles - this is a table with all permissions generally also including a human readable name and a descriptionUsers_have_Groups - this is a many-to-many table of what groups a user belongs toUsers_have_Roles - another many-to-many table of what roles are assigned to

    an individual userGroups_have_Roles - the final many-to-many table of what roles each group has

    At the beginning of a users session you would run some logic that pulls out every role they have assigned, either directory or through a group. Then you codeagainst those roles as your security permissions.

    Like I said this is what I typically do but your millage may vary.

    ----------

    Even though I have a robust and fast computer (Pentium Dual Core 2.0 with 2GbRAM), I'm always searching for lightweight software to have on it, so it runs fast even when many apps are up and running simultaneously.

    On the last few weeks I've been migrating gradually to Linux and want to install a free lightweight yet useful IDE to program on C++ and PHP. Sintax highlighting and code completition tips are must-haves.

    So, I'd like to receive some suggestions from you, guys.

  • 7/27/2019 Stack Overflow Post Examples

    4/30

    ----------

    Right-click on the Source view of an HTML / ASP page and select "Formatting and Validation".

    Click "Tag Specific Options".Expand "Client HTML Tags" and select the heading.Click "New Tag...".And just fill it in!

    I wish that I could add custom CSS values as well.

    ----------

    Should you set all the objects to null (Nothing inVB.NET) once you have finished with them?

    I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in me

    mory or at least in part?

    I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).

    So with this in mind will setting it to null speed up the systemreleasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?

    MSDN articles never do this in examples and currently I do this as I cannotsee the harm. However I have come across a mixture of opinions so any comments are useful.

    ----------

    Your CAST-FLOOR-CAST already seems tobe the optimum way, at least on MS SQL Server 2005.

    Some other solutions I've seen have a string-conversion, like Select Convert(varchar(11), getdate(),101) in them, which is slower by a factor of10.

    ----------

    Original Question

    If you are given N maximally distant colors (and some associated distance metric), can you come up with a way to sort those colors into some order such thatthe first M are also reasonably close to being a maximally distinct set?

    In other words, given a bunch of distinct colors, come up with an ordering soI can use as many colors as I need starting at the beginning and be reasonably

  • 7/27/2019 Stack Overflow Post Examples

    5/30

  • 7/27/2019 Stack Overflow Post Examples

    6/30

    Single executable (Linux)

    Freeze - works the same waylike py2exe but targets Linux platform

    Single executable (Mac)

    py2app - again, works like py2exe but targets Mac OS

    ----------

    Oh, in WinForms you definitely should be able to get it to work. The only thing you have to watch out for is things happening on different threads.

    I have an old CodeProject article here which should help:

    http://www.codeproject.com/KB/exception/ExceptionHandling.aspx

    ----------

    As far as I know the LINQ library is only available since the framework 3.0.If you want to use something similar in the framework 2.0, you would need to rewritte it yourself :) or find a similar third-party library. I only found a bit of information here but it didn't convinced me either.

    ----------

    SciTEhttp://www.scintilla.org/SciTE.html

    ----------

    In many places,(1,2,3) and [1,2,3] can be used interchangably.

    When should I use one or the other, and why?

    ----------

    I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user.

    The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program actimmediately upon a keystroke? Here's what I've got so far:

    import sysprint """Menu1) Say Foo

  • 7/27/2019 Stack Overflow Post Examples

    7/30

    2) Say Bar"""answer = raw_input("Make a selection> ")

    if "1" in answer: print "foo"elif "2" in answer: print "bar"

    It would be great to have something like

    print menuwhile lastKey = "":

    lastKey = check_for_recent_keystrokes()if "1" in lastKey: #do stuff...

    ----------

    Not efficient at all, but you can use a regular expression to test for primenumbers.

    /^1?$|^(11+?)\1+$/

    This tests if, for a string consisting of k 1s, k is not prime (i.e. whether the string consists of one 1 orany number of 1s that can be expressed as an n-ary product).

    ----------

    How often do you need to check for changes and how large (in terms of row size) are the tables in the database? If you use the CHECKSUM_AGG(BINARY_CHECKSUM(*)) method suggested by John, it will scan every row of the specified table. The NOLOCK hint helps, but on a large database, you arestill hitting every row. You will also need to store the checksum for every row

    so that you tell one has changed.

    Have you considered going at this from a different angle? If you do not wantto modify the schema to add triggers, (which makes a sense, it's not your database), have you considered working with the application vendor that does make thedatabase?

    They could implement an API that provides a mechanism for notifying accessoryapps that data has changed. It could be as simple as writing to a notificationtable that lists what table and which row were modified. That could be implemented through triggers or application code. From your side, ti wouldn't matter,your only concern would be scanning the notification table on a periodic basis.The performance hit on the database would be far less than scanning every row f

    or changes.

    The hard part would be convincing the application vendor to implement this feature. Since this can be handles entirely through SQL via triggers, you could do the bulk of the work for them by writing and testing the triggers and then bringing the code to the application vendor. By having the vendor support the triggers, it prevent the situation where your adding a trigger inadvertently replaces a trigger supplied by the vendor.

  • 7/27/2019 Stack Overflow Post Examples

    8/30

    ----------

    The only time you should set a variable to null is when the variable does notgo out of scope and you no longer need the data associated with it. Otherwise there is no need.

    ----------

    As always, Google is your friend:

    http://nixbit.com/cat/programming/libraries/c-generic-library/

    specifically:

    http://nixbit.com/cat/programming/libraries/generic-data-structures-library/

    ----------

    I've written a database generation script in sql, and want to execute it in my Adobe air application:

    Create Table tRole (roleID integer Primary Key

    ,roleName varchar(40));Create Table tFile (

    fileID integer Primary Key,fileName varchar(50),fileDescription varchar(500),thumbnailID integer,fileFormatID integer,categoryID integer,isFavorite boolean,dateAdded date,globalAccessCount integer,lastAccessTime date

    ,downloadComplete boolean,isNew boolean,isSpotlight boolean,duration varchar(30)

    );Create Table tCategory (

    categoryID integer Primary Key,categoryName varchar(50),parent_categoryID integer

    );...

    I execute this in Air using the following methods:

    public static function RunSqlFromFile(fileName:String):void {var file:File = File.applicationDirectory.resolvePath(fileName);var stream:FileStream = new FileStream();stream.open(file, FileMode.READ)var strSql:String = stream.readUTFBytes(stream.bytesAvailable);NonQuery(strSql);

    }

  • 7/27/2019 Stack Overflow Post Examples

    9/30

    public static function NonQuery(strSQL:String):void{

    var sqlConnection:SQLConnection = new SQLConnection();sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH);var sqlStatement:SQLStatement = new SQLStatement();sqlStatement.text = strSQL;sqlStatement.sqlConnection = sqlConnection;try{

    sqlStatement.execute();}catch (error:SQLError){

    Alert.show(error.toString());}

    }

    No errors are generated, however only tRole exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there anyway to call multiple queries in one statement?

    ----------

    Actually, PyDev plugin for Eclipse has a full support for code completion (try PyDev Extensions too). You can easily try it here. Another editor worth mentioning is WingIDE, which is really powerful. For more on Python editors check thispage.

    I use Aquamacs with ropemacs on my Mac, but that's an ultra geekysetup :)

    ----------

    I need the name of the current logged in user in my Air/Flex application. Theapplication will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways.

    ----------

    try libpcre

    If you're stuck on windows they have a windows port which should work. I knowe-texteditor uses it, so at least that'sproof it works :-)

    ----------

    XML/SWF Charts does Chart off XML:

    http://www.maani.us/xml_charts/

    ----------

    Definately the best tool I have ever used.

  • 7/27/2019 Stack Overflow Post Examples

    10/30

    It is the natural progression of the industry that the tools improve. It's not 'magic'! It's just like a JCB digger instead of a shovel. I can go dig a holemanually with a shovel if I have to - but it hurts!

    ----------

    Brad's list is pretty good. I also listen to:

    Sparkling Client (Silverlight specific)Jon Udell's Perspectives seriesHerding Code (shamelessplug for a podcast I put onwith Kevin Dente, Scott "lazycoder" Koon, and K. ScottAllen. We recently interviewed Jeff Atwood aboutStack Overflow, discussing both how the site isdesigned and the technology behind it.

    ----------

    My Goal

    I would like to have a main processing thread (non GUI), and be able to spinoff GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible withWindows Forms(?)

    (Sorry for the big post here. I've had complaints about previous shorter versions of this question just isn't comprehensible. I'm a lousy writer)

    Background

    I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponentinterface with a single method DoStuff() .

    Which components that gets loaded is configured via a xml configuration fileand by adding new assemblies containing different implementations of IComponent . The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, thecomponents might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what haveyou. What I would like, is to have one of these components be able to display aGUI, e.g. with status information for the said email sending component.

    The lifetime of the complete system looks like this

    Application starts.Check configuration file for components to load. Load them.For each component, run DoStuff() to initialize it and make it liveits own life in their own threads.Continue to do main application-thingy king of work, forever.

  • 7/27/2019 Stack Overflow Post Examples

    11/30

    I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff() . It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4.

    It would be great if these components were allowed to start up their own Windows Forms GUIs.

    Problem

    When a component tries to fire up a GUI in DoStuff() (the exact lineof code is when the component runs Application.Run(theForm)) , the component and hence our system "hangs" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected.

    Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them.

    public class MyComponent1: IComponent
    {
    public string DoStuff(...) { // write something to the database }
    }

    public class MyComponent2: IComponent
    public void DoStuff()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form());

    // I want the thread to immediately return after the GUI
    // is fired up, so that my mai

    n thread can continue to work.
    }
    }

    I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed.

    public void DoStuff()
    {
    new Thread(ThreadedInitialize).Start()
    }

    private void ThreadedInitialize()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form());
    }

    Is it possible to spin off a GUI and return after Application.Run()?

    ----------

    What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!

    ----------

    I have to agree with the OP 'wrong' dates really jar with my DD/MM/YYYY upbringing and I find ISO 8601 dates and times extremely easy to work with. For oncethe standard got it right and engtech has the obvious answer that doesn't require loca

    lisation.

    I was going to report the birthday input form on stack overflow as a bug because of how much of a sore thumb it is to the majority of the world.

    ----------

    In the vein of portability, I'd use relational. Moving a website from one host to another would be a nightmare with some niche DBMS. Almost all hosting providers offer MSSQL and MySQL these days.

  • 7/27/2019 Stack Overflow Post Examples

    12/30

    ----------

    When I was first learning Java we had to make Yahtzee and I thought it wouldbe cool to create custom Swing components and containers instead of just drawingeverything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a prettypicture. It may not be done the best way however, but it may be a good starting point for you.

    Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.



    Here are the basic steps:

    Create a class that extends JComponent

    Call parent constructor super() in your constructorsMake sure you class implements MouseListener

    Put this in the constructor:

    enableInputMethods(true);addMouseListener(this);

    Override these methods:

    public Dimension getPreferredSize()public Dimension getMinimumSize()public Dimension getMaximumSize()

    Override this method:

    public void paintComponent(Graphics g)

    The amount of space you have to work with when drawing your button is definedby getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

    And finally, the source code. In case I missed anything.

    ----------

    SVN has 3 main advantages over CVS

    it's fastersupports versioning of binary filesand adds transactional commit (all or nothing)

  • 7/27/2019 Stack Overflow Post Examples

    13/30

    ----------

    High Resolution, Low Overhead Timing for Intel Processors

    If you're on Intel hardware, here's how to read the CPU real-time instructioncounter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement.

    Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting thisto a double is quite handy.

    When I run this on my box, I get

    1186792787948473211867927879692217it took this long to call printf: 207485

    Here's the Intel developer's

    guide that gives tons of detail.

    #include #include

    inline uint64_t rdtsc() {uint32_t lo, hi;__asm__ __volatile__ ("xorl %%eax, %%eax\n""cpuid\n""rdtsc\n": "=a" (lo), "=d" (hi):

    : "%ebx", "%ecx");return (uint64_t)hi

    I'm not sure about the AMD CPUs, we're primarily an Intel shop,although I know some of our low-level systems gurus did anAMD evaluation.

    Hope this satisfies your curiosity, it's an interesting and (IMHO)under-studied area of programming. You know when Jeff and Joel weretalking about whether or not a programmer should know C? I wasshouting at them, "hey forget that high-level C stuff... assembleris what you should learn if you want to know what the computer isdoing!"

    ----------

    An approach I've used in various applications is to have a generic PermissionToken class which has a changeable Value property. Then you query the requested

    application, it tells you which PermissionTokens are needed in order to use it.

    For example, the Shipping application might tell you it needs:

    new PermissionToken()
    {
    Target = PermissionTokenTarget.Application,
    Action = PermissionTokenAction.View,
    Value = "ShippingApp"
    };

    This can obviously be extended to Create, Edit, Delete etc and, because of the custom Value property, any application, module or widget can define its own required permissions. YMMV, but this has always been an efficient method for me which I have found to scale well.

    ----------

    Big List of Resources:

    A Nanopass Framework for Compiler Education Advanced Compiler Design and Implementation $An Incremental Approach to Compiler Construction ANTLR 3.x Video TutorialBuilding a Parrot CompilerCompiler BasicsCompiler Construction $Compiler Design and ConstructionCrafting a Com

  • 7/27/2019 Stack Overflow Post Examples

    16/30

    piler with C $Dragon Book $ - Widely considered "the book" for compiler writing.Essentials of Programming LanguagesFlipcode Article ArchiveGame ScriptingMastery $How to build a virtual machine from scratch in C# Implementing Functional LanguagesImplementing Programming Languages using C# 4.0Interpreter pattern (described in Design Patterns $) specifies a way to evaluate sentences in a languageLanguage Implementation Patterns: Create Your Own Domain-Specific and General Programming LanguagesLets Build a Compiler - Th

    e PDF versionLinkers and Loaders $ (Google Books)Lisp in SmallPieces (LiSP) $LLVM TutorialModern Compiler Implementation in ML $ - There is a Java $ and C $ version as well - widly considered a very good bookObject-Oriented Compiler Construction

    ParrotTutorialParsing Techniques - A Practical GuideProjectOberon - Look at chapter 13Programming aPersonal Computer $Programing Languages: Application and InterpretationRabbit: A Compiler for SchemeReflections on Trusting

    Trust - a quick guideRoll Your Own Compiler for the .NET framework a quick toturial form MSDNStructure and Interpretation of Computer ProgramsTypes and Programming LanguagesWant to Write a Compiler? - aquick guide

  • 7/27/2019 Stack Overflow Post Examples

    17/30

    html">Writing a Compiler in Ruby Bottom Up

    Legend:
    Link to a PDF
    $ Link to a printed book

    ----------

    If the fact that the first button is used by default is consistent across browsers, why not put them the right way round in the source code, then use CSS toswitch their apparent positions? float them left and right to switch them around visually, for example.

    ----------

    Qt Cross-PlatformApplication Framework

    Qt is a cross-platform application framework for desktop and embedded development. It includes an intuitive API and a rich C++ class library, integrated tools for GUI development and internationalization, and support for Java and C++ deve

    lopment

    They have a plug-in for Visual Studio that costs a bit of money, but it is worth every penny.

    ----------

    Have a DTS job (or a job that is started by a windows service) that runs at agiven interval. Each time it is run, it gets information about the given tableby using the system INFORMATION_SCHEMA tables, and records this data in the data repository.Compare the data returned regarding the structure of the table with the data returned the previous time. If it is different, then you know that the structure h

    as changed.

    Example query to return information regarding all of the columns in table ABC(ideally listing out just the columns from the INFORMATION_SCHEMA table that you want, instead of using select * like I do here):

    select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'ABC'

    You would monitor different columns and INFORMATION_SCHEMA views depending onhow exactly you define "changes to a table".

    ----------

    John Resig did a script to extract images from a PDF as PNG files using ImageMagick.

    ----------

    Oracle has got an extensive tutorial on that topic

  • 7/27/2019 Stack Overflow Post Examples

    18/30

    ----------

    I didn't try it, but I did see an article on Code Project that implements C#scripting in a .NET application.

    http://www.codeproject.com/KB/cs/cs-script_for_cp.aspx

    ----------

    What is the difference between Math.Floor() and Math.Truncate()in .NET?

    ----------

    Check out FileHelpers.

    ----------

    Ummm. Maybe I am missing something about the question here, but if you havelong/lat info, you also have the direction of north?

    It seems you need to map geodesic coordinates to a projected coordinates system. For example osgb to wgs84.

    The maths involved is non-trivial, but the code comes out a only a few lines.If I had more time I'd post more but I need a shower so I will be boring and link to the wikipedia entry which is pretty good.

    Note: Post shower edited.

    ----------

    SQLite databases exist independently, so there's not way to do this from thedatabase level.

    You will have to write your own code to do this.

    ----------

    I'm trying to read binary data using C#. I have all information about the layout of the data in the files I want to read. I'm able to read the data "chunk bychunk", i.e. getting the first 40 bytes of data converting it to a string, getthe next 40 bytes, ...

    Since there are at least three slighlty different version of the data, I would like to read the data directly into a struct. It just feels so much more right

    than by reading it "line by line".

    I have tried the following approach but to no avail:

    StructTypeaStruct;int count = Marshal.SizeOf(typeof(StructType));byte[] readBuffer = new byte[count];BinaryReader reader = new BinaryReader(stream);readBuffer = reader.ReadBytes(count);GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
  • 7/27/2019 Stack Overflow Post Examples

    19/30

    handle.Free();

    The stream is an opened FileStream from which I have began to read from. I get an AccessViolationException when using Marshal.PtrToStructure.

    The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.

    The struct is defined like:

    [StructLayout(LayoutKind.Explicit)]struct StructType{

    [FieldOffset(0)]public string FileDate;[FieldOffset(8)]public string FileTime;[FieldOffset(16)]public int Id1;[FieldOffset(20)]public string Id2;

    }

    The examples code is changed from original to make this question shorter.

    How would I read binary data from a file into a struct?

    ----------

    This will work in IE and FF, the downside is that it is not XHTML standard.

    ----------

    Use a non-standard name and id for the fields, so rather than "name" have "name_". Browsers will then not see it as being the name field. The best part aboutit is that you can do this to some but not all fields and it will autocomplete

    some but not all fields.

    ----------

    Use subversion, it's easy to setup, easy to use, and has plenty of tools. Anyfuture revision system will have an import from SVN feature, so it isn't like you can't change down the road if your needs grow.

    ----------

    I found this project on google code. This is CCNET plugin to generatethe label in CCNET.

    The DLL is tested with CCNET 1.3 but it works withCCNET 1.4 for me. I'm successfully using this plugin to label my build.

    Now onto passing it to MSBuild...

    ----------

  • 7/27/2019 Stack Overflow Post Examples

    20/30

    The GNU C Library supports regular expressions. It's open, and the RE code seems to be easily extractable.

    ----------

    Checkboxes in html forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox.

    ----------

    A solution (albeit one that defers handling of the null value to the code) could be:

    DateTime yesterday = DateTime.Now.Date.AddDays(-1);

    var collection=
    from u in db.Universe
    select new
    {
    u.id,
    u.name,
    MaxDate =(DateTime?)
    (
    from h in db.History
    where u.Id == h.Id

    && h.dateCol < yesterday
    select h.dateCol
    ).Max()
    };

    This does not produce exactly the same SQL, but does provide the same logicalresult. Translating "complex" SQL queries to LINQ is not allways straightforwar

    d.

    ----------

    I believe DB Designer does something like that. And I think they even have a free version.

    editNever mind. Michael's link is much better.

    ----------

    There's a PHP5 "database migration framework" called Ruckusing. I haven't used it, but the examples show the idea, if you use the language to create the database as and when needed, you only have to track source files.

    ----------

    Martin Fowler's website(and his books) have fantastic in-depth articles on various ui patterns and what they address.

    ----------

    Depends on the version, 4 is by value, 5 is by reference.

    ----------

    I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure.

  • 7/27/2019 Stack Overflow Post Examples

    21/30

    My philosophy would be to go ahead and make both structures accessible to theclient in a polished way, just under the assumption they would be used in tandem.

    I would reference something like a QTextDocument in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to anobject like a QTextEdit to do the manipulation.

    ----------

    Here's a dynamic sql script I've used in the past. It can be further modified but it will give you the basics. I prefer scripting it to avoid the mistakesyou can make using the Management Studio:


    Declare @OldDB varchar(100)
    Declare @NewDB varchar(100)
    Declare @vchBackupPath varchar(255)
    Declare @query varchar(8000)


    /*Test code to implement
    Select @OldDB = 'Pubs'
    Select @NewDB = 'Pubs2'
    Select @vchBackupPath = '\\dbserver\C$\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\pubs.bak'
    */

    SET NOCOUNT ON;

    Select @query = 'Create Database ' + @NewDB
    exec(@query)

    Select @query = '
    Declare @vBAKPath varchar(256)
    declare @oldMDFName varchar(100)
    declare @oldLDFName var

    char(100)
    declare @newMDFPath varchar(100)
    declare @newLDFPath varchar(100)
    declare @restQuery varchar(800)

    select @vBAKPath = ''' + @vchBackupPath + '''
    select @oldLDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.ldf%''
    select @oldMDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.mdf%''
    select @newMDFPath = physical_name from '+ @NewDB +'.sys.database_files where type_desc = ''ROWS''
    select @newLDFPath= physical_name from ' + @NewDB +'.sys.database_files where type_desc = ''LOG''

    select @restQuery = ''RESTORE DATABASE ' + @NewDB +
    ' FROM DISK = N''+ '''''''' + @vBAKpath + '''''''' +
    '' WITH MOVE N'' + '''''''' + @oldMDFName + '''''''' +
    '' TO N'' + '''''''' + @newMDFPath + '''''''' +
    '', MOVE N'' + '''''''' + @oldLDFName + '''''''' +
    '' TO N'' + '''''''' + @newLDFPath + '''''''' +
    '', NOUNLOAD, REPLACE, STATS = 10''

    exec(@restQuery)
    --print @restQuery'


    exec(@query)





    ----------

    The Glib library used on the Gnome project may also be some use. Moreover it is pretty well tested.

    IBM developer works has a good tutorial on its use: Manage Cdata using the GLib collections

    ----------

    In your example above, when 'i' will always be positive and a higher range would be beneficial, unsigned would be useful. Like if you're using 'declare' statements, such as:

    #declare BIT1 (unsigned int 1)
    #declare BIT32 (unsigned int reallybignumber)

    Especially when these values will never change.

  • 7/27/2019 Stack Overflow Post Examples

    22/30

    However, if you're doing an accounting program where the people are irresponsible with their money and are constantly in the red, you will most definitely want to use 'signed'.

    I do agree with saint though that a good rule of thumb is to use signed, which C actually defaults to, so you're covered.

    ----------

    I was wondering if there is any good and clean oo implementation of bayesianfiltering for spam and text classification? For learning purposes.

    ----------

    I'm working on a multithreaded C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behaviour asthe most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bugwas introduced - there are a lot of code changes in the repository.

    The prompt for crashing behaviuor is to generate throughput in this system -

    socket transfer of data which is munged into an internal representation. I havea set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption).

    The behaviour seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash. Disabling a hyper-threading coreor a dual-core core reduces the rate of (but does not eliminate) corruption. This suggests a timing related issue.

    Now here's the rub:
    When it's run under a lightweight debug environment (say Visual Studio 98/ AKA MSVC6) the heap corruption is reasonably easy to reproduce - ten or

    fifteen minutes pass before something fails horrendously and exceptions, like an alloc; when running under a sophisticated debug environment (Rational Purify, VS2008/MSVC9 or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is notgetting above 50%, disk light is not on, the program's going as fast it can, box consuming 1.3G of 2G of RAM). So, I've gota choice between being able to reproduce the problem (but not identify the cause) or being able to idenify the cause or a problem I can't reproduce.

    My current best guesses as to where to next is:

    Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an E6550 Core2 Duo); this will make it possible to repro the crash causing mis-behaviour when running under a powerful debug environment; orRewrite operators new and delete to use VirtualAlloc and VirtualProtect to mark memory as read-only as soon as it's done with. Run under MSVC6 and have the OS catch the bad-guy who's writing to freed memory. Yes, this is a sign of desperation: who the hell rewrites new and delete?! I wonder if this isgoing to make it as slow as under Purify et al.

  • 7/27/2019 Stack Overflow Post Examples

    23/30

    And, no: Shipping with Purify instrumentation built in is not an option.

    A colleague just walked past and asked "Stack Overflow? Are we getting stackoverflows now?!?"

    And now, the question: How do I locate the heap corruptor?

    Update: balancing new[] and delete[] seems to havegotten a long way towards solving the problem. Instead of 15mins, the app now goes about two hours before crashing. Not there yet. Any further suggestions? The heap corruption persists.

    Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the STL implementation that ships with VS98.

    Reproduce the problem. Dr Watson will produce a dump that might be helpful in further analysis.

    I'll take a note of that, but I'm concerned that Dr Watson will only be tripped up after the fact, not when the heap is getting stomped on.

    Another try might be using WinDebug as a debugging tool which

    is quite powerful being at the same time also lightweight.

    Got that going at the moment, again: not much help until something goes wrong. I want to catch the vandal in the act.

    Maybe these tools will allow you at least to narrow the problem to certain

    component.

    I don't hold much hope, but desperate times call for...

    And are you sure that all the components of the project have correct runtim

    e library settings (C/C++ tab, Code Generation category in VS 6.0 p

    roject settings)?

    No I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with theappropriate flags.Update: This took 30 seconds. Select all projects in the Settingsdialog, unselect until you find the project(s) that don't have the right settings (they all had the right settings).

  • 7/27/2019 Stack Overflow Post Examples

    24/30

    ----------

    It sounds like this.Opacity is a double value, and the compilerdoesn't like you trying to cram a decimal value into it.

    ----------

    It depends, what is the nature of the site? If the sites customers are exposed to Identity Theft or similar horrific things, it is your duty to report the issue to outside authorities. The question is, how?

    I would suggest contacting The Consumerist and demonstrating your exploit to them. They will bring enough media attention to the issue that the company will be forced to do something about it.

    If on the other hand, it's a silly web forum for turtle lovers... well, if they don't care, move on to bigger and better things.

    ----------

    I listen to the javaposse regularly, they cover mostly Java, but not solely.

    ----------

    I am seconding the WMWare angle. Most of the open source OSes have a completemachine ready to roll, so there is no install time and VMWare Player is free touse with these.

    Also, some emulators that attempt to simulate a different resolution fail totake the browser into account and the virtual machine can replicate this better.

    ----------

    Looks like you're right. That's the only approach.

    This seems like a good detailed explanation of your advice: http://ajaxpatterns.org/Unique_URLs

    ----------

    You can print from the command line using the following:

    rundll32.exe%WINDIR%\System32\mshtml.dll,PrintHTML"%1"

    Where %1 is the file path of the html file to be printed.

    If you don't need to print from memory (or can afford to write to the disk ina temp file) you can use:

  • 7/27/2019 Stack Overflow Post Examples

    25/30

    using (Process printProcess = new Process())
    {
    string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
    printProcess.StartInfo.FileName = systemPath + @"\rundll32.exe";
    printProcess.StartInfo.Arguments = systemPath + @"\mshtml.dll,PrintHTML """ + fileToPrint +@"""";
    printProcess.Start();
    }

    N.B. This only works on Windows 2000 and above I think.

    ----------

    Make sure you keep a record of your e-mail message(s). You might need it in court.

    ----------

    I would look into IMAP

    IMAP, POP3 and NNTP

    ----------

    You do the unit testing by mocking out the database connection. This way, you

    can build scenarios where specific queries in the flow of a method call succeedor fail. I usually build my mock expectations so that the actual query text isignored, because I really want to test the fault tolerance of the method and howit handles itself -- the specifics of the SQL are irrelevant to that end.

    Obviously this means your test won't actually verify that the method works, because the SQL may be wrong. This is where integration tests kick in. For that, I expect someone else will have a more thorough answer, as I'm just beginning to get to grips with those myself.

    ----------

    I am thinking off the top of my head here. If you load both as Data Tables in

    the same Data Sets, and define a relation between the two over SKU, and then run a query on the Data Set which produces the desired result.

    ----------

    One of the many comparisons:

    http://wiki.scummvm.org/index.php/CVS_vs_SVN

    Now this is very specific to that project, but a lot of stuff apllies in general.

    Pro Subversion:

    Support for versioned renames/moves (impossible with CVS): Fingolfin, Ende

    rSupports directories natively: It's possible to remove them, and they are

    versioned: Fingolfin, EnderFile properties are versioned; no more "executable bit" hell: Fingolfin

  • 7/27/2019 Stack Overflow Post Examples

    26/30

    Overall revision number makes build versioning and regression testing mucheasier: Ender, FingolfinAtomic commits: FingolfinIntuitive (directory-based) branching and tagging: FingolfinEasier hook scripts (pre/post commit, etc): SumthinWicked (I use it for Do

    xygen after commits)Prevents accidental committing of conflicted files: Salty-horse, Fingolfin

    Support for custom 'diff' command: FingolfinOffline diffs, and they're instant: sev

    ----------

    Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting articlefrom Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.

    http://www.linuxjournal.com/article/9170

    ----------

    No, because while you thought LINQ is really just syntactic sugar, it actually heavily used expression trees -- a feature absent in .NET 2.0.

    That being said .NET 3.5 only builds up on top of .NET 2.0, and that's the reason why the IL doesn't look "different" or "special".

    I do not see a reason why you shouldn't just install the .NET 3.5 Framework.Everything .NET 2.0 will work fine on it, promise :)

    ----------

    I would say, don't worry so much about such micro performance. It is much be

    tter to just get something to work, and then make it as clear and concise and easy to read as possible. The worst thing you can do is sacrifice readability foran insignificant amount of performance.

    In the end, the best way to deal with performance issues is to save them forwhen you have data that indicates there is an actual performance problem... otherwise you will spend a lot of time micro-optimizing and actually cause higher maintenance costs for later on.

    If you find this parsing situation is really the bottleneck in your application, THEN is the time to try and figure out what the fastest way to solve the problem is. I think Jeff (and many others) have blogged about this sort of thing alot.

    ----------

    I have a little game written in C#. It uses a database as back-end. It'sa trading card game, and I wanted to implement the function of the cards as a script.

    What I mean is that I essentially have an interface, ICard, which a card class implements (public class Card056 : ICard) and whichcontains function that are called by the game.

  • 7/27/2019 Stack Overflow Post Examples

    27/30

  • 7/27/2019 Stack Overflow Post Examples

    28/30

    As I said, I hear a lot of opinions, but not a lot of consensus. I know Javadoesn't have unsigned values, and that must have been a concious decision on Sun's part.

    Looking forward to hearing everybody's opinion.

    ----------

    Does the Flash Trial version not last long enough (30 days) for you to evaluate if Flash is the right choice for you?

    @Bill, no probs, reading between the lines isn't my strong point sorry for any confusion :)

    ----------

    any of the popular editors can be turned into an ide.

    I use Vi on the console and have used various gui editors over the years. This doesn't just go for linux I use Crimson Editor on windows as a C/python/z80asm ide.

    ----------

    Past year's ICFP contests have interesting problems. 2006's is quite a lot of fun and has lots ofdifferent problems to work on, from building your own VM to coding in a 2D circuit language.

    ----------

    AppDomain.UnhandledException is an event, not a global exception handler. This means, by the time it is raised, your application is already on its way down the drain, and there is nothing you can do abou

    t it, except for doing cleanup and error logging.

    What happened behind the scenes is this: The framework detected the exception, walked up the call stack to the very top, found no handlers that would recoverfrom the error, so was unable to determine if it was safe to continue execution. So, it started the shutdown sequence, and fired up this event as a courtesy toyou so you can pay your respects to your already-doomed process. This happens when an exception is left unhandled in the main thread.

    There is no single-point solution to this kind of error. You need to put a real exception handler (a catch block) upstream of all places where this error occurs and forward it to (for example) a global handler method/class that will determine if it is safe to simply report and continue, based on exception type and/o

    r content.

    Edit: It is possible to disable (=hack) the error-reporting mechanism built into Windows so the mandatory "crash and burn" dialog does not get displayed whenyour app goes down. However, this becomes effective for all the applications in the system, not just your own.

    ----------

    I know several people who were in a situation like this.

  • 7/27/2019 Stack Overflow Post Examples

    29/30

    Let's say, you were trying out random sites for basic XSS/SQL Injection vulnerabilities, and you've found one that could be easily compromised. You email theadmin/webmaster, but they don't reply.

    What would you do?

    ----------

    I want to print HTML from a C# web service. The Web Browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free.NET library that will support the printing of a basic HTML page? Here is thecode I have so far, which does not run properly.

    public void PrintThing(string document){

    if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA){

    Thread thread =new Thread((ThreadStart) delegate { PrintDocument(document); });

    thread.SetApartmentState(ApartmentState.STA);thread.Start();

    }else{

    PrintDocument(document);}

    }

    protected void PrintDocument(string document){

    WebBrowser browser = new WebBrowser();browser.DocumentText = document;while (browser.ReadyState != WebBrowserReadyState.Complete){

    Application.DoEvents();}browser.Print();

    }

    This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing Print() to ShowPrintPreviewDialog() yields the following IE script error:

    Error: 'dialogArguments.___IE_PrintType' is null or not an object
    URL: res://ieframe.dll/preview.dlg

    And a small empty print preview dialog appears.

    ----------

    This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology.

  • 7/27/2019 Stack Overflow Post Examples

    30/30

    Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.

    This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam

    I figure this is a big topic in which I am essentially an ignorant simpleton.

    ----------

    Martin Fowler wrote my favorite article on the subject, http://martinfowler.com/articles/evodb.html. I choose not to put schema dumps in under version control as alumb and others suggest because I want an easy way to upgrade my production database.

    For a web application where I'll have a single production database instance,I use two techniques:

    Database Upgrade Scripts

    A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A version_history table, something like

    create table VersionHistory (
    Version int primary key,
    UpgradeStart datetime not null,
    UpgradeEnd datetime
    );

    gets a new entry every time an upgrade script runs which corresponds to the new version.

    This ensures that it's easy to see what version of the database schema existsand that database upgrade scripts are run only once. Again, these are not database dumps. Rather, each script represents the changes necessary to move from one version to the next. They're the script that you apply to your production database to "upgrade" it.

    Developer Sandbox Synchronization

    A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB.A script to restore (and tweak, if necessary) the backup on a developer's wo

    rkstation. Each developer runs this script after each upgrade to the productionDB.

    A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs.

    ----------