tag:refactormycode.com,2007:codesrecent Recent codes Fri Dec 05 11:46:21 +0000 2008 tag:refactormycode.com,2007:Code653 2008-12-05T11:42:04+00:00 2008-12-05T11:46:21+00:00 [Ruby] Photograhy methods <p>Any comments, corrections, refactorings or suggestions would be fantastic, thanks. <br />Hopefully we might have some photography nuts out there too :)</p> <pre># camera related def frame_diagonal(frame_horizontal, frame_vertical) @frame_diagonal = Math.sqrt((frame_horizontal**2) + (frame_vertical**2)) end def focal_length_multiplier(frame_diagonal_1, frame_diagonal_2) @focal_length_multiplier = frame_diagonal_1 / frame_diagonal_2 end def circle_of_confusion(frame_diagonal) @circle_of_confusion = frame_diagonal / 1730 end # lens related def hyperfocal_distance(focal_length, f_number, circle_of_confusion) @hyperfocal_distance = ((focal_length**2) / (f_number * circle_of_confusion)) + focal_length end def near_distance(focus_distance, hyperfocal_distance, focal_length) @near_distance = (focus_distance * (hyperfocal_distance - focal_length)) / (hyperfocal_distance + focus_distance - 2 * focal_length) end def far_distance(focus_distance, hyperfocal_distance, focal_length) @far_distance = (focus_distance * (hyperfocal_distance - focal_length)) / (hyperfocal_distance - focus_distance) end def total_distance(near_distance, far_distance) @total_distance = far_distance - near_distance end def magnification(focal_length, focus_distance) @magnification = focal_length/(focus_distance - focal_length) end def fov_rectilinear_horizontal(frame_horizontal, focal_length, magnification) @fov_rectilinear = 2 * Math.arctan(frame_horizontal/(focal_length * 2 * (magnification+1))) end def fov_rectilinear_vertical(frame_vertical, focal_length, magnification) @fov_rectilinear = 2 * Math.arctan(frame_vertical/(focal_length * 2 * (magnification+1))) end def fov_rectilinear_diagonal(frame_diagonal, focal_length, magnification) @fov_rectilinear = 2 * Math.arctan(frame_diagonal/(focal_length * 2 * (magnification+1))) end def f_number_to_aperture_diameter(focal_length, f_number) @aperture_diameter = focal_length / f_number end # exposure related def exposure_value(f_number, shutter_speed) @exposure_value = Math.logn(2, (f_number**2 / shutter_speed)) end # math related def Math.logn(x, n) Math.log(x) / Math.log(n) end def Math.arctan(x) Math.atan2(x, 1.0) end</pre> sfusion.myopenid.com sfusion@gmail.com tag:refactormycode.com,2007:Code652 2008-12-05T11:36:17+00:00 2008-12-05T11:36:17+00:00 [Java] Read/download images from an URL <p>Hi guys, <br />This code downloads some images from the given URL to the hard drive. <br />In my case I know the URL of the images and the number images of each folder :).</p> <pre>import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class ImagesDownloader { public static void main(String[] args) throws IOException { getImages(&quot;cars&quot;, &quot;bikes&quot;, &quot;motors&quot;); } private static void getImages(String... folders) throws IOException { String imagesRootPath = &quot;http://www.mysite.com/images&quot;; for (String folder : folders) { for (int i = 1; i &lt; 31; i++) { URL url = new URL(String.format(&quot;%s/%s/%d.gif&quot;, imagesRootPath, folder, i)); InputStream in = url.openStream(); OutputStream out = new BufferedOutputStream(new FileOutputStream(String.format(&quot;images/%s/%d.gif&quot;, folder, i))); for (int b; (b = in.read()) != -1; ) { out.write(b); } out.close(); in.close(); System.out.println(String.format(&quot;Image %d.gif from folder %s has been successfully downloaded.&quot;, i, folder)); } } } } </pre> Hbiloo waarheid08@gmail.com tag:refactormycode.com,2007:Code628 2008-11-27T13:45:53+00:00 2008-11-27T17:18:05+00:00 [Ruby] Displaying numbers to words. <p>Is it possible to refactore this code in order to display numbers to words from 1 - 1000000 only.</p> <pre>module Verbal module English module Numbers EXPONENT_EN = { 0 =&gt; '', 3 =&gt; 'thousand', 6 =&gt; 'million', 9 =&gt; 'billion', 12 =&gt; 'trillion', 15 =&gt; 'quadrillion', 18 =&gt; 'quintillion', 21 =&gt; 'sextillion' } NUMBERS_EN = { 0 =&gt; 'zero', 1 =&gt; 'one', 2 =&gt; 'two', 3 =&gt; 'three', 4 =&gt; 'four', 5 =&gt; 'five', 6 =&gt; 'six', 7 =&gt; 'seven', 8 =&gt; 'eight', 9 =&gt; 'nine', 10 =&gt; 'ten', 20 =&gt; 'twenty', 30 =&gt; 'thirty', 40 =&gt; 'fourty', 50 =&gt; 'fifty', 60 =&gt; 'sixty', 70 =&gt; 'seventy', 80 =&gt; 'eighty', 90 =&gt; 'ninety', 11 =&gt; 'eleven', 12 =&gt; 'twelve', 13 =&gt; 'thirteen', 14 =&gt; 'fourteen', 15 =&gt; 'fifteen', 16 =&gt; 'sixteen', 17 =&gt; 'seventeen', 18 =&gt; 'eighteen', 19 =&gt; 'nineteen' } def to_words(value) raise 'value must be an integer' unless value.is_a?(Integer) @exponent = Verbal::Core::exponent(value) @extracted_exponents = Verbal::Core::process_thousands(value) @in_words = '' @extracted_exponents.each do |e, v| @in_words &lt;&lt; &quot;#{process_hundreds(v, e, @exponent)} #{EXPONENT_EN[e]} &quot; end return @in_words.strip.squeeze(' ') end def process_hundreds(value, current_exponent, value_exponent) raise 'value should be in range: 0.999' unless (0..999).include?(value) if value &gt; 100 hundreds_count = value / 100 if value % 100 == 0 return NUMBERS_EN[hundreds_count] + ' hundred' else prefix = &quot;#{(value_exponent != 0 &amp;&amp; current_exponent == 0) ? ' and ': ''}&quot; return NUMBERS_EN[hundreds_count] + ' hundred ' + process_tens(value % 100, prefix) end else prefix = &quot;#{(value_exponent != 0 &amp;&amp; current_exponent == 0) ? ' and ': ''}&quot; return process_tens(value % 100, prefix) end end def process_tens(value, prefix) raise 'value should be in range: 0..99' unless (0..99).include?(value) return prefix + NUMBERS_EN[value] if value &lt; 9 return prefix + NUMBERS_EN[(value / 10) * 10] if (value % 10) == 0 if (11..19).include?(value) return prefix + NUMBERS_EN[value] else return prefix + NUMBERS_EN[(value / 10) * 10] + '-' + NUMBERS_EN[value % 10] end end module_function :to_words, :process_hundreds, :process_tens end end end</pre> ytse.myopenid.com jaredtse@hotmail.com tag:refactormycode.com,2007:Code627 2008-11-27T04:21:57+00:00 2008-11-27T04:21:57+00:00 [Python] Williams Words <p>For my blog: <a href="http://www.cmurphycode.blogspot.com" target="_blank">http://www.cmurphycode.blogspot.com</a></p> <p>A little project via Kottke (<a href="http://www.kottke.org/08/11/williams-poems" target="_blank">http://www.kottke.org/08/11/williams-poems</a>), that I thought would be easy and fun. No need to actually refactor unless you're truly bored- I'm just experimenting with using this as a place to share code. </p> <pre>import sys #input into this structure words = {} #strings generated go here gen = [] #input word word = &quot;&quot; #final output final = [] #first arg = word to parse, second arg = wordlist name, optional, third arg = (generated word) minimum length, optional arglength = len(sys.argv) if arglength &gt; 1: word = sys.argv[1] else: print &quot;Please specify an input file&quot; quit() if arglength &gt; 2: list = sys.argv[2] else: print &quot;Using default wordlist.txt&quot; list = &quot;wordlist.txt&quot; if arglength &gt; 3: cutoff = int(sys.argv[3]) else: print &quot;Using default cutoff of 1 letter&quot; cutoff = 1 #create output file based on the word we're generating outFile = &quot;output-&quot; + word + &quot;.txt&quot; out = open(outFile, 'w') #create input file f = open(list,'r') #file is one word per line, strip out the endline character, and throw in a dictionary for line in f: line = line.strip() if len(line) &gt; cutoff: words[line] = 1 #recurse calculates all the substrings forward, is exponential #input: current string, base string #example: spray =&gt; recurse(&quot;s&quot;,&quot;pray&quot;), recurse(&quot;&quot;,&quot;pray&quot;) def recurse(current, string): if string == &quot;&quot;: return gen.append(current) gen.append(str(current + string[:1])) recurse(current, string[1:]) recurse(str(current + string[:1]), string[1:]) #check the generated strings for words #input: string list, word list def checkOverlap(gen, words): for item in gen: #these are just strings, so lets check if they're words if item in words: #ignoring duplicates as we go if item not in final: final.append(item) #start recursion on the input word recurse(&quot;&quot;, word) #given the generated strings, find the words checkOverlap(gen, words) #sort the output final.sort() #write the output for item in final: out.write(item) out.write('\n') print &quot;Output written to &quot; + outFile</pre> cmurphycode.blogspot.com tag:refactormycode.com,2007:Code626 2008-11-26T19:01:18+00:00 2008-11-26T19:45:34+00:00 [Ruby] Doing a 'blank?' in named_scope <p>Can you do a .blank? in a named_scope? (MySQL)</p> <pre>named_scope :with_description, :conditions =&gt; &quot;description IS NOT NULL and trim(description) != ''&quot; </pre> Jo jopotts@gmail.com tag:refactormycode.com,2007:Code625 2008-11-26T17:30:38+00:00 2008-11-26T23:24:46+00:00 [Java] Factoring Integers <p>After taking all the factors of 60 (2, 2, 3, 5), when I invoke hasMoreFactors(), it should return false, cause there are no other factors beyond that 5, yet I can only get it to return true. Any ideas?</p> <pre>/** This class generates all the factors of a number. */ public class FactorGenerator { private boolean answer; private int factor, number; /** Creates a FactorGenerator object used to determine the factor of an input value. @param aNum is the input value */ public FactorGenerator(int aNum) { number = aNum; factor = 2; } /** Determine whether or not there are more factors. @return true there are more factors */ public boolean hasMoreFactors() { answer = true; while(number % factor != 0 &amp;&amp; answer == true) { if (factor &gt;= number) { answer = false; } factor++; } return answer; } /** Calculate the next factor of a value. @return factor the next factor */ public int nextFactor() { while(factor &lt; number) { if(number%factor == 0) { number/= factor; break; } else factor++; } return factor; } } </pre> Kellyscoth kellyscoth@gmail.com tag:refactormycode.com,2007:Code622 2008-11-25T16:33:17+00:00 2008-11-27T02:15:58+00:00 [C#] Filterting a List<> with a Regular Expression <p>Have the below code which filters a generic list for certain values. I haven't considered using a predicates to achieve the same effect,</p> <p>Thanks</p> <pre> List&lt;Document&gt; documents = documentLayer.GetDocuments(username); List&lt;Document&gt; filteredDocuments = new List&lt;Document&gt;(); string documentName = (string)Session[&quot;DocumentName&quot;]; string documentAuthor = (string)Session[&quot;DocumentAuthor&quot;]; if ((string.IsNullOrEmpty(documentName)) &amp;&amp; (string.IsNullOrEmpty(documentAuthor))) { documents.DataSource = documents; documents.DataBind(); } else { foreach (Document document in documents) { string name = document.Name; string author = document.Author; if (!(string.IsNullOrEmpty(documentName)) &amp;&amp; !(string.IsNullOrEmpty(documentAuthor))) { if ((Regex.IsMatch(name, documentName)) &amp;&amp; (Regex.IsMatch(author, documentAuthor))) { filteredDocuments.Add(document); } } else if (string.IsNullOrEmpty(documentName)) { if (Regex.IsMatch(author, documentAuthor)) { filteredDocuments.Add(document); } } else if (string.IsNullOrEmpty(documentAuthor)) { if (Regex.IsMatch(name, documentName)) { filteredDocuments.Add(document); } } } documents.DataSource = filteredDocuments; documents.DataBind(); }</pre> mantis7.myopenid.com tag:refactormycode.com,2007:Code621 2008-11-25T14:08:00+00:00 2008-11-26T21:24:30+00:00 [Ruby] Converting Textile to S5 <p>I'd like to take a bunch of textile and turn it into an s5 file. <br />I was trying to use rubular to isolate blocks of text, but couldn't get just the seperate blocks isolated... Went to looping and ended up with this monstrosity. <br />There has to be a better way.</p> <p>example regex trial over at <a href="http://www.rubular.com/regexes/4983" target="_blank">http://www.rubular.com/regexes/4983</a> <br />closer, but eliminate any more special characters and you get chaos <br /><a href="http://www.rubular.com/regexes/4986" target="_blank">http://www.rubular.com/regexes/4986</a> </p> <pre>/* sample input h1. Introduction * s5 is way cool, but I think in textile * textile is easy to write * it would be great to take a bunch of textile and transform it instantly into an s5 presentation h1. Regular Expressions * they are difficult for multiple lines * http://www.rubular.com/ helps, but I can't narrow it down to the simple bits. * let's go shopping or use loops h1. Looping * redcloth does the hard work * you just need to surround the redcloth output with &lt;div class=slide&gt; &lt;/div&gt; * this code smells so bad h1. You * please make sense of this */ def convert_from_textile_to_s5(fin) slide = &quot;&quot; File.open(fin) do | file_in| lines = file_in.readlines i=0 while i &lt; lines.length if lines[i][0..2] == &quot;h1.&quot; puts '&lt;div class=&quot;slide&quot;&gt;' puts RedCloth.new(lines[i]).to_html while i+1 &lt; lines.length &amp;&amp; lines[i+1][0,1]=='*' slide += lines[i+1] i+=1 end puts RedCloth.new(slide).to_html slide = &quot;&quot; puts '&lt;/div&gt;' end i+=1 end end end</pre> MattK openid@morelightmorelight.com tag:refactormycode.com,2007:Code620 2008-11-25T07:04:17+00:00 2008-11-25T08:18:54+00:00 [Java] Efficiently load a text file into a sorted String Array <p>Has full &quot;finally&quot; blocks, passes findBugs check, should be speedy using TreeSet. Useful for loading data files.</p> <pre>public static String[] loadFile(final String f) { String thisLine; final SortedSet&lt;String&gt; s = new TreeSet&lt;String&gt;(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); while ((thisLine = br.readLine()) != null) s.add(thisLine.trim()); } catch (IOException ioe) { System.err.println(&quot;Error reading file &quot; + f); throw new RuntimeException(ioe); } finally { if(br!=null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return s.toArray(new String[s.size()]); }</pre> firesalamander.myopenid.com benjaminhill@gmail.com tag:refactormycode.com,2007:Code619 2008-11-22T15:50:01+00:00 2008-11-24T10:54:18+00:00 [Ruby] Cheap ruby block templating <p>Hello all. I've got the following code which I'm using in a Rails helper atm. It seems there a few ways to do this so does anyone know which is the best way?</p> <pre>def field_row(options={}, &amp;block) concat(&quot;&lt;div class=&quot;field_row&quot;&gt;&quot;, block.binding) concat(capture(&amp;block), block.binding) concat(&quot;&lt;/div&gt;&quot;, block.binding) end # called with something like... &lt;% field_row do %&gt; &lt;%= text_field blah blah blah %&gt; &lt;% end %&gt;</pre> Alistair alistairholt@gmail.com tag:refactormycode.com,2007:Code618 2008-11-22T06:16:53+00:00 2008-11-22T15:48:37+00:00 [Ruby] Bindings on caller <p>I dont really have a need for this but i was trying to figure it out and was curious this sort of thing could be accomplished with bindings.</p> <pre>def test(a, b) capitalize_args puts a # =&gt; Hello puts b # =&gt; World end test &quot;hello&quot;, &quot;world&quot;</pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code617 2008-11-22T02:27:39+00:00 2008-11-22T02:27:39+00:00 [Ruby] Initial script execution very slow and skewing results <p>Below is a little snippit of a quick response time monitor I was playing around with, works fine BUT when executed the first time everything performs really slowly and skews the duration by 3 to 4 seconds.. after that every execution works as expected.</p> <pre>def monitor(uri) Thread.new(uri) do |uri| begin start = Time.now res = open uri duration = (Time.now - start).abs puts &quot; %0.3f | %s | %s&quot; % [duration, res.status.join(' '), uri] rescue puts &quot; 0.000 | 404 Not Found | %s&quot; % [uri] end end.queue end</pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code616 2008-11-22T02:16:09+00:00 2008-11-22T02:16:09+00:00 [Ruby] suppress ERB newlines <p>Just plain-jane ERB. What does rails do differently to allow &lt;% -%&gt; and &lt;%= -%&gt; ? to get below to actually format correctly I have to place the erb tags in a gross manor.. initializing ERB with &lt;&gt; or &gt;</p> <pre> NAME: &lt;%= @name %&gt; DESCRIPTION: &lt;%= @description %&gt; SYNOPSIS: &lt;%= @syntax %&gt; &lt;% unless @examples.empty? %&gt; EXAMPLES: &lt;% @examples.each do |example| %&gt; # &lt;%= example[:description] %&gt; &lt;%= example[:command] %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% unless @options.empty? %&gt; OPTIONS: &lt;% @options.each do |option| %&gt; &lt;%= option[:args].join(', ') %&gt; &lt;% end %&gt; &lt;% end %&gt; </pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code614 2008-11-20T22:09:32+00:00 2008-11-21T05:23:39+00:00 [Ruby] Arrays, loops, strings... <p>Can this be done in one line?</p> <pre>select = [] joins = [] %w[first second third forth].each{ |semester| joins &lt;&lt; &quot;:pdp_#{semester}_semester&quot;; (1..5).each{ |n| select &lt;&lt; &quot;pdp_#{semester}_semesters.objetive_#{n} AS #{semester}_objetive_#{n}&quot; }} [select, joins].each { |x| x.join(', ') }</pre> Ceritium ceritium@gmail.com tag:refactormycode.com,2007:Code613 2008-11-20T13:42:18+00:00 2008-11-21T06:12:09+00:00 [Ruby] Similar virtual attributes and their getters/setter <p>My Publication class has a few very similar virtual attributes. Is there any way to unite their setter and getter methods?</p> <pre>class Publication &lt; ActiveRecord::Base def publisher_name self.publisher.name end def publisher_name=(name) self.publisher = Publisher.find_or_create_by_name(name.strip) unless name.blank? end def organization_name self.organization.name end def organization_name=(name) self.organization = Organization.find_or_create_by_name(name.strip) unless name.blank? end end</pre> foxdemon ermin@nomail.com tag:refactormycode.com,2007:Code612 2008-11-19T22:23:15+00:00 2008-11-20T16:22:15+00:00 [C#] Check type is XML Serializable <p>I need a fast method to check to see if a type is XML Serializable, be that with the [Serializable] attribute or the IXmlSerializable interface. This is what I came up with. Can we make it better?</p> <pre>/// &lt;summary&gt; /// Test to see if the type can be XML serialized /// &lt;/summary&gt; /// &lt;param name=&quot;objectToTest&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static bool CanBeXmlSerialized(Type objectToTest) { Type[] interfaces = objectToTest.GetInterfaces(); bool containsIXmlSerializable = interfaces.Contains(typeof(IXmlSerializable)); return containsIXmlSerializable || objectToTest.IsSerializable; }</pre> sbehnke.myopenid.com tag:refactormycode.com,2007:Code611 2008-11-19T21:53:29+00:00 2008-11-19T21:53:29+00:00 [JavaScript] Serena Collage slideshow <p>Creating a slideshow in our crappy CMS, Collage (from Serena), using a simple doctype called 'slide'. <br />Early version.</p> <pre>## View [html] &lt;div id=&quot;slideshow&quot; style=&quot;background:#FFF&quot;&gt; &lt;h2 class=&quot;slideshowTitle&quot;&gt;Around the World with Language&lt;/h2&gt; &lt;nexus:component classid=&quot;nexus/components/AssetQuery&quot; code=&quot;/System/Components/nexusComponents.jar&quot; root=&quot;$node.path/slides&quot; levelsdeep=&quot;0&quot; filter=&quot;A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate &lt;= current timestamp)) AND ((A.ExpireDate &gt;= current timestamp) OR (A.ExpireDate is null))&quot; max=&quot;1&quot; orderonmetadata=&quot;pageListPriority&quot; orderbycode=&quot;1A&quot;&gt; &lt;div id=&quot;slide0&quot; name=&quot;slide&quot; style=&quot;display:block;&quot;&gt; &lt;h3 class=&quot;slideTitle&quot;&gt;$node.contribution(&quot;title&quot;)&lt;/h3&gt; &lt;div class=&quot;slideImage&quot; width=&quot;30%&quot;&gt;$node.contribution(&quot;image&quot;)&lt;/div&gt; &lt;p class=&quot;slideCaption&quot;&gt;$node.contribution(&quot;caption&quot;)&lt;/p&gt; &lt;/div&gt; &lt;/nexus:component&gt; &lt;nexus:component classid=&quot;nexus/components/AssetQuery&quot; code=&quot;/System/Components/nexusComponents.jar&quot; root=&quot;$node.path/slides&quot; levelsdeep=&quot;0&quot; filter=&quot;A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate &lt;= current timestamp)) AND ((A.ExpireDate &gt;= current timestamp) OR (A.ExpireDate is null))&quot; skip=&quot;1&quot; orderonmetadata=&quot;pageListPriority&quot; orderbycode=&quot;1A&quot;&gt; &lt;div id=&quot;slide$node.recordnumber&quot; name=&quot;slide&quot; style=&quot;display:none;&quot;&gt; &lt;h3 class=&quot;slideTitle&quot;&gt;$node.contribution(&quot;title&quot;)&lt;/h3&gt; &lt;div class=&quot;slideImage&quot; width=&quot;30%&quot;&gt;$node.contribution(&quot;image&quot;)&lt;/div&gt; &lt;p class=&quot;slideCaption&quot;&gt;$node.contribution(&quot;caption&quot;)&lt;/p&gt; &lt;/div&gt; &lt;/nexus:component&gt; &lt;p id=&quot;controls&quot;&gt;&lt;a href=&quot;javascript:prevslide()&quot;&gt;Previous&lt;/a&gt; &lt;a href=&quot;javascript:nextslide()&quot;&gt;Next&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; ## Javascript [javascript] var slideNum = 0; var slides = new Array(); slides = document.getElementsByName(&quot;slide&quot;); function nextslide() { if (slideNum &lt; slides.length - 1) { slides[slideNum + 1].style.display = 'block'; slides[slideNum].style.display = 'none'; slideNum++; } else { slides[0].style.display = 'block'; slides[slides.length - 1].style.display = 'none'; slideNum = 0; } } function prevslide() { if (slideNum &gt; 0) { slides[slideNum - 1].style.display = 'block'; slides[slideNum].style.display = 'none'; slideNum--; } else { slides[slides.length - 1].style.display = 'block'; slides[0].style.display = 'none'; slideNum = slides.length - 1; } } </pre> tbeseda tbeseda@gmail.com tag:refactormycode.com,2007:Code610 2008-11-19T18:48:58+00:00 2008-11-21T12:17:15+00:00 [Ruby] Shortest regular expression for matching a subdomain. <p>I have written this regular expression which matches any subdomain (consisting of only letters and digits) right below example.com (including the domain, e.g. test.example.com) but not <a href="http://www.example.com" target="_blank">www.example.com</a>. It works, but it is not very elegant.</p> <pre>/(?&lt;part&gt;(w(?!ww)|w(?=www)|w(?=[a-z0-9]+ww)|ww(?=[a-z0-9]+w)|www[a-z0-9]+|[a-vx-z0-9])[a-z0-9]*)\.example\.com/</pre> troethom t.thomsen@judoo.dk tag:refactormycode.com,2007:Code609 2008-11-19T05:23:59+00:00 2008-11-19T18:11:23+00:00 [Ruby] Caching Methods <p>Is it possible to cache methods in a manor similar to below? (non-RoR). I have a few ideas of how this may work but any suggestions would be great</p> <pre> class Something def something_else &quot;Expensive operation&quot; end cache_method :something_else, :for =&gt; 2.hours end inst = Something.new # Empty cache inst.something_else # Primed cache inst.something_else</pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Code608 2008-11-19T00:45:07+00:00 2008-11-19T00:48:25+00:00 [JavaScript] Tab-Switching in jQuery <p>Is there a better way?</p> <pre>## showcase.html [HTML] &lt;div id=&quot;showcase&quot;&gt; &lt;ul class=&quot;nav&quot;&gt; &lt;li&gt;&lt;a href=&quot;#example&quot; class=&quot;selected&quot;&gt;Example&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#another&quot;&gt;Another&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class=&quot;first item&quot; id=&quot;example&quot;&gt; This is the first item. By default it's shown. &lt;/div&gt; &lt;div class=&quot;item&quot; id=&quot;another&quot;&gt; This is another item. By default it's hidden. &lt;/div&gt; &lt;/div&gt; ## showcase.css [css] #showcase .item { display: none; } #showcase .first { display: block; } ## showcase.js [javascript] $(document).ready(function() { var selected = $(&quot;#showcase .first&quot;); // First is selected by default $(&quot;#showcase .nav a&quot;).click( function() { if($(this) != selected) { $('#showcase .nav a.selected').removeClass('selected'); selected.hide(); selected = $($(this).attr('href')); selected.show(); $(this).addClass('selected'); return false; // Stops link from jumping to the anchor } }) });</pre> Aupajo pete@metanation.com tag:refactormycode.com,2007:Code607 2008-11-18T16:22:53+00:00 2008-11-21T15:33:06+00:00 [Perl] Apache log file sorting <p>I have a huge amount of log files on my hard drive and regularly download more. All of the files end up in a single directory. The log file names contain UNIX timestamps. I wrote this script to execute in a given directory and then move the found files to a new path based on the UNIX timestamp. Each new directory is named after a year and the week of the year, e.g. 200801, the first week of 2008. (Actually, the month doesn't have a leading zero yet. I just realized.)</p> <pre>#!/usr/bin/perl -w use strict; use Time::localtime; use File::Find; use File::Copy; my $vmlogpath = $ARGV[0] or die &quot;y'all didn't enter no arguments&quot;; find(\&amp;sortFile, $ARGV[0]); sub sortFile { if ( -f ) { my $filename=$_; $filename =~ /([0-9]{5,})/; my $unixtime = $1 or print &quot;Not a log file: $filename\n&quot;; my $dirname=makeDirName($unixtime); unless(-e &quot;${ARGV[0]}/${dirname}/${filename}&quot;) { my $path=makeDir($ARGV[0], $dirname); moveFile($filename, $path); print &quot;$filename is the file name.\n&quot;; print &quot;$unixtime is the extracted unixtime.\n&quot;; print &quot;$dirname is the directory name.\n&quot;; print &quot;$path is the path.\n&quot;; } } else { print &quot;Not a plain file: $_\n&quot;; } } sub moveFile { my $tehfile=$_[0]; my $tehdir=$_[1]; move($tehfile, $tehdir) or die &quot;Could not move files!\n$!&quot;; return 1; } sub makeDir { my $currentdir=$_[0]; my $newdir=$_[1]; my $newpath=&quot;${currentdir}/${newdir}&quot;; unless (-d $newpath) { mkdir($newpath,755) or die &quot;mkdir failed for $newpath: $!\n&quot; } return $newpath; } sub makeDirName { my $tehunix=$_[0]; my $day_of_year=localtime(int($tehunix))-&gt;yday; my $week_of_year=int($day_of_year / 7) + 1; my $year=1900+localtime(int($tehunix))-&gt;year; return $year . $week_of_year; }</pre> hourback hourback@gmail.com tag:refactormycode.com,2007:Code606 2008-11-18T12:33:54+00:00 2008-11-20T00:52:58+00:00 [C] How to find max, min of three numbers? <p>I tried to use as less variables and less operators as possible. <br />Please help to make the code better.</p> <pre>int max = rand(); // or any init value int min = rand(); // or any init value int tmp = rand(); // or any init value if (max &lt; min) { if (tmp &lt; min) { if (max &lt; tmp) { tmp = max; max = min; min = tmp; } else { // max &lt; min &amp;&amp; tmp &lt; min &amp;&amp; tmp &lt;= max max = min; min = tmp; } } else { // max &lt; min &amp;&amp; min &lt;= tmp min = max; max = tmp; } } else { // min &lt;= max if (tmp &lt; min) min = tmp; else // min &lt;= max &amp;&amp; min &lt;= tmp if (max &lt; tmp) max = tmp; }</pre> Tien Dung dungtn@gmail.com tag:refactormycode.com,2007:Code605 2008-11-15T08:51:14+00:00 2008-11-15T08:51:14+00:00 [Ruby] repeated code in rspec model test <p>how do i clean up this repeated code (Stock.create &amp; Stock.new) in my rspec test</p> <pre>describe Stock do it &quot;should be valid when new&quot; do stock = Stock.new(:symbol =&gt; 'GOOG') stock.should be_valid end it &quot;should be invalid when symbol is empty&quot; do stock = Stock.new(:symbol =&gt; '') stock.should_not be_valid end it &quot;should have symbol in all uppercase&quot; do stock = Stock.create(:symbol =&gt; 'GOOG') stock.symbol.should equal(stock.symbol.upcase) stock = Stock.create(:symbol =&gt; 'goog') stock.symbol.should equal(stock.symbol.upcase) end end</pre> scottmotte.myopenid.com scott@scottmotte.com tag:refactormycode.com,2007:Code603 2008-11-12T02:16:38+00:00 2008-11-12T19:17:03+00:00 [Ruby] A simple factorial program. <p>I'm quite new to Ruby, and I'm currently reading &quot;Why's (Poignant) Guide to Ruby.&quot; It's a great book. <br />Anyway, I want this to do the same thing, WITHOUT recursion, but is there a way to do it without repeating the raise statement at the beginning and using blocks instead of for?</p> <pre>def factorial( n ) if !(n.is_a? Integer) raise ArgumentError, &quot;argument must be a positive integer&quot; elsif n &lt; 0 raise ArgumentError, &quot;argument must be a positive integer&quot; end factorial = 1 for i in 1...n factorial *= i + 1 end factorial end </pre> lordzoner.myopenid.com morgan.michael@me.com tag:refactormycode.com,2007:Code602 2008-11-11T22:53:23+00:00 2008-11-12T00:33:11+00:00 [Haskell] Cat90 <p>Rotates text given in stdin 90 degrees. </p> <pre>main = do s &lt;- getContents putStr (unlines (reverse (rotate (lines s)))) rotate ls = if (maxLength ls) &gt; 0 then (column ls) : (rotate (dropColumn ls)) else [] maxLength ls = (maximum (map length ls)) column ls = map wholeHead ls dropColumn ls = map (drop 1) ls wholeHead cs = if (null cs) then ' ' else (head cs) </pre> jarkko jarkko.sakkinen@iki.fi