Search Results

Search found 1067 results on 43 pages for 'thomas berger'.

Page 4/43 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • What is a good DBMS for archiving?

    - by Thomas.Winsnes
    I've been stuck in a MsSql/MySql world now for a few years, and I've decided to spread my wings a little further. At the moment I'm researching which DBMS is good at things needed when archiving data. Eg. lots of writes and low reads. I've seen the NoSQL crusade, but I have a very RDBMS mindset, so I'm a bit skeptical. Anyone have any suggestions? Or even any pointers to where there are some benchmarks etc for this kind of stuff. Thank you :) Thomas

    Read the article

  • logrotate compress files after the postrotate script

    - by Thomas
    I have an application generating a really heavy big log file every days (~800MB a day), thus I need to compress them but since the compression takes time, I want that logrotate compress the file after reloading/sending HUP signal to the application. /var/log/myapp.log { rotate 7 size 500M compress weekly postrotate /bin/kill -HUP `cat /var/run/myapp.pid 2>/dev/null` 2>/dev/null || true endscript } Is it already the case that the compression takes place after the postrotate (which would be counter-intuitive)? If not Can anyone tell me if it's possible to do that without an extra command script (an option or some trick)? Thanks Thomas

    Read the article

  • Does anyone has the experience of using the new p4 replicate command in their Perforce back-up /rest

    - by Thomas Corriol
    Hi all, we recently performed an upgrade of our whole perforce system to 2009.02 During this exercise, we noticed that the back-up /restore process that was installed here by the Perforce consultant a year ago was not completely working. Basically, the verify command has never worked (scary !). As we are obliged to revisit our Back-Up/Restore scripts, I was toying with the idea of using the new p4 replicate command. The idea is to use it alongside an rsync of the data files, so that in case of crash we will lose at worst an hour of work (if we execute them every hour). Does anyone has the experience or an example of back-up/restore scripts using the p4 replicate command of the 2009.02 version ? Thanks, Thomas

    Read the article

  • Problems after adding Control dynamically on Panel

    - by Thomas
    Hello, I have added an View List onto a Panel like that: panelComponent.Controls.Add(viewListComponent); Everthing works just fine. Mouse Events are handled, Repaint works. But one: I cant dynamically move it around. If i change the control.Top Variablen it just sit there and nothing. Its clued to the top left corner. Resizing the right and bottom line works just fine! I did it without dynamically adding and than no Problem. Hope you can help. Thomas

    Read the article

  • 2 way synchronization of in-house gitosis repositories server with Github repositories

    - by Robert J Berger
    We use gitosis as our local in-house shared repository and also have a private Github account that mirrors our local repository. If one does a git push to the in-house repository the post-update hook updates the Github repository. How can I make this two way without causing "loops"? I.e. if someone pushes to the Github repository, I would like it to also update the in-house gitosis repository. A pointer to an example of how to do it would be greatly appreciated. Or if there are recommendations of alternatives to gitosis that would make this kind of thing easy, I would consider migrating to that.

    Read the article

  • Process XML in C# using external entity file

    - by Ryan Berger
    I am processing an XML file (which does not contain any dtd or ent declarations) in C# that contains entities such as &eacute; and &agrave;. I receive the following exception when attempting to load an XML file... XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(record); Reference to undeclared entity 'eacute'. I was able to track down the proper ent file here. How do I tell XmlDocument to use this ent file when loading my XML file?

    Read the article

  • Append a parent element to arrays in PHP for a foreach loop

    - by Erik Berger
    print_r of $data = json_decode($src, true); returns data that looks like this: Array ( [0] => Array ( [var1] => blah [var2] => foo ) [1] => Array ( [var1] => lorem [var2] => ipsum ) // goes down to [1936] ) I want to build an html table that shows var1 and var2 next to each other in the same row. I know do to this I need a foreach statement like foreach($data['items'] as $item) but the problem I think I am having is that my many arrays aren't the child of one thing like 'items', right? I looked into array_push but couldn't figure it out. Can someone help my orphaned parentless arrays?

    Read the article

  • TXT File or Database?

    - by Ruth Rettigo
    Hey folks! What should I use in this case (Apache + PHP)? Database or just a TXT file? My priority #1 is speed. Operations Adding new items Reading items Max. 1 000 records Thank you. Database (MySQL) +----------+-----+ | Name | Age | +----------+-----+ | Joshua | 32 | | Thomas | 21 | | James | 34 | | Daniel | 12 | +----------+-----+ TXT file Joshua 32 Thomas 21 James 34 Daniel 12

    Read the article

  • Exclude a string from wildcard search in a shell

    - by steigers
    Hello everybody I am trying to exclude a certain string from a file search. Suppose I have a list of files: file_Michael.txt, file_Thomas.txt, file_Anne.txt. I want to be able and write something like ls *<and not Thomas>.txt to give me file_Michael.txt and file_Anne.txt, but not file_Thomas.txt. The reverse is easy: ls *Thomas.txt Doing it with a single character is also easy: ls *[^s].txt But how to do it with a string? Sebastian

    Read the article

  • jqGrid Coloring an entire line in Grid based upon a cells value

    - by Thomas
    Hi all, i know it's been asked before but i cant get it to run and i'm out of things to try. So i want to colorize a row in a Grid if its value is not 1 - i use a custom formatter for this. The formatter itself works, thats not the problem. I've tried multple ways I've found so far on the web - adding a class, directly adding css code, using setRowData, using setCell.... Here are my examples - none of them worked for me (linux, ff363) - any pointer would be gratly appreciated. 27.05.2010_00:00:00-27.05.2010_00:00:00 is my row id <style> .state_inactive { background-color: red !important; } .state_active { background-color: green !important; } </style> function format_state (cellvalue, options, rowObject) { var elem='#'+options.gid; if (cellvalue != 1) { jQuery('#list2').setRowData(options.rowID,'', {'background-color':'#FF6F6F'}); jQuery('#list2').setRowData('27.05.2010_00:00:00-27.05.2010_00:00:00', '',{'background-color':'#FF6F6F'}); for (var cnt=0;cnt<rowObject.length;cnt=cnt+1) { jQuery(elem).setCell(options.rowId,cnt,'','state_inactive',''); jQuery(elem).setCell('"'+options.rowId+'"',cnt,'','state_inactive'); jQuery(elem).setCell('"'+options.rowId+'"',cnt,'5', {'background-color':'#FF6F6F'},''); } } else { for (var cnt=0;cnt<rowObject.length;cnt=cnt+1) { jQuery(elem).setCell(options.rowId,cnt,'','state_active',''); } } <!-- dont modify, we simply added the class above--> return cellvalue; } Thanks, Thomas

    Read the article

  • Qt Object Linker Problem " undefined reverence to vtable"

    - by Thomas
    This is my header: #ifndef BARELYSOCKET_H #define BARELYSOCKET_H #include <QObject> //! The First Draw of the BarelySocket! class BarelySocket: public QObject { Q_OBJECT public: BarelySocket(); public slots: void sendMessage(Message aMessage); signals: void reciveMessage(Message aMessage); private: // QVector<Message> reciveMessages; }; #endif // BARELYSOCKET_H This is my class: #include <QTGui> #include <QObject> #include "type.h" #include "client.h" #include "server.h" #include "barelysocket.h" BarelySocket::BarelySocket() { //this->reciveMessages.clear(); qDebug("BarelySocket::BarelySocket()"); } void BarelySocket::sendMessage(Message aMessage) { } void BarelySocket::reciveMessage(Message aMessage) { } I get the Linker Problem : undefined reference to 'vtable for barelySocket' This should mean, i have a virtual Function not implemented. But as you can see, there is non. I comment the vector cause that should solve the Problem, but i does not. The Message is a complex struct, but even converting it to int did not solve it. I searched Mr G but he could not help me. Thank you for your support, Thomas

    Read the article

  • Displaying indexed png- files out of NSArray on the iphone screen

    - by Thomas Hülsmann
    Hi, i like to create an artwork counter- display on an iphone, diplaying 0 to 9. The 10 digits are 10 png- files with the numbers 0 to 9 as their artwork content. The 10 png- files are implemented by using NSArray. Following you'll find the implementation- code: zahlenArray = [NSArray arrayWithObjects: [UIImage imageNamed:@"ziffer-0.png"], [UIImage imageNamed:@"ziffer-1.png"], [UIImage imageNamed:@"ziffer-2.png"], [UIImage imageNamed:@"ziffer-3.png"], [UIImage imageNamed:@"ziffer-4.png"], [UIImage imageNamed:@"ziffer-5.png"], [UIImage imageNamed:@"ziffer-6.png"], [UIImage imageNamed:@"ziffer-7.png"], [UIImage imageNamed:@"ziffer-8.png"], [UIImage imageNamed:@"ziffer-9.png"], nil]; As an index for the 10 digitis I use an integer variable, initializing with 0: int counter = 0; Furthermore I declare an UIImageview programmaticaly: UIImageView *zahlenEinsBisNeun; The implementation code for the UIImageview is: zahlenEinsBisNeun = [UIImage alloc] initWithFrame:CGRectMake(240, 50, 200, 200)]; ???????????????????????????????????????? [self.view addSubview:zahlenEinsBisNeun]; [zahlenEinsBisNeun release]; There, where you see the questionmarks, I don't know how to write the code, to retrieve my content artworks 0 to 9 from NSArray with the index "counter" and make it visible on my iphone screen by using .... addSubview:zahlenEinsBisNeun ... Can anybody help??? My thanks for your support in advance Thomas Hülsmann

    Read the article

  • How do I access variable values from one view controller in another?

    - by Thomas
    Hello all, I have an integer variable (time) in one view controller whose value I need in another view controller. Here's the code: MediaMeterViewController // TRP - On Touch Down event, start the timer -(IBAction) startTimer { time = 0; // TRP - Start a timer timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; [timer retain]; // TRP - Retain timer so it is not accidentally deallocated } // TRP - Method to update the timer display -(void)updateTimer { time++; // NSLog(@"Seconds: %i ", time); if (NUM_SECONDS == time) [timer invalidate]; } // TRP - On Touch Up Inside event, stop the timer, decide stress level, display results -(IBAction) btn_MediaMeterResults { [timer invalidate]; NSLog(@"Seconds: %i ", time); ResultsViewController *resultsView = [[ResultsViewController alloc] initWithNibName:@"ResultsViewController" bundle:nil]; [self.view addSubview:resultsView.view]; } And in ResultsViewController, I want to process time based on its value ResultsViewController - (void)viewDidLoad { if(time < 3) {// Do something} else if ((time > 3) && (time < 6)) {// Do something else} //etc... [super viewDidLoad]; } I'm kind of unclear on when @property and @synthesize is necessary. Is that the case in this situation? Any help would be greatly appreciated. Thanks! Thomas

    Read the article

  • SQL 2008: Using separate tables for each datatype to return single row

    - by Thomas C
    Hi all I thought I'd be flexible this time around and let the users decide what contact information the wish to store in their database. In theory it would look as a single row containing, for instance; name, adress, zipcode, Category X, Listitems A. Example FieldType table defining the datatypes available to a user: FieldTypeID, FieldTypeName, TableName 1,"Integer","tblContactInt" 2,"String50","tblContactStr50" ... A user the define his fields in the FieldDefinition table: FieldDefinitionID, FieldTypeID, FieldDefinitionName 11,2,"Name" 12,2,"Adress" 13,1,"Age" Finally we store the actual contact data in separate tables depending on its datatype. Master table, only contains the ContactID tblContact: ContactID 21 22 tblContactStr50: ContactStr50ID,ContactID,FieldDefinitionID,ContactStr50Value 31,21,11,"Person A" 32,21,12,"Adress of person A" 33,22,11,"Person B" tblContactInt: ContactIntID,ContactID,FieldDefinitionID,ContactIntValue 41,22,13,27 Question: Is it possible to return the content of these tables in two rows like this: ContactID,Name,Adress,Age 21,"Person A","Adress of person A",NULL 22,"Person B",NULL,27 I have looked into using the COALESCE and Temp tables, wondering if this is at all possible. Even if it is: maybe I'm only adding complexity whilst sacrificing performance for benefit in datastorage and user definition option. What do you think? Best Regards /Thomas C

    Read the article

  • How can I load a view based on how long I hold a UIButton?

    - by Thomas
    Hello all, I've searched the net and documentation, but haven't found anything quite like what I'm trying to do. I'm working on an app where I want to load one view if a UIButton is held for x seconds, another if it's held for x+y seconds, etc. I found this tutorial. The problem I'm running into is, how do I switch the length of the button press? The tutorial switched the number of taps. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSSet *allTouches = [event allTouches]; switch ([allTouches count]) { case 1: // Single touch { // Get the first touch. UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; switch ([touch tapCount]) { case 1: // Single Tap. { // Start a timer timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(showAlertView:) userInfo:nil repeats:NO]; [timer retain]; } break; case 2: // Double tap. break; } } break; case 2: // Double touch { } break; default: break; } } Any suggestions? Thanks! Thomas

    Read the article

  • How to efficiently show many Images? (iPhone programming)

    - by Thomas
    In my application I needed something like a particle system so I did the following: While the application initializes I load a UIImage laserImage = [UIImage imageNamed:@"laser.png"]; UIImage *laserImage is declared in the Interface of my Controller. Now every time I need a new particle this code makes one: // add new Laserimage UIImageView *newLaser = [[UIImageView alloc] initWithImage:laserImage]; [newLaser setTag:[model.lasers count]-9]; [newLaser setBounds:CGRectMake(0, 0, 17, 1)]; [newLaser setOpaque:YES]; [self.view addSubview:newLaser]; [newLaser release]; Please notice that the images are only 17px * 1px small and model.lasers is a internal array to do all the calculating seperated from graphical output. So in my main drawing loop I set all the UIImageView's positions to the calculated positions in my model.lasers array: for (int i = 0; i < [model.lasers count]; i++) { [[self.view viewWithTag:i+10] setCenter:[[model.lasers objectAtIndex:i] pos]]; } I incremented the tags by 10 because the default is 0 and I don't want to move all the views with the default tag. So the animation looks fine with about 10 - 20 images but really gets slow when working with about 60 images. So my question is: Is there any way to optimize this without starting over in OpenGl ES? Thank you very much and sorry for my english! Greetings from Germany, Thomas

    Read the article

  • QT EventTransition implementation

    - by Thomas
    I am trying to build an QT State Maschine. I have some States, and for those States i need Transition that alter the Graphics on my gui. The Problem i having and the only reason i am asking, i am Stuck and Point 1. The compiler cant identifie the QTEventTransition. I have QT 4.6 wroking with QT Creator on Windows. The compiler does not find Header #include < QtEventTransition This is what i did i never did this bevor but i think it should be correct, I have A Header File where i have my Transitions Declareted like this: class validateBoatTransition : public QtEventTransition { public: validateBoatTransition(Widget *widget,ServerSkeleton* server); protected: bool eventTest(QEvent *e); void onTransition(QEvent *); private: Chart* ourChart; Message current; BarelySocket* myBarelySocket; }; Than i have my Cpp File where i have this: validateBoatTransition::validateBoatTransition(Widget *widget,ServerSkeleton* server) { } void validateBoatTransition::onTransition(QEvent *e) { /* My Logik should go here */ } What i want is that if the Transition is activated by an Button (clicked) it should fire this transition! I searched the net, but cant find an solution. Can i do that? I should i think. Yours Thomas

    Read the article

  • Why is my UIWebView not scrollable?

    - by Thomas
    In my most frustrating roadblock to date, I've come across a UIWebView that will NOT scroll! I call it via this IBAction: -(IBAction)session2ButtonPressed:(id)sender { Session2ViewController *session2View = [[Session2ViewController alloc]initWithNibName:@"Session2ViewController" bundle:nil]; self.addictionViewController = session2View; [self.view insertSubview:addictionViewController.view atIndex:[self.view.subviews count]]; [session2View release]; } In the viewDidLoad of Session2ViewController.m, I have - (void)viewDidLoad { [super viewDidLoad]; // TRP - Grab data from plist // TRP - Build file path to the plist NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Addiction" ofType:@"plist"]; // TRP - Create NSDictionary with contents of the plist NSDictionary *addictionDict = [NSDictionary dictionaryWithContentsOfFile:filePath]; // TRP - Create an array with contents of the dictionary NSArray *addictionData = [addictionDict objectForKey:@"Addiction1"]; NSLog(@"addictionData (array): %@", addictionData); // TRP - Create a string with the contents of the array NSString *addictionText = [NSString stringWithFormat:@"<DIV style='font-family:%@;font-size:%d;'>%@</DIV>", @"Helvetica", 18, [addictionData objectAtIndex:1]]; addictionInfo.backgroundColor = [UIColor clearColor]; // TRP - Load the string created and stored into addictionText and display in the UIWebView [addictionInfo loadHTMLString:addictionText baseURL:nil]; // TODO: MAKE THIS WEBVIEW SCROLL!!!!!! } In the nib, I connected my web view to the delegate and to the outlet. When I run my main project, the plist with my HTML code shows up, but does not scroll. I copied and pasted this code into a new project, wired the nib the exact same way, and badda-boom badda-bing. . . it works. I even tried to create a new nib from scratch in this project, and the exact same code would not work. Whiskey Tango Foxtrot Any ideas?? Thanks! Thomas

    Read the article

  • Using ember-resource with couchdb - how can i save my documents?

    - by Thomas Herrmann
    I am implementing an application using ember.js and couchdb. I choose ember-resource as database access layer because it nicely supports nested JSON documents. Since couchdb uses the attribute _rev for optimistic locking in every document, this attribute has to be updated in my application after saving the data to the couchdb. My idea to implement this is to reload the data right after saving to the database and get the new _rev back with the rest of the document. Here is my code for this: // Since we use CouchDB, we have to make sure that we invalidate and re-fetch // every document right after saving it. CouchDB uses an optimistic locking // scheme based on the attribute "_rev" in the documents, so we reload it in // order to have the correct _rev value. didSave: function() { this._super.apply(this, arguments); this.forceReload(); }, // reload resource after save is done, expire to make reload really do something forceReload: function() { this.expire(); // Everything OK up to this location Ember.run.next(this, function() { this.fetch() // Sub-Document is reset here, and *not* refetched! .fail(function(error) { App.displayError(error); }) .done(function() { App.log("App.Resource.forceReload fetch done, got revision " + self.get('_rev')); }); }); } This works for most cases, but if i have a nested model, the sub-model is replaced with the old version of the data just before the fetch is executed! Interestingly enough, the correct (updated) data is stored in the database and the wrong (old) data is in the memory model after the fetch, although the _rev attribut is correct (as well as all attributes of the main object). Here is a part of my object definition: App.TaskDefinition = App.Resource.define({ url: App.dbPrefix + 'courseware', schema: { id: String, _rev: String, type: String, name: String, comment: String, task: { type: 'App.Task', nested: true } } }); App.Task = App.Resource.define({ schema: { id: String, title: String, description: String, startImmediate: Boolean, holdOnComment: Boolean, ..... // other attributes and sub-objects } }); Any ideas where the problem might be? Thank's a lot for any suggestion! Kind regards, Thomas

    Read the article

  • WPF closing child- closes parent-window

    - by Thomas Spranger
    i have the pretty same sample as mentioned here. Fast concluded: MainWindow closes when the last childwindow is closed. My Problem: I couldn't solve my problems with the described solutions. I can't produce a program where it als takes place. Only in one of my bigger progs. Maybe someone has an idea or knows any further steps. Thanks for reading - Thomas As requested here's a bit of code: This is the part in the MainWindow: bool editAfterSearch = false; Movie selectedMovie = (Movie)this.listView.SelectedItem; Movie backup = (Movie)selectedMovie.Clone(); if (new OnlineSearchWindow().EditMovieViaOnlineSearch(ref selectedMovie, out editAfterSearch)) { this.coverFlow.Update(selectedMovie); } And that's the part of the ChildWindow: public bool EditMovieViaOnlineSearch(ref Movie preset, out bool editAfter) { this.exitWithOk = false; this.editMovieAfterSearch = false; this.tbx_SearchTerm.Text = preset.Title; this.linkedMovie = preset; this.ShowDialog(); editAfter = editMovieAfterSearch; if (this.exitWithOk) { this.linkedMovie.CloneOnlineInformation(ref preset); preset.Bitmap = this.linkedMovie.Bitmap; return true; } else { return false; } }

    Read the article

  • Non-normalized association with legacy tables in Rails and ActiveRecord

    - by Thomas Holmström
    I am building a Rails application accessing a legacy system. The data model contains Customers which can have one or more Subscriptions. A Subscription always belong to one and only one Customer. Though not needed, this association is represented through a join table "subscribes", which do not have an id column: Column | Type | Modifiers -----------------+---------+----------- customer_id | integer | not null subscription_id | integer | not null I have this coded as a has_and_belongs_to_many declarations in both Customer and Subscription class Customer < Activerecord::Base has_and_belongs_to_many :subscriptions, :join_table => "subscribes", :foreign_key => "customer_id", :association_foreign_key => "subscription_id" end class Subscription < Activerecord::Base has_and_belongs_to_many :customers, :join_table => "subscribes", :foreign_key => "subscription_id", :association_foreign_key => "customer_id" end The problem I have is that there can only ever be one customer for each subscription, not many, and the join table will always contain at most one row with a certain customer_id. And thus, I don't want the association "customers" on a Subscription which returns an array of (at most one) Customer, I really do want the relation "customer" which returns the Customer associated. Is there any way to force ActiveRecord to make this a 1-to-N relation even though the join table itself seems to make it an N-to-M relation? --Thomas

    Read the article

  • Creating android app Database with big amount of data

    - by Thomas
    Hi all, The database of my application need to be filled with a lot of data, so during onCreate(), it's not only some create table sql instructions, there is a lot of inserts. The solution I chose is to store all this instructions in a sql file located in res/raw and which is loaded with Resources.openRawResource(id). It works well but I face to encoding issue, I have some accentuated caharacters in the sql file which appears bad in my application. This my code to do this : public String getFileContent(Resources resources, int rawId) throws IOException { InputStream is = resources.openRawResource(rawId); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a string. return new String(buffer); } public void onCreate(SQLiteDatabase db) { try { // get file content String sqlCode = getFileContent(mCtx.getResources(), R.raw.db_create); // execute code for (String sqlStatements : sqlCode.split(";")) { db.execSQL(sqlStatements); } Log.v("Creating database done."); } catch (IOException e) { // Should never happen! Log.e("Error reading sql file " + e.getMessage(), e); throw new RuntimeException(e); } catch (SQLException e) { Log.e("Error executing sql code " + e.getMessage(), e); throw new RuntimeException(e); } The solution I found to avoid this is to load the sql instructions from a huge static final string instead of a file, and all accentutated characters appears well. But Isn't there a more elegant way to load sql instructions than a big static final String attribute with all sql instructions ? Thanks in advance Thomas

    Read the article

  • A way of doing real-world test-driven development (and some thoughts about it)

    - by Thomas Weller
    Lately, I exchanged some arguments with Derick Bailey about some details of the red-green-refactor cycle of the Test-driven development process. In short, the issue revolved around the fact that it’s not enough to have a test red or green, but it’s also important to have it red or green for the right reasons. While for me, it’s sufficient to initially have a NotImplementedException in place, Derick argues that this is not totally correct (see these two posts: Red/Green/Refactor, For The Right Reasons and Red For The Right Reason: Fail By Assertion, Not By Anything Else). And he’s right. But on the other hand, I had no idea how his insights could have any practical consequence for my own individual interpretation of the red-green-refactor cycle (which is not really red-green-refactor, at least not in its pure sense, see the rest of this article). This made me think deeply for some days now. In the end I found out that the ‘right reason’ changes in my understanding depending on what development phase I’m in. To make this clear (at least I hope it becomes clear…) I started to describe my way of working in some detail, and then something strange happened: The scope of the article slightly shifted from focusing ‘only’ on the ‘right reason’ issue to something more general, which you might describe as something like  'Doing real-world TDD in .NET , with massive use of third-party add-ins’. This is because I feel that there is a more general statement about Test-driven development to make:  It’s high time to speak about the ‘How’ of TDD, not always only the ‘Why’. Much has been said about this, and me myself also contributed to that (see here: TDD is not about testing, it's about how we develop software). But always justifying what you do is very unsatisfying in the long run, it is inherently defensive, and it costs time and effort that could be used for better and more important things. And frankly: I’m somewhat sick and tired of repeating time and again that the test-driven way of software development is highly preferable for many reasons - I don’t want to spent my time exclusively on stating the obvious… So, again, let’s say it clearly: TDD is programming, and programming is TDD. Other ways of programming (code-first, sometimes called cowboy-coding) are exceptional and need justification. – I know that there are many people out there who will disagree with this radical statement, and I also know that it’s not a description of the real world but more of a mission statement or something. But nevertheless I’m absolutely sure that in some years this statement will be nothing but a platitude. Side note: Some parts of this post read as if I were paid by Jetbrains (the manufacturer of the ReSharper add-in – R#), but I swear I’m not. Rather I think that Visual Studio is just not production-complete without it, and I wouldn’t even consider to do professional work without having this add-in installed... The three parts of a software component Before I go into some details, I first should describe my understanding of what belongs to a software component (assembly, type, or method) during the production process (i.e. the coding phase). Roughly, I come up with the three parts shown below:   First, we need to have some initial sort of requirement. This can be a multi-page formal document, a vague idea in some programmer’s brain of what might be needed, or anything in between. In either way, there has to be some sort of requirement, be it explicit or not. – At the C# micro-level, the best way that I found to formulate that is to define interfaces for just about everything, even for internal classes, and to provide them with exhaustive xml comments. The next step then is to re-formulate these requirements in an executable form. This is specific to the respective programming language. - For C#/.NET, the Gallio framework (which includes MbUnit) in conjunction with the ReSharper add-in for Visual Studio is my toolset of choice. The third part then finally is the production code itself. It’s development is entirely driven by the requirements and their executable formulation. This is the delivery, the two other parts are ‘only’ there to make its production possible, to give it a decent quality and reliability, and to significantly reduce related costs down the maintenance timeline. So while the first two parts are not really relevant for the customer, they are very important for the developer. The customer (or in Scrum terms: the Product Owner) is not interested at all in how  the product is developed, he is only interested in the fact that it is developed as cost-effective as possible, and that it meets his functional and non-functional requirements. The rest is solely a matter of the developer’s craftsmanship, and this is what I want to talk about during the remainder of this article… An example To demonstrate my way of doing real-world TDD, I decided to show the development of a (very) simple Calculator component. The example is deliberately trivial and silly, as examples always are. I am totally aware of the fact that real life is never that simple, but I only want to show some development principles here… The requirement As already said above, I start with writing down some words on the initial requirement, and I normally use interfaces for that, even for internal classes - the typical question “intf or not” doesn’t even come to mind. I need them for my usual workflow and using them automatically produces high componentized and testable code anyway. To think about their usage in every single situation would slow down the production process unnecessarily. So this is what I begin with: namespace Calculator {     /// <summary>     /// Defines a very simple calculator component for demo purposes.     /// </summary>     public interface ICalculator     {         /// <summary>         /// Gets the result of the last successful operation.         /// </summary>         /// <value>The last result.</value>         /// <remarks>         /// Will be <see langword="null" /> before the first successful operation.         /// </remarks>         double? LastResult { get; }       } // interface ICalculator   } // namespace Calculator So, I’m not beginning with a test, but with a sort of code declaration - and still I insist on being 100% test-driven. There are three important things here: Starting this way gives me a method signature, which allows to use IntelliSense and AutoCompletion and thus eliminates the danger of typos - one of the most regular, annoying, time-consuming, and therefore expensive sources of error in the development process. In my understanding, the interface definition as a whole is more of a readable requirement document and technical documentation than anything else. So this is at least as much about documentation than about coding. The documentation must completely describe the behavior of the documented element. I normally use an IoC container or some sort of self-written provider-like model in my architecture. In either case, I need my components defined via service interfaces anyway. - I will use the LinFu IoC framework here, for no other reason as that is is very simple to use. The ‘Red’ (pt. 1)   First I create a folder for the project’s third-party libraries and put the LinFu.Core dll there. Then I set up a test project (via a Gallio project template), and add references to the Calculator project and the LinFu dll. Finally I’m ready to write the first test, which will look like the following: namespace Calculator.Test {     [TestFixture]     public class CalculatorTest     {         private readonly ServiceContainer container = new ServiceContainer();           [Test]         public void CalculatorLastResultIsInitiallyNull()         {             ICalculator calculator = container.GetService<ICalculator>();               Assert.IsNull(calculator.LastResult);         }       } // class CalculatorTest   } // namespace Calculator.Test       This is basically the executable formulation of what the interface definition states (part of). Side note: There’s one principle of TDD that is just plain wrong in my eyes: I’m talking about the Red is 'does not compile' thing. How could a compiler error ever be interpreted as a valid test outcome? I never understood that, it just makes no sense to me. (Or, in Derick’s terms: this reason is as wrong as a reason ever could be…) A compiler error tells me: Your code is incorrect, but nothing more.  Instead, the ‘Red’ part of the red-green-refactor cycle has a clearly defined meaning to me: It means that the test works as intended and fails only if its assumptions are not met for some reason. Back to our Calculator. When I execute the above test with R#, the Gallio plugin will give me this output: So this tells me that the test is red for the wrong reason: There’s no implementation that the IoC-container could load, of course. So let’s fix that. With R#, this is very easy: First, create an ICalculator - derived type:        Next, implement the interface members: And finally, move the new class to its own file: So far my ‘work’ was six mouse clicks long, the only thing that’s left to do manually here, is to add the Ioc-specific wiring-declaration and also to make the respective class non-public, which I regularly do to force my components to communicate exclusively via interfaces: This is what my Calculator class looks like as of now: using System; using LinFu.IoC.Configuration;   namespace Calculator {     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         public double? LastResult         {             get             {                 throw new NotImplementedException();             }         }     } } Back to the test fixture, we have to put our IoC container to work: [TestFixture] public class CalculatorTest {     #region Fields       private readonly ServiceContainer container = new ServiceContainer();       #endregion // Fields       #region Setup/TearDown       [FixtureSetUp]     public void FixtureSetUp()     {        container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "Calculator.dll");     }       ... Because I have a R# live template defined for the setup/teardown method skeleton as well, the only manual coding here again is the IoC-specific stuff: two lines, not more… The ‘Red’ (pt. 2) Now, the execution of the above test gives the following result: This time, the test outcome tells me that the method under test is called. And this is the point, where Derick and I seem to have somewhat different views on the subject: Of course, the test still is worthless regarding the red/green outcome (or: it’s still red for the wrong reasons, in that it gives a false negative). But as far as I am concerned, I’m not really interested in the test outcome at this point of the red-green-refactor cycle. Rather, I only want to assert that my test actually calls the right method. If that’s the case, I will happily go on to the ‘Green’ part… The ‘Green’ Making the test green is quite trivial. Just make LastResult an automatic property:     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         public double? LastResult { get; private set; }     }         One more round… Now on to something slightly more demanding (cough…). Let’s state that our Calculator exposes an Add() method:         ...   /// <summary>         /// Adds the specified operands.         /// </summary>         /// <param name="operand1">The operand1.</param>         /// <param name="operand2">The operand2.</param>         /// <returns>The result of the additon.</returns>         /// <exception cref="ArgumentException">         /// Argument <paramref name="operand1"/> is &lt; 0.<br/>         /// -- or --<br/>         /// Argument <paramref name="operand2"/> is &lt; 0.         /// </exception>         double Add(double operand1, double operand2);       } // interface ICalculator A remark: I sometimes hear the complaint that xml comment stuff like the above is hard to read. That’s certainly true, but irrelevant to me, because I read xml code comments with the CR_Documentor tool window. And using that, it looks like this:   Apart from that, I’m heavily using xml code comments (see e.g. here for a detailed guide) because there is the possibility of automating help generation with nightly CI builds (using MS Sandcastle and the Sandcastle Help File Builder), and then publishing the results to some intranet location.  This way, a team always has first class, up-to-date technical documentation at hand about the current codebase. (And, also very important for speeding up things and avoiding typos: You have IntelliSense/AutoCompletion and R# support, and the comments are subject to compiler checking…).     Back to our Calculator again: Two more R# – clicks implement the Add() skeleton:         ...           public double Add(double operand1, double operand2)         {             throw new NotImplementedException();         }       } // class Calculator As we have stated in the interface definition (which actually serves as our requirement document!), the operands are not allowed to be negative. So let’s start implementing that. Here’s the test: [Test] [Row(-0.5, 2)] public void AddThrowsOnNegativeOperands(double operand1, double operand2) {     ICalculator calculator = container.GetService<ICalculator>();       Assert.Throws<ArgumentException>(() => calculator.Add(operand1, operand2)); } As you can see, I’m using a data-driven unit test method here, mainly for these two reasons: Because I know that I will have to do the same test for the second operand in a few seconds, I save myself from implementing another test method for this purpose. Rather, I only will have to add another Row attribute to the existing one. From the test report below, you can see that the argument values are explicitly printed out. This can be a valuable documentation feature even when everything is green: One can quickly review what values were tested exactly - the complete Gallio HTML-report (as it will be produced by the Continuous Integration runs) shows these values in a quite clear format (see below for an example). Back to our Calculator development again, this is what the test result tells us at the moment: So we’re red again, because there is not yet an implementation… Next we go on and implement the necessary parameter verification to become green again, and then we do the same thing for the second operand. To make a long story short, here’s the test and the method implementation at the end of the second cycle: // in CalculatorTest:   [Test] [Row(-0.5, 2)] [Row(295, -123)] public void AddThrowsOnNegativeOperands(double operand1, double operand2) {     ICalculator calculator = container.GetService<ICalculator>();       Assert.Throws<ArgumentException>(() => calculator.Add(operand1, operand2)); }   // in Calculator: public double Add(double operand1, double operand2) {     if (operand1 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand1");     }     if (operand2 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand2");     }     throw new NotImplementedException(); } So far, we have sheltered our method from unwanted input, and now we can safely operate on the parameters without further caring about their validity (this is my interpretation of the Fail Fast principle, which is regarded here in more detail). Now we can think about the method’s successful outcomes. First let’s write another test for that: [Test] [Row(1, 1, 2)] public void TestAdd(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Add(operand1, operand2);       Assert.AreEqual(expectedResult, result); } Again, I’m regularly using row based test methods for these kinds of unit tests. The above shown pattern proved to be extremely helpful for my development work, I call it the Defined-Input/Expected-Output test idiom: You define your input arguments together with the expected method result. There are two major benefits from that way of testing: In the course of refining a method, it’s very likely to come up with additional test cases. In our case, we might add tests for some edge cases like ‘one of the operands is zero’ or ‘the sum of the two operands causes an overflow’, or maybe there’s an external test protocol that has to be fulfilled (e.g. an ISO norm for medical software), and this results in the need of testing against additional values. In all these scenarios we only have to add another Row attribute to the test. Remember that the argument values are written to the test report, so as a side-effect this produces valuable documentation. (This can become especially important if the fulfillment of some sort of external requirements has to be proven). So your test method might look something like that in the end: [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 2)] [Row(0, 999999999, 999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, double.MaxValue)] [Row(4, double.MaxValue - 2.5, double.MaxValue)] public void TestAdd(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Add(operand1, operand2);       Assert.AreEqual(expectedResult, result); } And this will produce the following HTML report (with Gallio):   Not bad for the amount of work we invested in it, huh? - There might be scenarios where reports like that can be useful for demonstration purposes during a Scrum sprint review… The last requirement to fulfill is that the LastResult property is expected to store the result of the last operation. I don’t show this here, it’s trivial enough and brings nothing new… And finally: Refactor (for the right reasons) To demonstrate my way of going through the refactoring portion of the red-green-refactor cycle, I added another method to our Calculator component, namely Subtract(). Here’s the code (tests and production): // CalculatorTest.cs:   [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 0)] [Row(0, 999999999, -999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, -double.MaxValue)] [Row(4, double.MaxValue - 2.5, -double.MaxValue)] public void TestSubtract(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Subtract(operand1, operand2);       Assert.AreEqual(expectedResult, result); }   [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 0)] [Row(0, 999999999, -999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, -double.MaxValue)] [Row(4, double.MaxValue - 2.5, -double.MaxValue)] public void TestSubtractGivesExpectedLastResult(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       calculator.Subtract(operand1, operand2);       Assert.AreEqual(expectedResult, calculator.LastResult); }   ...   // ICalculator.cs: /// <summary> /// Subtracts the specified operands. /// </summary> /// <param name="operand1">The operand1.</param> /// <param name="operand2">The operand2.</param> /// <returns>The result of the subtraction.</returns> /// <exception cref="ArgumentException"> /// Argument <paramref name="operand1"/> is &lt; 0.<br/> /// -- or --<br/> /// Argument <paramref name="operand2"/> is &lt; 0. /// </exception> double Subtract(double operand1, double operand2);   ...   // Calculator.cs:   public double Subtract(double operand1, double operand2) {     if (operand1 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand1");     }       if (operand2 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand2");     }       return (this.LastResult = operand1 - operand2).Value; }   Obviously, the argument validation stuff that was produced during the red-green part of our cycle duplicates the code from the previous Add() method. So, to avoid code duplication and minimize the number of code lines of the production code, we do an Extract Method refactoring. One more time, this is only a matter of a few mouse clicks (and giving the new method a name) with R#: Having done that, our production code finally looks like that: using System; using LinFu.IoC.Configuration;   namespace Calculator {     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         #region ICalculator           public double? LastResult { get; private set; }           public double Add(double operand1, double operand2)         {             ThrowIfOneOperandIsInvalid(operand1, operand2);               return (this.LastResult = operand1 + operand2).Value;         }           public double Subtract(double operand1, double operand2)         {             ThrowIfOneOperandIsInvalid(operand1, operand2);               return (this.LastResult = operand1 - operand2).Value;         }           #endregion // ICalculator           #region Implementation (Helper)           private static void ThrowIfOneOperandIsInvalid(double operand1, double operand2)         {             if (operand1 < 0.0)             {                 throw new ArgumentException("Value must not be negative.", "operand1");             }               if (operand2 < 0.0)             {                 throw new ArgumentException("Value must not be negative.", "operand2");             }         }           #endregion // Implementation (Helper)       } // class Calculator   } // namespace Calculator But is the above worth the effort at all? It’s obviously trivial and not very impressive. All our tests were green (for the right reasons), and refactoring the code did not change anything. It’s not immediately clear how this refactoring work adds value to the project. Derick puts it like this: STOP! Hold on a second… before you go any further and before you even think about refactoring what you just wrote to make your test pass, you need to understand something: if your done with your requirements after making the test green, you are not required to refactor the code. I know… I’m speaking heresy, here. Toss me to the wolves, I’ve gone over to the dark side! Seriously, though… if your test is passing for the right reasons, and you do not need to write any test or any more code for you class at this point, what value does refactoring add? Derick immediately answers his own question: So why should you follow the refactor portion of red/green/refactor? When you have added code that makes the system less readable, less understandable, less expressive of the domain or concern’s intentions, less architecturally sound, less DRY, etc, then you should refactor it. I couldn’t state it more precise. From my personal perspective, I’d add the following: You have to keep in mind that real-world software systems are usually quite large and there are dozens or even hundreds of occasions where micro-refactorings like the above can be applied. It’s the sum of them all that counts. And to have a good overall quality of the system (e.g. in terms of the Code Duplication Percentage metric) you have to be pedantic on the individual, seemingly trivial cases. My job regularly requires the reading and understanding of ‘foreign’ code. So code quality/readability really makes a HUGE difference for me – sometimes it can be even the difference between project success and failure… Conclusions The above described development process emerged over the years, and there were mainly two things that guided its evolution (you might call it eternal principles, personal beliefs, or anything in between): Test-driven development is the normal, natural way of writing software, code-first is exceptional. So ‘doing TDD or not’ is not a question. And good, stable code can only reliably be produced by doing TDD (yes, I know: many will strongly disagree here again, but I’ve never seen high-quality code – and high-quality code is code that stood the test of time and causes low maintenance costs – that was produced code-first…) It’s the production code that pays our bills in the end. (Though I have seen customers these days who demand an acceptance test battery as part of the final delivery. Things seem to go into the right direction…). The test code serves ‘only’ to make the production code work. But it’s the number of delivered features which solely counts at the end of the day - no matter how much test code you wrote or how good it is. With these two things in mind, I tried to optimize my coding process for coding speed – or, in business terms: productivity - without sacrificing the principles of TDD (more than I’d do either way…).  As a result, I consider a ratio of about 3-5/1 for test code vs. production code as normal and desirable. In other words: roughly 60-80% of my code is test code (This might sound heavy, but that is mainly due to the fact that software development standards only begin to evolve. The entire software development profession is very young, historically seen; only at the very beginning, and there are no viable standards yet. If you think about software development as a kind of casting process, where the test code is the mold and the resulting production code is the final product, then the above ratio sounds no longer extraordinary…) Although the above might look like very much unnecessary work at first sight, it’s not. With the aid of the mentioned add-ins, doing all the above is a matter of minutes, sometimes seconds (while writing this post took hours and days…). The most important thing is to have the right tools at hand. Slow developer machines or the lack of a tool or something like that - for ‘saving’ a few 100 bucks -  is just not acceptable and a very bad decision in business terms (though I quite some times have seen and heard that…). Production of high-quality products needs the usage of high-quality tools. This is a platitude that every craftsman knows… The here described round-trip will take me about five to ten minutes in my real-world development practice. I guess it’s about 30% more time compared to developing the ‘traditional’ (code-first) way. But the so manufactured ‘product’ is of much higher quality and massively reduces maintenance costs, which is by far the single biggest cost factor, as I showed in this previous post: It's the maintenance, stupid! (or: Something is rotten in developerland.). In the end, this is a highly cost-effective way of software development… But on the other hand, there clearly is a trade-off here: coding speed vs. code quality/later maintenance costs. The here described development method might be a perfect fit for the overwhelming majority of software projects, but there certainly are some scenarios where it’s not - e.g. if time-to-market is crucial for a software project. So this is a business decision in the end. It’s just that you have to know what you’re doing and what consequences this might have… Some last words First, I’d like to thank Derick Bailey again. His two aforementioned posts (which I strongly recommend for reading) inspired me to think deeply about my own personal way of doing TDD and to clarify my thoughts about it. I wouldn’t have done that without this inspiration. I really enjoy that kind of discussions… I agree with him in all respects. But I don’t know (yet?) how to bring his insights into the described production process without slowing things down. The above described method proved to be very “good enough” in my practical experience. But of course, I’m open to suggestions here… My rationale for now is: If the test is initially red during the red-green-refactor cycle, the ‘right reason’ is: it actually calls the right method, but this method is not yet operational. Later on, when the cycle is finished and the tests become part of the regular, automated Continuous Integration process, ‘red’ certainly must occur for the ‘right reason’: in this phase, ‘red’ MUST mean nothing but an unfulfilled assertion - Fail By Assertion, Not By Anything Else!

    Read the article

  • How can I use GPRename's regex feature to reinsert the matched-group into the 'replace'?

    - by David Thomas
    I've been using GPRename to batch-rename files; this is rather more efficient than individually correcting each file, but still seems to be less efficient than it might be, primarily because either I don't understand the regex syntax used, or because the regex implementation is incomplete1 Given a list of files of the following syntax: (01) - title of file1.avi (02) - title of file2.avi (03) - title of file3.avi I attempted to use the 'replace' (with the regex option selected, the case-sensitive option deselected): (\(\d{2}\)) The preview then shows (given that I've specified no 'replace with' option as yet): title of file1.avi title of file2.avi title of file3.avi Which is great, clearly the regex is identifying the correct group (the (01)). Now, what I was hoping to do (using the JavaScript syntax) in the 'replace with' option is use: $1 (I also tried using '$1', \1 and '\1') This was just to check that I could access the matched group, and it seems I can't, the matched group is, as I suppose might be expected, replaced with the literal replacement string. So, my question: is it possible to match a particular group of characters, in this case the numbers within the brackets, and then insert those into the replacement string? Therefore: (01) title of file1.avi (02) title of file2.avi (03) title of file3.avi Becomes: 01 title of file1.avi 02 title of file2.avi 03 title of file3.avi I absolutely suspect the former, personally.

    Read the article

  • How can I secure an installation of MediaWiki?

    - by Thomas Owens
    I want to run an installation of MediaWiki as a Internet-accessible personal wiki, running on wiki.mysite.com. However, I want to ensure that I am the only one who can read and write to this wiki. In the future, I may explicitly give other people read and/or read/write access, so the method of securing the wiki should account for that as well. I see two options: I can use some MediaWiki plugin or I can secure the subdomain with HTTP authentication. However, I'm not sure what the advantages and disadvantages of either are in the long run. Suggestions or advice as to what plugins or authentication methods might be most reliable?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >