Search Results

Search found 406 results on 17 pages for 'dry'.

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

  • How to refactor this Ruby on Rails code?

    - by yuval
    I want to fetch posts based on their status, so I have this code inside my PostsController index action. It seems to be cluttering the index action, though, and I'm not sure it belongs here. How could I make it more concise and where would I move it in my application so it doesn't clutter up my index action (if that is the correct thing to do)? if params[:status].empty? status = 'active' else status = ['active', 'deleted', 'commented'].include?(params[:status]) ? params[:status] : 'active' end case status when 'active' #active posts are not marked as deleted and have no comments is_deleted = false comments_count_sign = "=" when 'deleted' #deleted posts are marked as deleted and have no comments is_deleted = true comments_count_sign = "=" when 'commented' #commented posts are not marked as deleted and do have comments is_deleted = false comments_count_sign = ">" end @posts = Post.find(:all, :conditions => ["is_deleted = ? and comments_count_sign #{comments_count_sign} 0", is_deleted])

    Read the article

  • using yield in C# like I would in Ruby

    - by Sarah Vessels
    Besides just using yield for iterators in Ruby, I also use it to pass control briefly back to the caller before resuming control in the called method. What I want to do in C# is similar. In a test class, I want to get a connection instance, create another variable instance that uses that connection, then pass the variable to the calling method so it can be fiddled with. I then want control to return to the called method so that the connection can be disposed. I guess I'm wanting a block/closure like in Ruby. Here's the general idea: private static MyThing getThing() { using (var connection = new Connection()) { yield return new MyThing(connection); } } [TestMethod] public void MyTest1() { // call getThing(), use yielded MyThing, control returns to getThing() // for disposal } [TestMethod] public void MyTest2() { // call getThing(), use yielded MyThing, control returns to getThing() // for disposal } ... This doesn't work in C#; ReSharper tells me that the body of getThing cannot be an iterator block because MyThing is not an iterator interface type. That's definitely true, but I don't want to iterate through some list. I'm guessing I shouldn't use yield if I'm not working with iterators. Any idea how I can achieve this block/closure thing in C# so I don't have to wrap my code in MyTest1, MyTest2, ... with the code in getThing()'s body?

    Read the article

  • What's the best platform for a static-website?

    - by Earlz
    Hello, I am building a static-website (as in, to change a page, we change the HTML and there is no DB or anything). Well, it will have a number of pages and I don't want to copy and paste the HTML navigation and layout code around everywhere. So what would be the best platform to use in this situation so I can have all my layout and "common" HTML markup all in one place?

    Read the article

  • Is it possible to do a wget dry-run?

    - by Svish
    I know you can download webpages recursively using wget, but is it possible to do a dry-run? So that you could sort of do a test-run to see how much would be downloaded if you actually did it? Thinking about pages that have a lot of links to media files like for example images, audio or movie files.

    Read the article

  • git: Is it possible to save the packed objects of a dry run and push them later?

    - by shovavnik
    I'm trying to push a bunch of commits that contain a lot of code and a few thousand MP3 and PDF files besides (ranging from 5-40 MB each). Git successfully packs the objects: C:\MyProject> git push Counting objects: 7582, done. Delta compression using up to 2 threads. Compressing objects: 100% (7510/7510), done. But it fails to send the push for some as yet unknown reason. The problem is that it takes it a very long time to repack the files (I'm on a battery-powered laptop and it took about 20 minutes to pack). So I guess my question can be phrases thus: Is it possible to save the packed objects created in a dry run? Once saved, is it possible to push those packed objects and avoid repacking? I looked it up in the git manual and elsewhere and couldn't find anything conclusive. Any help or pointers are appreciated.

    Read the article

  • Does overloading Grails static 'mapping' property to bolt on database objects violate DRY?

    - by mikesalera
    Does Grails static 'mapping' property in Domain classes violate DRY? Let's take a look at the canonical domain class: class Book {      Long id      String title      String isbn      Date published      Author author      static mapping = {             id generator:'hilo', params:[table:'hi_value',column:'next_value',max_lo:100]      } } or: class Book { ...         static mapping = {             id( generator:'sequence', params:[sequence_name: "book_seq"] )     } } And let us say, continuing this thought, that I have my Grails application working with HSQLDB or MySQL, but the IT department says I must use a commercial software package (written by a large corp in Redwood Shores, Calif.). Does this change make my web application nobbled in development and test environments? MySQL supports autoincrement on a primary key column but does support sequence objects, for example. Is there a cleaner way to implement this sort of 'only when in production mode' without loading up the domain class?

    Read the article

  • Silverlight DRY when animating multiple UserControls on main Navigation page.

    - by Tobias op den Brouw
    Hello all. Starting with Silverlight development. Yet to read a good Silverlight book: suggestions welcome. I have a main GUI screen where 7 user controls (menu items) 'swoop' into sight, all along their own path. I have the user controls nicely seperated and behaving well. Having multiple storyboards (1 each for each menuitem) with multiple keyframe animations (X,Y,height, width) in one .XAML is not sitting well with me. Repeating all those property values is hideous, neverthemind maintenance. I've tried to move values into the app.xaml and set animation durations with style keys, but having limited success. Can anyone suggest a nice way of making this cleaner? Refactor the storyboards out to their own control? Property values in resources? Dynamic building in codebehind? Referring me to a how-to site is fine as well. Tx!

    Read the article

  • How can I use a single-table inheritance and single controller to make this more DRY?

    - by Angela
    I have three models, Calls, Emails, and Letters and those are basically templates of what gets sent to individuals, modeled as Contacts. When a Call is made, a row in model in ContactCalls gets created. If an Email is sent, an entry in ContactEmails is made. Each has its own controller: contact_calls_controller.rb and contact_emails_controller.rb. I would like to create a single table inheritance called ContactEvents which has types Calls, Emails, and Letters. But I'm not clear how I pass the type information or how to consolidate the controllers. Here's the two controllers I have, as you can see, there's alot of duplication, but some differences that needs to be preserved. In the case of letter and postcards (another Model), it's even more so. class ContactEmailsController < ApplicationController def new @contact_email = ContactEmail.new @contact_email.contact_id = params[:contact] @contact_email.email_id = params[:email] @contact = Contact.find(params[:contact]) @company = Company.find(@contact.company_id) contacts = @company.contacts.collect(&:full_name) contacts.each do |contact| @colleagues = contacts.reject{ |c| [email protected]_name } end @email = Email.find(@contact_email.email_id) @contact_email.subject = @email.subject @contact_email.body = @email.message @email.message.gsub!("{FirstName}", @contact.first_name) @email.message.gsub!("{Company}", @contact.company_name) @email.message.gsub!("{Colleagues}", @colleagues.to_sentence) @email.message.gsub!("{NextWeek}", (Date.today + 7.days).strftime("%A, %B %d")) @contact_email.status = "sent" end def create @contact_email = ContactEmail.new(params[:contact_email]) @contact = Contact.find_by_id(@contact_email.contact_id) @email = Email.find_by_id(@contact_email.email_id) if @contact_email.save flash[:notice] = "Successfully created contact email." # send email using class in outbound_mailer.rb OutboundMailer.deliver_campaign_email(@contact,@contact_email) redirect_to todo_url else render :action => 'new' end end AND: class ContactCallsController < ApplicationController def new @contact_call = ContactCall.new @contact_call.contact_id = params[:contact] @contact_call.call_id = params[:call] @contact_call.status = params[:status] @contact = Contact.find(params[:contact]) @company = Company.find(@contact.company_id) @contact = Contact.find(@contact_call.contact_id) @call = Call.find(@contact_call.call_id) @contact_call.title = @call.title contacts = @company.contacts.collect(&:full_name) contacts.each do |contact| @colleagues = contacts.reject{ |c| [email protected]_name } end @contact_call.script = @call.script @call.script.gsub!("{FirstName}", @contact.first_name) @call.script.gsub!("{Company}", @contact.company_name ) @call.script.gsub!("{Colleagues}", @colleagues.to_sentence) end def create @contact_call = ContactCall.new(params[:contact_call]) if @contact_call.save flash[:notice] = "Successfully created contact call." redirect_to contact_path(@contact_call.contact_id) else render :action => 'new' end end

    Read the article

  • What's the most DRY-appropriate way to execute an SQL command?

    - by Sean U
    I'm looking to figure out the best way to execute a database query using the least amount of boilerplate code. The method suggested in the SqlCommand documentation: private static void ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } } finally { reader.Close(); } } } mostly consists of code that would have to be repeated in every method that interacts with the database. I'm already in the habit of factoring out the establishment of a connection, which would yield code more like the following. (I'm also modifying it so that it returns data, in order to make the example a bit less trivial.) private SQLConnection CreateConnection() { var connection = new SqlConnection(_connectionString); connection.Open(); return connection; } private List<int> ReadOrderData() { using(var connection = CreateConnection()) using(var command = connection.CreateCommand()) { command.CommandText = "SELECT OrderID FROM dbo.Orders;"; using(var reader = command.ExecuteReader()) { var results = new List<int>(); while(reader.Read()) results.Add(reader.GetInt32(0)); return results; } } } That's an improvement, but there's still enough boilerplate to nag at me. Can this be reduced further? In particular, I'd like to do something about the first two lines of the procedure. I don't feel like the method should be in charge of creating the SqlCommand. It's a tiny piece of repetition as it is in the example, but it seems to grow if transactions are being managed manually or timeouts are being altered or anything like that.

    Read the article

  • LinqToSql: How can I create a projection to adhere to DRY?

    - by mhutter
    Just wondering if there is a way to take some of the repitition out of a LINQ to SQL projected type. Example: Table: Address Fields: AddressID, HouseNumber, Street, City, State, Zip, +20 more Class MyAddress: AddressID, HouseNumber, Street (Only 3 fields) LINQ: from a in db.Addresses select new MyAddress { AddressID = a.AddressID, HouseNumber = a.HouseNumber, Street = a.Street } The above query works perfectly, and I understand why something like this will return all 20+ fields in each row: from a in db.Addresses select new MyAddress(a); class MyAddress { public MyAddress(Address a) { this.AddressID = a.AddressID, this.HouseNumber = a.HouseNumber, this.Street = a.Street } } Which leads me to my Question: Is it possible to implement some kind of helper function or extension method to "map" from the LINQ model to MyAddress yet only return the necessary fields in the query result rather than all of the fields?

    Read the article

  • Bejeweled Blitz - How does it assert there is always a move?

    - by EvilTeach
    I have been playing Bejeweled Blitz for a while now. Yes, it is an addiction. In thinking about the game, I have observed that on some boards, the bottom runs dry (no moves) leaving only the top part of the board playable. Frequently that part of the board drys up, and one is left with moves in area cleared by the last move. The board never runs completely dry, so clearly the program is doing some sorts of calculation that allows it to choose what to drop to prevent it from running dry. I have noticed in this 'mode' that it is very common for the algorithm to drop jewels which causes more non-dry area to appear in the horizontal area. Perhaps less frequent is a drop which seems designed to open up the bottom part of the board again. So my question is "How would one go about designing an algorithm guarantee that there is always a move available.?"

    Read the article

  • Tester that doesn't test

    - by George
    What should I do about a tester that does not test? We have a complicated dry run scenario, that takes a lot of time to execute. Mostly this tester will execute it's tests in very slow way...checking emails, internet, etc. He reports just a few bugs, but! Whenever the official dry-run begins (these are logged with testlink) the tester starts to open new bugs that where not discovered before. Is he not doing his job correctly? Or am I just overlooking how tests work? I'm not his supervisor, but he is testing code that I wrote.

    Read the article

  • How to have operations with character/items in binary with concrete operations?

    - by Piperoman
    I have the next problem. A item can have a lot of states: NORMAL = 0000000 DRY = 0000001 HOT = 0000010 BURNING = 0000100 WET = 0001000 COLD = 0010000 FROZEN = 0100000 POISONED= 1000000 A item can have some states at same time but not all of them Is impossible to be dry and wet at same time. If you COLD a WET item, it turns into FROZEN. If you HOT a WET item, it turns into NORMAL A item can be BURNING and POISON Etc. I have tried to set binary flags to states, and use AND to combine different states, checking before if it is possible or not to do it, or change to another status. Does there exist a concrete approach to solve this problem efficiently without having an interminable switch that checks every state with every new state? It is relatively easy to check 2 different states, but if there exists a third state it is not trivial to do.

    Read the article

  • How to have operations with character/items on binary with concrete operations on C++?

    - by Piperoman
    I have the next problem. A item can have a lot of states: NORMAL = 0000000 DRY = 0000001 HOT = 0000010 BURNING = 0000100 WET = 0001000 COLD = 0010000 FROZEN = 0100000 POISONED= 1000000 A item can have some states at same time but not all of them Is impossible to be dry and wet at same time. If you COLD a WET item, it turns into FROZEN. If you HOT a WET item, it turns into NORMAL A item can be BURNING and POISON Etc. I have tried to set binary flags to states, and use AND to combine different states, checking before if it is possible or not to do it, or change to another status. Does there exist a concrete approach to solve this problem efficiently without having an interminable switch that checks every state with every new state? It is relatively easy to check 2 different states, but if there exists a third state it is not trivial to do.

    Read the article

  • How to had operation with character/items on binary with concrete operations on C++?

    - by Piperoman
    I have the next problem. A item can had a lot of states: NORMAL = 0000000 DRY = 0000001 HOT = 0000010 BURNING = 0000100 WET = 0001000 COLD = 0010000 FROZEN = 0100000 POISONED= 1000000 A item can had some states at same time but not all of them Is impossible to be dry and wet at same time. If you COLD a WET item, it turns into FROZEN. If you HOT a WET item, it turns into NORMAL A item can be BURNING and POISON Etc. I have try to set binary flags to states, and use AND to set operation to combine different states, checking before if is possible or not to do it, or change to another status. Exist a concrete patron to solve this problem efficiently without had a interminable switch that check every states with everynew states? It is relative easy to check 2 different states, but if exist a third state it is not trivial to do.

    Read the article

  • backing up ntfs disk using rsync on ubuntu

    - by user70366
    For a long time I was using windows. I have a separate drive I use to keep copies of my media files, photos etc. on, which I periodically backup to an external drive. In Windows I used SyncToy to do this. After my Windows stopped booting, I decided to switch to Linux (Ubuntu 10.10). That seems to be going fine, but now I want to backup my drive to the external drive like before. Mostly the two drives will be already the same with maybe about 10GB of extra files added. So I try to use rsync to synchronise the two drives like this: rsync --dry-run -rvlt --modify-window=1 /media/Antonio1TB/Backup /media/FREECOM\ HDD/Backup The problem is the dry run indicates that every file on the drive will be copied. Not just the files I have recently added. What is the correct command to synch two NTFS drives under Ubuntu so that files that already exist don't get copied again? Thanks.

    Read the article

  • backing up ntfs disk using rsync on ubuntu

    - by user70366
    For a long time I was using windows. I have a separate drive I use to keep copies of my media files, photos etc. on, which I periodically backup to an external drive. In Windows I used SyncToy to do this. After my Windows stopped booting, I decided to switch to Linux (Ubuntu 10.10). That seems to be going fine, but now I want to backup my drive to the external drive like before. Mostly the two drives will be already the same with maybe about 10GB of extra files added. So I try to use rsync to synchronise the two drives like this: rsync --dry-run -rvlt --modify-window=1 /media/Antonio1TB/Backup /media/FREECOM\ HDD/Backup The problem is the dry run indicates that every file on the drive will be copied. Not just the files I have recently added. What is the correct command to synch two NTFS drives under Ubuntu so that files that already exist don't get copied again? Thanks.

    Read the article

  • MVC2 Client validation with Annotations in View with RenderAction

    - by Olle
    I'm having problem with client side validation on a View that renders a dropdownlist with help of a Html.RenderAction. I have two controllers. SpecieController and CatchController and I've created ViewModels for my views. I want to keep it as DRY as possible and I will most probably need a DropDownList for all Specie elsewhere in the near future. When I create a Catch i need to set a relationship to one specie, I do this with an id that I get from the DropDownList of Species. ViewModels.Catch.Create [Required] public int Length { get; set; } [Required] public int Weight { get; set; } [Required] [Range(1, int.MaxValue)] public int SpecieId { get; set; } ViewModels.Specie.List public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; } public IEnumerable<SelectListItem> Species { get; private set; } My View for the Catch.Create action uses the ViewModels.Catch.Create as a model. But it feels that I'm missing something in the implemetation. What I want in my head is to connect the selected value in the DropDownList that comes from the RenderAction to my SpecieId. View.Catch.Create <div class="editor-label"> <%: Html.LabelFor(model => model.SpecieId) %> </div> <div class="editor-field"> <%-- Before DRY refactoring, works like I want but not DRY <%: Html.DropDownListFor(model => model.SpecieId, Model.Species) %> --%> <% Html.RenderAction("DropDownList", "Specie"); %> <%: Html.ValidationMessageFor(model => model.SpecieId) %> </div> CatchController.Create [HttpPost] public ActionResult Create(ViewModels.CatchModels.Create myCatch) { if (ModelState.IsValid) { // Can we make this StronglyTyped? int specieId = int.Parse(Request["Species"]); // Save to db Catch newCatch = new Catch(); newCatch.Length = myCatch.Length; newCatch.Weight = myCatch.Weight; newCatch.Specie = SpecieService.GetById(specieId); newCatch.User = UserService.GetUserByUsername(User.Identity.Name); CatchService.Save(newCatch); } This scenario works but not as smooth as i want. ClientSide validation does not work for SpecieId (after i refactored), I see why but don't know how I can ix it. Can I "glue" the DropDownList SelectedValue into myCatch so I don't need to get the value from Request["Species"] Thanks in advance for taking your time on this.

    Read the article

  • Subjective question...would you use the Action delegate to avoid duplication of code?

    - by Seth Spearman
    Hello, I just asked a question that helps about using generics (or polymorphism) to avoid duplication of code. I am really trying to follow the DRY principle. So I just ran into the following code... Sub OutputDataToExcel() OutputLine("Output DataBlocks", 1) OutputDataBlocks() OutputLine("") OutputLine("Output Numbered Inventory", 1) OutputNumberedInventory() OutputLine("") OutputLine("Output Item Summaries", 1) OutputItemSummaries() OutputLine("") End Sub Should I rewrite this code to be as follows using the Action delegate... Sub OutputDataToExcel() OutputData("Output DataBlocks", New Action(AddressOf OutputDataBlocks)) OutputData("Output Numbered Inventory", New Action(AddressOf OutputNumberedInventory)) OutputData("Output Item Summaries", New Action(AddressOf OutputItemSummaries)) End Sub Sub OutputData(ByVal outputDescription As String, ByVal outputType As Action) OutputLine(outputDescription, 1) outputType() OutputLine("") End Sub I realize this question is subjective. I am just wondering about how religiously you follow DRY. Would you do this? Seth

    Read the article

  • Custom array sort in perl

    - by ABach
    I have a perl array of to-do tasks that looks like this: @todos = ( "1 (A) Complete online final @evm4700 t:2010-06-02", "3 Write thank-you t:2010-06-10", "4 (B) Clean t:2010-05-30", "5 Donate to LSF t:2010-06-02", "6 (A) t:2010-05-30 Pick up dry cleaning", "2 (C) Call Chris Johnson t:2010-06-01" ); That first number is the task's ID. If a task has ([A-Z]) next to, that defines the task's priority. What I want to do is sort the tasks array in a way that places the prioritized items first (and in order): @todos = ( "1 (A) Complete online final @evm4700 t:2010-06-02", "6 (A) t:2010-05-30 Pick up dry cleaning", "4 (B) Clean t:2010-05-30", "2 (C) Call Chris Johnson t:2010-06-01" "3 Write thank-you t:2010-06-10", "5 Donate to LSF t:2010-06-02", ); I cannot use a regular sort() because of those IDs next to the tasks, so I'm assuming that some sort of customized sorting subroutine is needed. However, my knowledge of how to do this efficiently in perl is minimal. Thanks, all.

    Read the article

  • Show different sub-sets in edit view

    - by Martin R-L
    In the context of C# 4, ASP.NET MVC 2, and NHibernate; I've got the following scenario: Let's assume an entity Product that have an association to ProductType. In a product edit view; how do I implement that only a sub-set of the product's properties are shown in an elegant and DRY way? Use a product view model builder, and from different view models automagically generate the view with my own Html.EditorForModel() (including drop-downs and other stuff not out-of-the-box)? Attribute the properties of one view model and use the Html.EditorForModel() way aforementioned? Use one model, but implement different web controls (view strategies) (can it be done DRY?)? Something else entirely?

    Read the article

  • Adding a generic image field onto a ModelForm in django

    - by Prairiedogg
    I have two models, Room and Image. Image is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY. Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. Update: I've tried to clarify why I chose this design in comments to the current answers. To summarize: I didn't simply put an ImageField on the Room model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single Image class, which seemed messy, or multiple Image classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that. Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed. # Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context)

    Read the article

  • How can I pass a dynamic backing bean into a JSF 2.0 page using facelets?

    - by kgrad
    Hi, I am using a JSF 2.0 to create a web app (purely jee6, without spring/seam etc.). I would like to have a single xhtml page but pass the proper backing bean / entity into it. For example, I would like to be able to edit a user other than the logged in user, I have a user edit page which displays the information of the logged in user (being tracked by my session), I would like to instead pass in a user selected from a list and edit that user's information, without switching the user that is stored in the session or creating a separate xhtml page (violating DRY). The "best" way I can see to achieve this would be to reuse the exact same xhtml page that I am using to display the logged-in-user's edit page, but simply pass in a different entity in some way. Perhaps calling the setter in the backing bean before redirecting to the page (if this is even possible) or some other solution that does not violate DRY. Perhaps I have designed this all wrong, is there a way to pass in entities to JSF pages? thanks.

    Read the article

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