refactor-my-code

select single item from a collection : Python

I created a utility function to return the expected single item from an generator expression print one(name for name in ('bob','fred') if name=='bob') Is this a good way to go about it? def one(g): try: val = g.next() try: g.next() except StopIteration: return val else: ...

Subtract from an input appended list with a running balance output

Noob I am trying to write a script that gives a running balance. I am messing up on the elementary declared functions of python. I need it too: accept a balance via input append a list of transactions take those out one by one in the order they were input print a running total use pyhtmltable to make the output in html table rea...

String Benchmarks in C# - Refactoring for Speed/Maintainability

I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code). I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with. A...

refactor this dictionary-to-xml converter in python

It's a small thing, really: I have this function that converts dict objects to xml. Here's the function: def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node....

Refactor subqueries using GROUP BY/HAVING?

I'm building a MySQL query to determine how many items from each of several categories appear in a given date range. My initial attempt looked like this: select Title, (select count(*) from entries where CategoryID=1 and Date >= @StartDate and Date <= @EndDate) as Cat1, (select count(*) from entries where CategoryID=2 and Da...

Refactoring in model: what's going wrong?

I'm currently trying to DRY up this initial verbose code: def planting_dates_not_nil? !plant_out_week_min.blank? || !plant_out_week_max.blank? || !sow_out_week_min.blank? || !sow_out_week_max.blank? end def needs_planting?(week) if !plant_out_week_min.blank? && !plant_out_week_max.blank? (plant_out_week_min..plant_out...

Refactor my C# code - Switch statement

I have the following code which I am are currently using .... Basically, this method assigns the correct boolean flag (TRUE/FALSE) for each Task. As more and more tasks need to be added .. I can see that the switch statement will have to grow to cater for every task. There has to be an easier way ... to keep the method small. Code: (fo...

ASP C# How to program neat GUI code

For about a few months i'm programming ASP C#. I always program a lot code in the events and in the load event i check the querystring for valid data. This is some sample code i have in one of my projects: protected void Page_Load(object sender, EventArgs e) { if (Controller.Manual == null) { Response.Redirect("login.asp...

best way of replacing all tags in a string with java

I have a service method that takes a String and then replaces tags in the String with items from a tag library. As follows: for( MetaDataDTO tag : tagValues ) { message = message.replace( tag.getKey(), tag.getText1() ); } Obviously; this make heaps of new strings and is BAD. But the StringBuilder replace method is cumbersome to ...

How can I refactor this jQuery code?

The code below is for a simple newsletter signup widget. I'm sure there's a way to make it more concise, any ideas? var email_form = $('.widget_subscribe form'); var email_submit = $('.widget_subscribe .submit'); var email_link = $('.widget_subscribe .email'); // Hide the email entry form when the page loads email_form.hide(); // Sh...

Make it pretty: processing an array concurrently

I want to convert this linear loop into a concurrent one: for(Item item : ItemList) { processItem(item); } Is this really the shortest way to do this? class Worker implements Runnable { Item item; Worker(Item item) { this.item = item; } public void Run() { processItem(item); } } ExecutorServic...

How to refactor this Ruby (controller) code?

This is the code in my reports controller, it just looks so bad, can anyone give me some suggestions on how to tidy it up? # app\controller\reports_controller.rb @report_lines = [] @sum_wp, @sum_projcted_wp, @sum_il, @sum_projcted_il, @sum_li,@sum_gross_profit ,@sum_opportunities = [0,0,0,0,0,0,0] date = @start_date num_of_...

How to refactor this conditional to avoid repetition?

This is part of an events page that can be filtered by date (using pre-defined date ranges or a date picker). I want to avoid repeating the whole foreach ($days as $day_number)... etc. loop for every condition. I guess that whole loop could be moved to a function, but I'm not sure how to implement it. <?php // open the db connection ...

Remove boilerplate from db code

It seems that every time I want to perform a db query, I have to write the following: Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(sql); // ...set stmt params rset = stmt.executeQuery(); while(rset.next()) { // Do ...

Better way to extract phone number and reformat?

Phone number data in various formats (I've chosen these because the data coming in is unreliable and not in expected formats): +1 480-874-4666 404-581-4000 (805) 682-4726 978-851-7321, Ext 2606 413- 658-1100 (513) 287-7000,Toll Free (800) 733-2077 1 (813) 274-8130 212-363-3200,Media Relations: 212-668-2251. 323/221-2164 My Ruby code t...

Count matching characters between two strings using LINQ

A friend asked me how to improve some code with LINQ. How would you do a character by character comparison between two strings to count the number of matches at an index? Here's the original code, could it be improved with LINQ? private int Fitness(string individual, string target) { int sum = 0; for (int i = 0; i < ind...

Is it possible to check if pdostatement::fetch() has results without iterating through a row?

I have a page which needs to check for results, and the way I came up with to do it is successful, but iterates through the first row of results. Is there a way I can check without iterating, or to go back to that first row without executing the query again? I was doing this: $q = pdo::prepare($SQL); $q->execute(array(':foo'=> foo, '...

Is this the way to go about building Perl subroutines?

So I've had a simple ucwords function for Perl which I've had a while, and wanted to expand it, this is what I've come up with, is this the way I should be building my functions to handle optional parameters? Original: sub ucwords{ $str = @_[0]; $str = lc($str); $str =~ s/\b(\w)/\u$1/g; return $str; } Extended: sub u...

PDO in PHP, how to improve this PDO mysql code

Thanks for checking. All helpful answers/comments are up voted. I have the following code, which does the job, but imo is not efficient. The reason I think it's not efficient is because I'm using fetchAll + loop even though I know that the query will return either 1 or no records. //assume the usual new PDO, binding, and execute are up ...

Refactoring the following methods to remove duplicate code

I have a bunch of DAO classes that do something similar for an Entity. I was wondering if anyone can help me with ways to: 1) Simplify this code 2) Stop from duplicating code like this for each entity. public IList<IUser> GetAll() { IList<IUser> users = new List<IUser>(); using (var myConnection = new SqlConnect...