Star Rating Control with Clojurescript, Reagent, Facebook React JS

There are at least two Star Rating components for Facebook React that can be used with the brilliant Reagent.I found these to be too complex and neigh impossible to integrate with Reagent so I came up with a simple solution like so: (ns my-star-rating-control (:require [reagent.core :as reagent :refer [atom]]) ) (defonce star-rating-info (atom { :rating-temp 0 :rating 0 :clicked false })) (defn get-attr [x] (-> x .-target (.getAttribute "data-index...

Google Maps Weather Layer, Clouds Layer and Panoramio Layer Not Working

If you broke out your JavaScript debugger after a missing Google Maps Api weather layer, panoramio layer or cloud layer, you can close it. These layers have been deprecated and were removed on June 4th, 2015.Googling for this issue is hopeless as it leads to redirects to the main Google Maps Api Page. Disappointing search results from Google for once....

Hippo CMS and PostgreSQL - The Setup

The original instructions on the Hippo site are somewhat outdated. Moreover, the linked blog post is currently down but archive.org still has a copy:http://web.archive.org/web/20101026204317/http://gotext.org/people/bluesman/en/2009/10/english-configuring-hippo-7-for-postgresql-and-tomcat/Most of the instructions are still relevant but it's probably unnecessary to install HST 2, so the first step can be skipped.The instructions starting at “Go to _your-project-dir/cms/src/main/webapp/WEB-INF…” _...

Date Formats in Clojurescript

Formatting dates in JavaScript can be tricky, even getting the name of the month. It's possible to use the clunky $.datepicker.formatDate (); from jquery.ui, but in Clojurescript we have the Google Clojure library at our disposal. Its goog.i18n.DateTimeFormat class has a few useful functions that can be applied like so: (ns netsupply.client.calendars (:require [goog.i18n.DateTimeFormat :as dtf] )) (def format-map (let [f goog.i18n.DateTimeFormat.Format] {:FULL_DATE (.-FULL_DATE f) :FU...

Thumbs from Downloaded Images in Clojure

The code creates a thumb from either a local file or a remote URI. It combines ideas from a blog post dealing with image downoads in clojure and an older post dealing with thumbnail creation. (import javax.imageio.ImageIO) (import java.awt.image.BufferedImage) (use '[clojure.java.io :only [as-file input-stream output-stream] :as io]) (defn make-thumbnail-generic [input new-filename width] (let [img (javax.imageio.ImageIO/read input) imgtype (java.awt.image.BufferedImage/TYPE_INT_ARGB)...

Naïveté to Brilliance

Unlike Scala, even beginning learners of Clojure will experience the fun of functional programming almost immediately. Converting the Rails function “simple_format” from Ruby def simple_format(text, html_options={}, options={}) text = text ? text.to_str : '' text = text.dup if text.frozen? start_tag = tag('p', html_options, true) text.gsub!(/\r\n?/, "\n") text.gsub!(/\n\n+/, "

\n\n#{start_tag}") text.gsub!(/([^\n]\n)(?=[^\n])/, '\1
') text.insert 0, start_tag text.concat("

")...

LessCss / Less.js With --watch Option Watching Included Files

Needed a less css compiler who watches changes to a main .less file as well as all those include with an @import statement. ##One could just use an old version of the less gem that still supported the —watch option, i.e. the 1.x versions. However, the gem won't track included/imported files, the obsolete more plugin was required for this in Ruby on Rails. Peeking over the platform wall, the dotless compiler does all this well under Windows and it's very fast. However, running this app with mono ...

Debugging Scala with IntelliJ and the SBT Plugin

Here's the correct setup, including the remote build configuration:http://blog.morroni.com/2011/06/30/debugging-scala-projects-in-intellij/comment-page-1/You may have to restart the IDE to get the debugger to stop when running from the SBT console. Yes, you can actually run your tests on the SBT console that comes with the SBT plugin for IntelliJ (test-only etc.), set breakpoints on your test code, and the debugger will open when it hits the break points. This is really cool....

Rails Migration to Convert all Table Names and Column Names to underscore

This may be useful for legacy database, whose table and column names are in CamelCase. Use with extreme caution: {:tag :br, :attrs nil, :content []}class ChangeAllColumnsToUnderscore < ActiveRecord::Migration include ActiveRecord::ConnectionAdapters::SchemaStatements require 'active_record/connection_adapters/abstract_adapter' #not needed in Rails 3 #pilfered from here: #http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-column_exists-3F ...

Gitosis Installation on OpenSuse

The repo info is here (click and expand that page's silly javascript widgets), so for OpenSuse 11.4 (use sudo for all commands that need it): zypper addrepo http://download.opensuse.org/repositories/home:elvigia/openSUSE_11.4/home:elvigia.repo zypper refresh zypper install gitosis Then continue as outlined here, slightly adjusted for OpenSuse with user creation: Then just proceed with `git clone git@YOUR_SERVER_HOSTNAME:gitosis-admin.git` `on your local machine etc. etc.` #Henrik: Hi, all sou...

Install RubyGems Legacy Versions

To install a legacy version of RubyGems, you will need some version installed first, so use aptitude, yum, zypper etc: apt-get install rubygems Then revert to an older version (for example 1.3.6): gem install rubygems-update -v=1.3.6 update_rubygems Check your version with gem env...

PostgreSQL - Add a Column to All Tables in the Database Unless it Exists

To be able to use NHibernate – and as a general purpose and learning exercise – I wanted to write a script that adds a version column of type integer to all tables in the database, unless such column exists (in Rails the schema_migrations table has a version column for example). In SQL Server we have the “secret” sproc sp_MSforeachtable for this purpose, but how to bend the stricter syntax of plpgslq to achieve something similar? After a number of hours of trial and error, here's is a script tha...

Enabling gzip Compression with SOAP4R

It's a one-liner, but info isn't easy to find (as usual with soap4r).When you generate your local driver with for example wsdl2ruby.rb --wsdl MyService.wsdl --classdef MyService --type client --force and you instantiate your proxy driver like so ms = MyService.new ms.wiredump_dev = STDERR you simply add ms.streamhandler.accept_encoding_gzip = true That's all. No need for custom headers etc.And: zlib (compression library used by soap4r) is built into Ruby since version 1.8. No need for any g...

Prepend to javascript_include_tag :defaults

Yes, there is register_javascript_include_default but it will only** append** to your sources.To prepend (I’ll use this to have the excellent JS.Class libraries loaded before anything else), proceed like so:While in Rails 3, you can set in your application.rb file,in Rails 2.3.x you create an initializer (e.g. config/initializers/my_js_defaults.rb) and reset the JAVASCRIPT_DEFAULT_SOURCES constant as so: module ActionView::Helpers::AssetTagHelper JAVASCRIPT_DEFAULT_SOURCES = (remove_const :J...

Admin Plugin for Your Rails App - admin_data FTW

After installing, trying and discarding typus, casein as well as ActiveScaffold, I ended up with one of the best plugins I've seen, and certainly the best for utterly effortless admin panel setup, admin_data.It is super-quick to install (Rails 3 is the gem, Rails 2 is a plugin branch, no digging through trees on github), unintrusive (all code is in vendor/admin_data where it belongs), requires no set-up, correctly (!) gets all model information from your model definitions (primary_key,...

Testing AuthLogic with RSpec and Mock Helpers

Note: This all concerns Rails 2.3.x and recent versions of AuthLogicTesting AuthLogic with RSpec is still a puzzle with several parts that can be difficult to fit together. Very helpful is a sample project on github that demonstrates several testing options with RSpec.A series of mock helper methods that you can stuff in your spec_helper.rb can ease testing, letting you call login or current_user anywhere in your specs.If you get errors such as Mock "UserSession_1002" received unexpected mes...

Install Gems Remotely When Using Git and Gitosis

To host your private gems you have several options. The cheapest and most scalable solution will likely be to run your own gitosis server. Then you build your gems as described in this railscast and push them up to your gitosis repo. But how to deploy and install these gems when the gem is updated?Installing a gem from Git involves four steps: Clone the Git repository. Change to the new directory. Build the gem. Install the gem. #One way is to implement a Git post-receive hook. This hoo...

Apache SSL Library Error 218529960

If your Apache2 server fails to start after installing SSL (recommended guides are here and here), and get an error in your logs (probably at /var/log/apache2/error.log on Ubuntu) such as SSL Library Error: 218529960 error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag SSL Library Error: 218595386 error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error be sure you have the correct "tags" in your certificate file: It should start with (if PEM-encoded) -----BEGIN CERT...

SQL Server with FreeTDS Unicode Data Error

Update (Aug. 28, 2011): You may want to check out tiny_tds which obviates many of the below settings and gives you a richer and more scalable connection than ODBC. If you get Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. when connecting to SQL Server from Linux via FreeTDS, you don't set the FreeTDS version correctly. To use SQL Server from Rails, I usually just create shared DSNs in /etc/odbc.ini...

Full Trace with RSpec

Just a reminder: To get a the full backtrace when running RSpec, either use the -b option, script/spec -b /path/to/spec.rb or add --backtrace to your spec.opts. Here are the other options for either the opts file or the command line....

Netbeans Legacy Versions, Old Versions, Build and Release Archive

Just for the record, as this can be hard go google. If you need old and legacy versions of Netbeans, you can find them through this page:http://www.netbeans.info/downloads/dev.phpBesides all releases, it also gets you to all build types including nightly, daily, milestone etc., acting as a way-back machine for Netbeans developers and users....

Quickstart with YQL and HTTParty with Rails

YQL makes it super-easy to consume data in your web app through a unified SQL-like API. And HTTParty by John Nunemakers makes HTTP really easy. A perfect match.In environment.rb: config.gem 'httparty' Now, just create a model. Be sure to use the public endpoint for now, as the others need oauth authentication. class News include HTTParty base_uri 'http://query.yahooapis.com/v1/public/yql' def self.new_york_news self.get("", :query => {:q => 'select title, abstract, url from search.news where ...

Convert between XML, Hash, YAML, JSON in Ruby - Conversion Cheat Sheet

Here's a little XML/JSON/YAML/Hashconversioncheat sheet for Ruby: First, let's create an XML document: {:tag :br, :attrs nil, :content []}require 'rubygems' require 'nokogiri' builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.products { xml.widget { xml.id_ "10" xml.name "Awesome widget" } } } ...

Clearing Memcached at Capistrano Deployment

It’s a two step process: Create a rake task (in lib/tasks/clear_memcached.rake for example): {:tag :br, :attrs nil, :content []}namespace :cache do desc 'Clear memcache' task :clear => :environment do ActionController::Base.cache_store.clear end end In deploy.rb add the following: namespace :cache do desc "Clear memcach after deployment" task :clear, :roles => :app do run "cd #{current_release} && rake cache:clear RAILS_ENV=production" end end and (depending on your task chain...

CSS Specificity Algorithm Table from Evan Sharp's Mix 2010 talk

Having watched Evan Sharp’s “Comp to Code” talk at Mix 2010 video (check out the other Mix videos also, most are excellent), searching the web for the CSS specificity algorithm table turned up nothing as simple as his pseudo-decimal algorithm. So I reproduced the table from the talk verbatim here for reference. As you can see, id selector elements will dramatically increase the specificity of the selector, while class selector elements are an order of magitude less specific:CSS specificity algor...

Thailand 2010, Moving Forward?

A great overview of the current political situation in Thailand and its roots, from long term on-the-ground experience in Thailand and conversations with Thais from all walks of life, which I think is essential. I agree on most counts, especially the view of Abhisit and his (in)ability to bring about reconciliation, and I also hope for a good outcome over the next few years. However, I’m slightly more sceptical that the outcome can be peaceful....

odd number of arguments for Hash (ActionView::TemplateError)

This error can be caused by an outdated version of the globalize2 plugin, so try script/plugin remove globalize2 and script/plugin install git://github.com/joshmh/globalize2.git Hope it helps.#Nico: Thanks for This! Saved me quite some debugging...Matte: Thanks! you saved me!...

RSpec and Webrat for Rails Integration Testing

Getting RSpec and Webrat to cooperate has gotten a bit easier recently, so make sure you have all the latest versions of the webrat, rspec and rspec-rails gems installed. Some quirks remain which might trip you up coming from TestUnit. For example if you cd spec/integration and spec ./user_integration_spec.rb or ruby ./user_integration_spec.rb you might get undefined method `visit (?) while a similar procedure would run fine in test/integration with TestUnitBut with RSpec, when you run spec ...

Using routing_filter with Devise

Having used Sven Fuchs' routing_filter to localize routes (see here for alternative solutions), I now moved my authentication to devise from authlogic. This broke my localized routes with the default configuration, so for example http://localhost:3000/**en**/users/sign_in failed with an ActionController::UnknownAction error.Fixing it was super-easy, simply open your config/initializers/devise.rb file and uncomment (currently line 81) config.use_default_scope = true and it should work like bef...

Using rails-footnotes with vim/gVim

Update March 7, 2011: The rails-footnotes gem/plugin as of version 3.6.7 finally works with Rails 3 and Rails > 2.3.6, meaning the project has been revived in a great way. One less reason for shirking the upgrade to Rails 3 and newer versions of rails 2.3.Few gems or plugins speed up Rails development like rails-footnotes by José Valim and others. Especially useful is its ability to open files directly in the a text editor from Firefox. Out of the box, this gem works with Textmate, but it's qui...

Fixing FuzzyFileFinder::TooManyEntries

If you get FuzzyFileFinder::TooManyEntries edit your ~/.vim/plugin/fuzzyfinder_textmate.vim file and set the following line to a higher value, for example 50000 let g:fuzzy_ceiling = 10000...

gh-pages -> gh-pages (non-fast forward) when creating github project page

If you get ! [rejected] gh-pages -> gh-pages (non-fast forward) when following the instructions to create a github project page, you might just try to delete the gh-pages branch git push origin :gh-pages and then push the gh-pages branch again git push origin gh-pages Hope it helps.#Emaad Manzoor: Thanks for this! Really needed it....

So the most popular search term starting with "delete" seems to be "delete facebook account". In the face of recent changes to "fan" and profile settings that "deepen the marketing graph", it could become even more popular. Wonder what all the buzz is about......

Learning Javascript with Crockford and Spidermonkey

As JavaScript is the language I'm planning to learn more in-depth this year, primarily to approach the latest map-reduce API's of the latests NoSQL databases (CouchDB, riak etc.), I've recently made good progress thanks to two invaluable resources:#First, Douglas Crockford's lecture videos at the YUI theater. He has created three separate series, The JavaScript Programming language, Advanced JavaScript. and more recently, Crockford on JavaScript, all available on the same page in the YUI theater...

ruby-debug with Ruby 1.9.x and Rails 3 on RVM

Things are moving fast in the Rails/Ruby world with the imminent releases of Ruby 1.9.2 and Rails 3.An essential tool for a smooth transition is RVM by Wayne Seguin (Where can i vote for this guy as Ruby Hero? Ah, it's here.) In the first Rails 3 Railscast RVM sounds more like an afterthought and only necessary if you don't have Ruby 1.8.7+ installed, but it's advisable to not even try the migration to Rails 3 without installing RVM and a dedicated version of Ruby (can be the same version as you...

Convert CHM to PDF on Linux (Ubuntu)

The Google search led me down the wrong path, so here is the gist of it:Install chm2pdf, which is in the repositories starting with Ubuntu 8.04 sudo apt-get install chm2pdf Get help with chm2pdf --help Convert with for example (all three “dashes” are double dashes half eaten by Wordpress): chm2pdf --continuous --no-links --quiet input_file.chm The input file name should not contain any special characters or spaces, otherwise you might get all kinds of "File not found" errors, regarding for ex...

Smoothgallery-like Slideshow Script with Text Overlay and jQuery

Impressed by fellow Chiang Mai expat's site gt-rider.com I was looking for an gallery/slideshow javascript similar to JonDesign's SmoothGallery (jdgallery), but working with jQuery rather than mootols. jdgallery combines slideshow, image title overlay and many different transitions in an aesthetically appealing package. The search led me to the conclusion that the transitions (slideshow functionality) should be handled by a different script than the actual image display. For the former there is ...

Folder org already exists/Too many open files with Netbeans

The messages "Folder org already exists in ..." and "Too many open files" when using Netbeans are likely related. The underlying error might be that Linux runs out of file descriptors, which can happen rather quickly when you open many projects at once. Here's the solution.The file descriptors can be set at the system level and at the shell level:Check how many your system allows: cat /proc/sys/fs/file-max This value can be set to a high number, probably to several 100k without major issues. For...

Editing less (less css) with Netbeans IDE

Just a little tip, as the syntax of less (less css) is so similar to css, just add a new file type in Netbeans > Tools > Options > Miscellaneous > Files like so: ![](/wordpress/wp-content/uploads/2009/11/netbeans-less.png) Update: I found less editing works a lot better with Netbeans 6.5.1 than with 6.8. The code formatting of 6.8 is too picky and will essentially not format less as it's not proper css. No such problems with Netbeans 6.5.1 which I also use on Windows as a vastly superior less an...

Globalizing the Current URL in a Rails View

Rails I18n, globalize2 and Sven Fuchs’ routing_filter provide a nigh complete globalization solution for Rails, especially after the splendid new localized view support in Rails 2.3.So I was looking for a way to display small flags found at famfamfam and link them to the “localized” versions of the current uri in all pages of the application, so that for example/widget/8/editwould become/de/widget/8/editand /would become/de/Having said routing_filter installed, I created this little helper metho...

Multi-Level Nested Object Forms in Rails (with jQuery)

Complex forms were the focus of Railscasts 73, 74 and 75 and the latter episode outlined the rather involved way to get a single nested model to work correctly with form elements generated on the client via javascript. Nested model forms built into Rails became the most requested feature and release 2.3 finally delivered with the** accepts_nested_attributes_for function**. Still, challenges remained, especially when trying to generate form elements on the client. A suggested solution was an alte...

Adjust Screen Brightness in Ubuntu via xrandr

Certain issues with screen brightness adjustment in Ubuntu for a variety Intel graphics chips (945GM, GL40) which will be fixed in the upcoming Ubuntu Karmic. For now, if you have problems getting your screen brightness adjusted via fn keys (I had this issue on a new Acer notebook), you might try this command: xrandr --output LVDS --set BACKLIGHT_CONTROL combination The screen will flicker when you run this but your function keys might just start working. You might add this command to your start...

Rails Auto Complete with jQuery/jRails

Having long used jRails in place of of scriptaculous/prototype with my Rails projects, I found that the latter won’t work with the original auto_complete plugin for Rails. So I tried a few solutions such as this which uses the auto_complete_jquery plugin, as well as more involved solutions such as this and this one which uses HAML. However, I didn’t want to write javascript and also have all the helpers of the original plugin, to implement the solution presented in Railscast 102, with a RESTful ...

Low-Pain Drop-Down Navigation Menu for YAML

Having recently dug into css-frameworks, I’ve found Dirk Jesse’s YAML to be in a league of its own. While I think that support for IE5.5 could be dropped, YAML makes many right choices regarding abstraction and accommodating browser quirks.And while YAML has two basic navigation bars out of the box (named sliding-door and shiny-buttons), I wanted a drop down menu on hover over the navigation items, with as much CSS and as little JavaScript as possible.After some searching I found the Drop-Down-M...

White Noise Generator for Linux

Noise of different colors can be generated on a Linux box with these commands (Ubuntu, Debian etc.): sudo apt-get install soxplay -n synth 60:00 whitenoise The latter command will generate white noise for 60 minutes. Also works with brown and pink.#Mikaela Mendoza: White noise machine are clinically proven solutions for looking for effective sleep aids.dmitry: Awesome! I just looking for brownnoise. Thanks you very much.GratefulMan: Thanks! This is certainly less resource intensive than flashpla...

Convert Quicktime Mov to Avi on Linux (and Windows)

The basic task is to create a frontend for the encoding titans ffmpeg and mencoder and on Windows there’s the (otherwise) super Super. If if already arrived on Linux you should check out WinFF by Matt Weatherford (Big Matt). Easy-to-use, fast and effiecient describe this neat little program....

Custom Primary Key and Mass Assignment

Say you have an ActiveRecord model with a custom primary key and no field named “id”, a common occurrence when working with legacy data: hotel.rbclass Hotel < ActiveRecord::Base set_primary_key :hotel_id(…) Now you have the pertinent form <% form_for(@hotel) do |f| %> <%= f.error_messages %> <%= f.label 'Hotel ID' %>: <%= f.text_field :hotel_id %> <%= f.label 'Name' %>: <%= f.text_field :name %> <%= f.label 'Destination ID' %>: <%= f.text_field :destination_id %> <%= f.submit 'Save' %> <% ...

pack-objects died with strange error when running git push

If you get errors such as fatal: Out of memory, malloc failederror: pack-objects died with strange errorerror: failed to push some refs to ‘git@myserver.com:foo.git’ when running git push first, upgrade git to the latest version on both ends, then check if git repack still works. If not, you might have a local issue.If repack still works, your remote server (the server you push to) might actually run out of memory, which can easily happen with for example smallish VPS slices. So, just increas...

Forwarding Multiple Messages with Thunderbird - And Not as Attachments

Mozilla Thunderbird does not have a built-in option to right-click and forward multiple messages without sending them as attachments of a single message or sending each message inline after entering the address manually. While this makes sense as it minimizes server resources and web traffic, sometimes it is more convenient for sender to send (bounce) multiple messages to the same recipient in one action, giving the reader single messages in her inbox. Luckily there’s the Mail Redirect Add-on th...

Sorted and Translated ActiveRecord Model with Globalize2 and Ruby Magic

This code returns all records of your model sorted by translated field name when using Globalize2 : app/models/widget.rb def self.all_sorted Widget.find(:all, :joins => :globalize_translations, :conditions => ['locale = ?', I18n.locale]).sort_by(&:name) end As outlined it this post, :joins => :globalize_translations is mandatory. The unary ampersand operator converts a Proc to a block, so in this case sort_by(&:name) is “shorthand” for sort {|x,y| x.name <=> y.name} Ruby sometimes feels li...

no such file to load -- readline (LoadError) when running script/console

If you get Loading development environment (Rails 2.3.2)/usr/local/lib/ruby/1.8/irb/completion.rb:10:in require': no such file to load -- readline (LoadError) from /usr/local/lib/ruby/1.8/irb/completion.rb:10 from /usr/local/lib/ruby/1.8/irb/init.rb:252:inrequire' from /usr/local/lib/ruby/1.8/irb/init.rb:252:in load_modules' from /usr/local/lib/ruby/1.8/irb/init.rb:250:ineach' from /usr/local/lib/ruby/1.8/irb/init.rb:250:in load_modules' from /usr/local/l...

routing-filter plugin Issue with Rails 2.3.2

If you get => Booting WEBrick=> Rails 2.3.2 application starting on http://0.0.0.0:3002/usr/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/action_controller/routing/route_set.rb:142:in named_helper_module_eval': (eval):28:innamed_helper_module_eval': compile error (SyntaxError)(eval):28: syntax error, unexpected kEND, expecting $end end ^ from /usr/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/action_controller/routing/route_set.rb:175:in `define_url_helper'(…) after upgrading to Rails 2.3.2, the cu...

IIS7 Certificate Renewal Process Generates Invalid CSR

When using the Renew Option in IIS Manager>Server Certificates, a longish CSR (Certificate Signing Request) is created but when submitting it to your certificate authority it is rejected, as the CSR is invalid. Godaddy might give you a message like "Unable to extract CSR information", so you this tool to check your CSR and the invalid parts are underlined in red. It seems IIS7 tries to generate a key with a length of 4096 bits even when renewing a 1024 bit certificate. This issue is likely a bug...

libpq.so.4: cannot open shared object file

Ok, last hurdle (I hope) for the CentOS migration:If you get Starting httpd: /usr/sbin/httpd: error while loading shared libraries: libpq.so.4: cannot open shared object file: No such file or directory starting Apache2 on CentOS, possibly after having installed later versions of Postgresql and forcing some compat-postgresql-libs, you might proceed like this: yum remove apr-util (this will remove httpd / Apache2 also)then: yum install httpd (this will reinstall apr-util and [hopefully] fix the de...

Selecting and Submitting the Entire List Item

Note: this article uses jQuery, Ruby on Rails and CSS. It might be useful for other combinations.You have a list of products and don’t want to force users to search for the link to the details page. Rather, give him some hover effect for each list item and let him click anywhere on the item. The list here is displayed as an unordered list (UL), but a similar technique should work with table rows (TR), divs or other block elements.Several techniques are applied here:Step 1: Turn the cursor into a...

Override number_to_currency in Rails

This article explains the approach but I had problems getting the implementation to work (can't convert BigDecimal into String errors). So here’s my solutions:Create a file in #{RAILS_ROOT}/config/initializers, which you can name anything you want, for example my_currency_helpers.rbPaste this code: module ActionView module Helpers module NumberHelper def number_to_currency_with_euro(number, options = {}) defaults = { :unit => ‘€’, #obvious :precision => 2, #digits after separator :separat...

Accessing Routes in script/console

In script console the app object exposes ActionController::Integration::Session which contains all your routes, so you can go: app.widgets_path etc. No need (comment) to include ActionController::UrlWriterBut to use your routes in the model, you wouldn’t use an instance of ActionController::Integration::Session, no, don’t, it’s a terrible hack, dirty and immoral, bordering on evil, MVC abused and perverted. Then again, you never know…...

rails-i18n translation missing errors in production

Here’s the solution:In environment.rb, put this I18n.load_path = Dir.glob("#{RAILS_ROOT}/locales/**/*.{rb,yml}")I18n.default_locale = 'en'I18n.reload! This was the only place I could get the I18n.reload! command to help with this issue....

Paginate over HABTM with Globalize2

As outlined in this post, find and paginate require a :joins => :globalize_translations statement to eager load the translations.Here’s an extended version for pagination over a has-and-belongs-to-many (HABTM) relationship: app/models/widget.rbhas_and_belongs_to_many :categories…def self.find_by_category(category_id, page) paginate( :page => page, :per_page => 30, #:include => :categories, #does not work but this does: ** :joins => [:categories, :globalize_translations],** :conditions => ['categ...

Netbeans Regular Expressions Find and Replace

Powerful find and replace with regular expressions should be the hallmark of every IDE worth its mettle. MS Visual Studio does it so-so, but lo and behold, Netbeans (at least in version 6.1) is even worse.So I wanted to put foo at the beginning of every line in a text, which calls for a regex like: ^.* and replace like: foo $0 However, Netbeans only ever replaces the first match in a text, over and over again. It also hangs up easily in the process.As with many a Netbeans quirk, it’s Quanta Plus...

HTML List Items in Two or More Columns without and with Rails

Table avoidance is raging on in contemporary HTML design and nobody wan’t to be caught with an unnecessary table on their pages. This may go to far or not, but to display data in multiple columns without resorting to a table you can proceed like this: 1 2 3 4 5 6 Then make the ul 100% wide and the list items (li) 50% or 33% or 25% or whatever and float them left (fixed values in pixels or ems work as well): .lst {width:100%} .lst li {width:25%;float:left;} Here’s the result: 1 2 ...

Populate an ActiveRecord Model with Images Using attachment_fu

Is there anything more painful than manually populating your model with sample data? The thought alone makes most developers’ skin scrawl because we write code to do the work for us and abhor manually entering fugacious data.As always, first things first, watch the relevant Railscast, which will introduce you to populator and faker, both great tools you will soon find indispensable. And here’s a little rake task to populate your model with images, useful to see how it looks with product thumbnai...

Scroll Wheel Function for the Marble Mouse on Linux

Update: Since Ubuntu 8.10 "Intrepid Ibex" Hal has superseded xserver/xorg.conf as the preferred means to configure input devices. This post has the settings for hal, and they work just like the old xorg.settings outlined in the original post. Migration to hal will likely bring benefits for most, such as plug-and-play hot plugging. You might want to check out this writeup before taking the plunge.Original post (applies to xserver/xorg.conf < Ubuntu 8.10):As you know I consider the Logitech Marble...

The Art of Rails - Review of the Best Rails Book

I read this book a couple of months ago but wanted to get a review out before year end. Why this book review, the first on this blog? Because I find The Art of Rails to be the best book on Rails for developers moving from a beginner to a more advanced level, and I want to wholeheartedly recommend it.Once you’re done with the “big two” (Agile Dev with Rails and The Rails Way) you will have nice first set of “hows” (The Rails Way is supposed to to be used as a developer’s reference book). But you’...

Understanding class << self

Excerpted from:http://whytheluckystiff.net/articles/seeingMetaclassesClearly.htmlDisclaimer: Enjoy with a huge grain of chunky bacon...Objects (instances of classes) DO NOT STORE methods, objects only store VARIABLES, instance variables.METHODS are stored IN THE CLASS. In this sense "a class is an object" is not quite true, objects (instances) and classes (the method store) are DIFFERENT! However, to the PROGRAMMER a class is an object after all, because he can store variables in a class. Duh.Wh...

Rails i18n with Routed Locales

Localizing and globalizing Rails apps has gotten much easier with version 2.2. Add model translations with Globalize2 and you’re on your way. But where to store the locale? The session is a big no no, so it would be more elegant to just prepend them to the path and adjust the routes accordingly:/widgets//en/widgets//de/widgets/Rails routing is arcane and difficult, so hacking away at it is like stumbling into a mine field. Especially difficult is the preservation of url_helpers, so Sven Fuchs de...

'GIMP XCF image plug-In could not open image' with Images Saved in Inkscape

With Gimp for raster graphics and Inkcape for vector drawings, Linux is a graphics platform whose speed, stability and functionality and last but not least lack of clutter will suprise even jaded Photoshop and Illustrator users. However, there were until recently a few quirks in the data exchange between the two applications. Inkscape can export to the Gimp default file format XCF since version 0.44, but the saved files could throw the GIMP XCF image plug-In could not open imageerror upon openin...

rm * Argument list too long

To delete all files in the current directory, you run the extremely dangerous **rm * **and **rm -rf ***to recursively remove all files and directories.However, the command has a 128K buffer limitation in the Linux Kernel. As a workaround you can pipe each file to rm like so: **find . -name '*' | xargs rm** See this article for details....

All Fall Down - Including the Bucket of Formulas

As the Economist’s Buttonwood points out, when everyone heads for the exit, all get squeezed. This defeats all hedging strategies. The late eighties and nineties brought us the end of a formulaic approach to politics (Socialism vs. Capitalism); the current decade follows up with the end of a formulaic approach to investing (Long vs. Short, Stocks vs. Bonds etc.). A brilliant comment by Hyun-U Sohn sums it up: The article betrays the view of correlations and other statistics as describing laws of...

Change the Netbeans Windows Layout

In Netbeans there currently (Version 6.1) is no built-in option to save a windows layout, you can only do a “Reset Windows” (in the Window menu) to get back to the factory layout.I’ve been looking for a solution to get a cough Visual Studio cough like layout (all navigation on the right of the code window) and found a great plugin called Perspective (click this link twice as for some reason on the first click it will give you the plugin home page) that lets you save a layout and switch easily be...

ArgumentError: wrong number of arguments (3 for 2) with Better Nested Set Plugin

If you’re using the Better Nested Set plugin in your 2.1 Rails app and get an error such as ArgumentError: wrong number of arguments (3 for 2) from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:2479:in `attributes_with_quotes' upon saving your model or upon calling update_attributes, you have two options: Move to Awesome Nested Set, a drop-in replacement for BNS which has some additional features, among them STI (Single Table Inheritance). Apply this patch develo...

Dual-Screen on Ubuntu with Intel 945GM Chipset

You’ve surely read this article on the topic, which describes a long (and arduous) process to set up dual monitors on an Ubuntu system with a lowly graphics chip such as the Intel 945GM. However, there is a much easier option which is outlined here: For my system, all I had to was add the bold line in /etc/X11/xorg.conf Section "Screen" Identifier "Default Screen" Device "Intel Corporation Mobile 945GM/GMS, 943/940GML Express Integrated Graphics Controller" Monitor "Generic...

Thai-English Dictionary for Linux

The old post has become obsolete and I removed it. Today it's a bit more straightforward and easier to get a English-Thai-English dictionary installed on Linux (and Windows). The original Nectec portal (registration is now required) referenced in the old post is here: http://lexitron.nectec.or.th/2009_1/index_en.php?q=common_manager/download However, it's probably best to install StarDict from a repo manager for your system. Then download the dictionary files from NecTec, unzip and put them int...

Combining TOP and GROUP BY with SQL Server 2005

It's an every day task: Select the ten top-selling widgets from each category. The obvious approach is to combine TOP and GROUP BY, which usually comes with some annoying "Column 'xxx' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" errors you try to work around. The culprit is a misunderstanding of the GROUP BY clause. It will NOT give you multiple result sets, but rather ONE result set with a single row for each group. From Book...

Mount a Shared Windows Drive in Ubuntu Linux to Use Open Office

Accessing files located on a Windows Active Directory network share from your Linux machine is easy via Samba (and probably NFS, which I've never tried). However, trying to use Open Office applications such as Writer or Calc to open these files will likely fail. OO apps will start up and then die silently. That's why it's usually necessary to mount the shared drive with a command such as this: sudo mkdir /media/mynetworkserverc sudo mount -t cifs //mynetworkserver/c /media/mynetworkserverc -o us...

Failed to get lock on destination repos

This error indicates that svnsync failed to release locks upon exit. You can release the locks with the command: svn propdel svn:sync-lock --revprop -r 0 svn://targetrepository...

Enable IIS7 to Serve Bittorrents (.torrent Files)

It's hard to google for this info as most results will be torrents of some kind, but the solution is obvious: Simply add a mime type (application/x-bittorrent) for torrent files (.torrent):That's it. Hope it helps....

Moving Active Directory Log and Database Files

The entire relocation process is described in this TechNet article: http://207.46.196.114/WindowsServer/en/library/af6646aa-2360-46e4-81ca-d51707bf01eb1033.mspx?mfr=true, the core for moving to local drives: http://207.46.196.114/WindowsServer/en/library/af6646aa-2360-46e4-81ca-d51707bf01eb1033.mspx?mfr=true and for network drives: http://technet2.microsoft.com/WindowsServer/en/library/dd498633-5d65-4a14-b68d-edcb85fada651033.mspxOnce you have completed the preparation of your target volumes and...

Ampersand & the Request URL in IIS7

Update: The below “solution” should not be considered as it creates invalid URLs. All ampersands should be encoded as "%26", see Bill's comments from Nov. 11, 2010. This was just meant as a quick-fix-short-term-workaround as these URLs were supported in IIS 6. There's a reason why IIS 7 and above don't support them.With the arrival of ASP.NET MVC and the complementary IIS7 file-extension-less request pipeline it's finally possible to turn ugly "classic ASP.NET" query string URLs into pretty and ...

Windows Live Writer for Windows Server and Windows XP Professional x64 Edition

I've posted about this nonsensical issue before. As the source link quoted in that post is now dead and the issue continues with the latest version of WLinstaller.exe, here's the msi source for direct download. It installs fine on Windows Server 2008 (x64) and Windows Server 2003 (32 bit x86). Not sure if it installs on XP Professional x64 as I haven't tried it, it should though.And while we're at it, here are the other files (msi sources):Windows Live Mail for Windows Server and Windows XP Prof...

IIS 7.0 FastCGI PHP 5 MySQL

Once you've followed these instructions to install PHP hosted on IIS7 using FastCGI (there's also a video by Scott Hanselman), you'll probably want to install MySQL and make it work with PHP. However, with your php.ini in its current state you'll likely get an error message when you start a MySQL-based app, such as Wordpress:Your PHP installation appears to be missing the MySQL which is required for WordPress.There's a lot of information out there to fix this on Windows, and much advice involves...

Best Pointing Device - My Vote Goes to the Marble Mouse

Something wasn't right. Over the past few years computer mice had been getting better and better in terms of tech: Laser replaced optical replaced the mechanical ball, resolution went from a few hundred dpi to a few thousand, and wireless options are getting faster (Bluetooth) and more reliable at ever larger distances from the machine. Still, I found all the gadgets and mice I tried ended up in the drawer sooner rather than later, making me go back to the notebook's built-in touchpad that some ...

Identify which w3wp.exe belongs to which Application Pool in IIS7

If Windows Task manager shows excessive resource usage (CPU or memory, mostly) for an IIS 7 worker process (w3wp.exe), it's helpful to identify which of your application pools consumes the resources. I haven't found a way to accomplish this in IIS Manager so I proceeded like so: At the command prompt: net start WAS Note: WAS is the Windows Process Activation Service (btw, pretty silly service name, as it's nigh impossible to google for WAS). Run appcmd list wp: **C:\Windows\system32>%windir%/sys...

Serving HD View Content with IIS 7

With the default configuration of IIS 7 you will not be able to serve the .wdp images requested by the HD View plugin in the clients browser. The user will get the "Could not create scene from file http://{your source path}/l_{l}/c_{c}/tile_{r}.wdp>. hr=0x..." error message displayed instead of the HD View. As found in this discussion, it's necessary to enable the image/vnd.ms-photo MIME type on the web server, which on IIS 7 is in done IIS Manager >> MIME Types:Simply add a MIME Type for wdp an...

Wildcard Host Header Binding And Subdomains with IIS7

Like its predecessors, IIS7 does not support wildcard (catch-all) binding or wildcards for host names, see this discussion for the state of things and how the much requested feature didn't make it into the II7 release version as it stands. So, if you try to add *.yourdomain.com as a host name in IIS 7 you will get this warning:There is only one "workaround" at the web server level and it requires a dedicated IP address for the particular site: Set up a wildcard host record in DNS: right-click th...

Capitalize with C and ASP.NET

It may be surprising for some, but the .NET framework has capitalization built in:**using System.Globalization;class Test{public static void Main (){string s =CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("i want this capitalized or capitalised if possible.");Console.WriteLine (s);}}**It's even easier with VB.NET:StrConv(yourTextvalue, VbStrConv.ProperCase)Still not as elegant as capitalize(str) in Rails ActiveSupport, but the approach via globalize might be more maintainable in the long run....

The value for the property

You might also get a related error when building your ASP.NET project with a Linq to SQL class:Build failed due to validation errors in myfile.dbml. Open the file and resolve the issues in the Error List, then try rebuilding the project.This issue can be resolved by **removing all dots **from the connection string key in web.config, see here, so becomes ** ** ** ** Then the build should suc...

Gigapixel Multi-Row Panoramas Made Easy with Monopod Technique

Microsoft's HD View caused quite a stir last year, and rightly so. The MS Research team solved several issues that have hampered the wider adoption of panoramic imagery in a single and mature offering. The wide angle projection issues of QuickTime VR and other viewers were solved with an ingenious adaptive projection algorithm. Also, tone mapping correction (haze reduction) was introduced to deliver a truly immersive experience that invites exploration of gigapixel images and is also great for w...

C compiler cannot create executables

I ran ./configure to install Postgresql-8.3.0 on Linux Mint 4.0 (Daryna)/Ubuntu Gutsy Gibbon and got the errorchecking for C compiler default output file name... configure: error: C compiler cannot create executablesTo fix it simply do anapt-get install build-essentialas recommended here or, as minimal fix:apt-get install libc6-devas recommended here (in the comments).Btw., this is my first post using flock as a blog editor on Linux. It's not Windows Live Writer but it works fine....

Generating CHM Documentation for RSpec on Rails

RSpec is the king of the BDD hill when it comes to Rails, and the learning curve is quite steep. For Windows developers hooked on CHM documentation, it's very easy to generate RSpec CHM files by running the commandrdoc -f chm -o chm_folder rspec*in the /vendor/pluginsdirectory of your RoR project where you have installed the RSpec and RSpec on Rails plugins using ruby script/plugin install http://rspec.rubyforge.org/svn/tags/CURRENT/rspec ruby script/plugin install http://rspec.rubyforge.org/svn...

The Dark Side Revisited - Darkish Color Themes for Visual Studio

Developers have been experimenting with darker color schemes for Visual Studio, aiming to port their beloved Textmate or Vim environment to other IDEs including VS. The Textmate Vibrant Ink theme was ported for Visual Studio and recently improved. Zenburn was ported from Vim to Visual Studio. Collections of other dark color themes can be found here, here, and here. Some like them, some don't. I was in the latter group until recently. That was when I came across the Aloha scheme for Netbeans 6, w...

Generate Ruby on Rails CHM Documentation

Update April 21, 2008: Delynn Berry now has a new CHM file up for Rails version 2.0.2 with a much better index and fewer broken links than what I was able to create. Get it ****here_****._CHM (compiled HTML Help) is arguably one of the better Microsoft inventions and generating these files from Ruby on Rails documentation is should be easy using Rdoc.A general article on the different ways of generating Rails offline documentation is here. The Rdoc approach is described in this article:http://wi...

Using Regular Expressions in MS SQL Server 2005

Regular Expressions are an extremely powerful tool for parsing and querying textual data; so using them in a database environment looks like a good match. But DBMS vendors have been rather slow building RegEx functionality into their offerings. Oracle has it since 10g and some open source databases also have a head start.Microsoft obviously put the emphasis on XML/XPath since SQL Server 2000, and regular expression support is not on the horizon, even for SQL Server 2008. A MSDN article gives you...

Windows Live programs can't be installed on this operating system

My Microsoft Annoyance du Jour: Trying to download Live Writer Beta 3 from any computer located in Thailand will bring up a Thai download screen. While I have problem with the Thai page as such I'm not too keen on having the Thai version of the program with all dialogs and help in Thai but this is the only choice:There is no option to choose another language, and every browser I tested (Opera, IE6, Firefox 1.5) will not let me download the US-English version regardless of browser language settin...

If you have MySQL Connector/Net installed and then install Orcas (Visual Studio 2008) Beta 2 (and probably earlier versions), your machine.config file will be changed so that it does not include the MySQL Connector/Net data provider information anymore. This can lead to problems with the DataSet designer, first complaining about the MySQL Connector/Net and then with the message quoted in title of this post. The simple solution is to reinstall the MySQL Connector/Net which will put the necessary ...

Finding Asymmetrical Duplicates with Transact-SQL

Finding duplicates over all involved columns with Transact-SQL is done with the queryselect column1 (, column2...)from tablegroup by column1 (, column2...)having count(*) > 1This technique is especially important for finding duplicates before inserting into tables with primary keys made up of multiple columns.But what if the duplicate is only in one column, call it half- or semi-duplicate, incomplete duplicate or asymmetrical duplicate or whatever. For example, I tried to come up with a query th...

Scaffold HABTM

Simple many-to-many relationships in Rails can be defined with the has_and_belongs_to_many directive in the controller. However, this approach has limitations for scaffolding in that Rails does not support rendering the relevant selection controls for the "other side of many" out-of-the box . There are a few plugins that can handle this, namely the scaffolding extension and ActiveScaffold. The latter gives you much richer - albeit somewhat rough around the edges - date entry pages for simply rep...

Google Map API - Mouse Wheel Zooming while Preventing Page Scroll

Update: This post may be outdated as implementations of the Google Map API should support pagescroll prevention out of the box now. This has been checked for Ruby on Rails and the pertinent code was removed.Since version 2.78 the Google Map API exposes mouse wheel scroll zooming straight out of the box, obviating the need for hacks and custom programming to get this essential user experience to fly. Mouse wheel zooming is enable by simply adding map.enableScrollWheelZoom(); after the code that ...

100% View but no Order (at least not in SQL Server 2005)

In SQL Server 2000 you could add ORDER BY to the query defining a view that started with SELECT TOP (100) PERCENT... which is the default query when you create a view with SQL Server Enterprise Manager for SQL Server 2000.The TOP statement would pretend to limit the resultset (nothing is actually limited when 100 percent are returned) and ORDER BY could be applied. However, things changed with SQL Server 2005. The query optimizer now removes both TOP and ORDER BY clauses if the query is for the ...

IDE Time Savers - Quickly Locate and Open Project Files

One of the greatest time-wasters using Visual Studio is navigating the Solution Explorer looking for files to open or edit. With multiple projects and more files and folders for each project it just gets worse and worse. So Chris O'Sullivan created this little Visual Studio Plugin to quickly find files to open and edit without leaving the keyboard. Lars Engel has improved it to work with Visual Studio 2003 (and 2005). Be sure to follow the installation instructions on Chris' site.The free DPack ...

Working with Nested Repeaters in ASP.NET

Sometimes I miss the option that you have in classic ASP, PHP or Ruby on Rails to just put a nested loop into the html page (view, presentation layer) to display nested data. Of course this is, strictly speaking, against ASP.NET best practices where you're supposed to use web controls for everything. Then again one could make the argument that the loop actually belongs in the view. This would be .aspx page, and not in the controller or the model (code behind file in ASP.NET).The task at hand is ...

Ubuntu in an Active Directory Windows Domain

Ok, the title's a bit contrived. It's for the keywords, mainly. Anyway, to have an Ubuntu machine in your network environment has a number of benefits: Learning Linux and trying out Linux software which for the most part is high-quality (and free). Have a staging server for your Ruby on Rails applications. Having an SSH access point into your network for (limited) remote administration, much easier to set up (less secure though) than VPN. You can either have a full installation of Ubuntu ...

Pretty Wordpress Permalinks on IIS 6 Shared Hosting

We all want pretty and search-engine friendly URLs for our blog posts. The most common format is /%year%/%monthnum%/%day%/%postname%/ as it gives users and search engines optimal information about the topic and the month of the post (er, you might want to check out the URL of this post for an example). As it turns out, having Wordpress generate such URLs is possible on IIS 6 in a shared hosting environment without much effort and there is no need to move to an Apache host with mod_rewrite etc. T...

Validating Windows Forms Text Input

Unlike ASP.NET (which I'm more familiar with), Windows Forms don't have any "Validation Controls", so validating input has to be wired into the event model of your app. After some experimenting I found this procedure to work best for validating text box input:1. Drop an ErrorProvider component onto your form. This component appears to have designer support when you drag it, however, it is not a control but a container-level component (like ImageList and ToolTip among others). The ErrorProvider c...

Berlin Wall (Berliner Mauer) in HD View

HD View is a technology from Microsoft Research, merging pyramidic/pyramidal (mutiple layers with different pixel counts) viewing technology introduced by the likes of Zoomify with panoramic viewing today offered by viewers implemented in QTVR, Java and Flash. Microsoft have also addressed the issues arising from the perspective projection used by current panoramic viewers, which are especially obvious with wide-angle QTVR cubic panoramas. These problems make the viewing experience sometimes fee...

Health Care Quality and Costs in Thailand

The quality of healthcare in Thailand is truly amazing. Hospitals in larger cities are not only clean, well organized and staffed with friendly nurses and doctors, they also have all the latest technology and equipment. Add to that the dexterity and craftsmanship Thais have built over centuries, which today comes to the fore in high quality surgery. Having lived in Thailand for ten years I have yet to come across a foreigner being the "victim" of a botched surgery. Rather, everyone seems to be t...

Synchronizing Local Data with a Remote Web Hosting Database

Many webmasters of smaller web sites use the services of web hosting companies located in locations around the globe. Here in Thailand running your own web server is not feasible, as connections from the important markets of Europe, the Americas and even other parts of Asia might be too slow and unreliable. Using the services of a web hosting company usually involves running a local development database and an identical database running on the web hosting company's servers.To keep the contents i...

Spirited Away (Twice)

From The Nation:##Work began in Chiang Mai yesterday to remove a fountain at the Chang Pheuk Gate. The fountain, which has been the subject of a seven-year dispute between the Chiang Mai Municipality and the Fine Arts Department, will be re-installed at Suan Lanna Rama IX Park. Published on July 13, 2007A ritual to apologise to supernatural spirits was held at 8am yesterday before work began. Astrologer Sukit Phutasin said the gate had served as a triumphal entranceway to the city for Lanna king...

Resource file

Visual Studio 2002 and 2003 created resx resource files for each and every ascx and aspx file. When upgrading to ASP.NET 2.0 these files are no longer needed as resource files are centrally stored in the resource folders and compiled.So if after removing the resx files you get compilation errors such as the followingsimply open the project file (.csproj or .vbproj) in Notepad and delete the entries that look like this: {:tag :br, :attrs nil, :content []}Proposing a Centimal Number System for Geotagging and Geocoding

##Geotagging of photos and other data items today is a tedious and error-prone affair, not least because Latitude and Longitude have to be entered 100% correctly. One wrong digit and you may be many meters or many miles off. Certainly there are numerous tools to these task easier and new ones are released almost daily in this age of geotagging craze. Even with these products, having to deal with high precision numbers, positive and negative, matching time etc. can be quite daunting. So as with d...

The Antonym of Integer

What is the antonym of integer (whole number)? I found nothing in any dictionaries or a clear answer on the web, but this in the Wikipedia:Historically, any number that did not represent a whole was called a "fraction". The numbers that we now call "decimals" were originally called "decimal fractions"; the numbers we now call "fractions" were called "vulgar fractions", the word "vulgar" meaning "commonplace"."Fraction" makes sense, as anything that is not integer (whole) is fractured (broken). O...

Seconds Passed since Point in Time

After not finding a simple app online calculating the seconds since a past point in time, I made this little web form.It uses the rather obscure DateTime.ParseExact () function which provides an unforgiving way to parse a date string according to a specific date format string. The date string has to match the format string exactly, otherwise an exception will be thrown. Also, don't forget to escape slashes in your date format string.Here's some sample code: string theDate = tbDateInput.Text;...

Split()-like string-to-array function in Transact-SQL

Transact-SQL doesn't have arrays or nifty string functions like the C SELECT * FROM table1 WHERE id in (1,2,3,526); so why no looping through comma-delimited strings?A "Table-valued User-defined Function" returning a table variable is a handy and versatile workaround letting you query and loop through the values with near array-like ease.The code could look like this: Leo: Man, thank you very much for this. I was looking so hard for something like this and I found your site. Thanx a lot LeoAsh...

Query multiple databases with SQL Server 2005's new SYNONYMS aliasing feature

In SQL Server 2005 it's very easy to query multiple databases in the same statement.For databases on the same server just use: SELECT * FROM Database1.dbo.Table1 INNER JOIN Database2.dbo.Table1 ON Database1.dbo.Table1.ID = Database2.dbo.Table1.ID GO The statement is similar for linked servers.To provide for changing object names in the future the new SYNONYM feature of SQL Server 2005 is very handy. It lets you declare aliases for the following objects: Tables Views Stored procedures C...

Perl Help CHM

Compiled HTML help for Perl is here, well written and easy to read. The very useful link contains much other stuff too.#Donnette Panama: I just wanted to say that I found your site via Goolge and I am glad I did. Keep up the good work and I will make sure to bookmark you for when I have more free time away from the books. Thanks again!...

Alt + Tab Task Switcher with clickable icons

Goheer has created a very nifty utility to greatly improve on the windows task switcher (Ctrl + T) with clickable icons and thumbnails of the open windows. There is also a power toy doing something similar but why use MS when you can avoid it? One more reason not to upgrade to Vista....

Structure and Interpretation of Computer Programs PDF

Structure and Interpretation of Computer Programs in tagged and optimized PDF version is available here. The book is the basis for computer science course 6.001 at MIT and quoted by Joel Spolsky's rant about the dangers of Java Schools. You could read this book on your PDA and code away on or cut and paste the samples using the brilliant Pocket Scheme for an extremely geeky tour de force. By all means buy a copy of this unrivaled classic, also to get the famous wizard cover that’s missing from t...

Honda Jazz/Fit Owner's Manual

Having bought a Honda Jazz in Thailand I was looking all over the web for an owner's manual in English (the supplied version is in Thai which is tedious for me to read). Here I finally found it.#Nigel: Just to say thanks - I too have been searching for an owners manualHelen: Many thanks for this - I have also been searching to not much avail.andria: thank you very much for your help! i beleive it is rediculous that an english manual for this car is not available! thank you again for your help!zh...

Understanding Thailand's Political Situation - Essential Reading

The current politial situation in Thailand can only be understood in its historical context. The Western notion expressed by some that "the coup was justified to fight corruption of the toppled regime" is quite simplistic, legalistic and seen from a purely Western perspective. For more profound backround information, two articles stand out: Kasian Tejapira's Toppling Thaksin (PDF download is at the bottom of the page) and Duncan McCargo's **Network monarchy and legitimacy crises in Thailand** (f...

The Culture of Corruption from a Religious Perspective

Another article analyzing Thailand's culture of corruption from a religious vantage point. Thailand is fundamentally a very individualistic society where social conscience is exercised only within a circle of family, village or friends. This can be observed in road traffic where strangers meet and show hardly any consideration for one another. However, as soon as some sort of contact is established, Thais are extremely friendly and helpful with excellent social skills.The karmic viewpoint is als...

Thailand's Culture of Corruption

A brilliant article detailing the corruption from cradle to grave ingrained in Thai society. Surely the described "short-cuts" can be a very refreshing break from over-regulated Western societies, but sometimes one really learns the hard way that the rule of law has definite advantages. Thais have never subjected to rulers or rules, the villages were always rather independent. But practiced by the ruling elites, these customs have very sinister consequences in perpetuating an extreme hierarchica...

ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'Update' that has parameters:...

When building an editable ASP.NET 2.0 GridView or **DetailsView **this error is probably the most common issue. There must hardly be a developer who has not come across it at one time or another. It occurs when working with an ObjectDataSource based on a TableAdapter in ASP.NET 2.0, the easy path to enable Updating, Inserting and Deleting without any code or stored procedures the TableAdapter respresenting the data layer. This is the main advantage the GridView has over the DataGrid of .NET v.1x...

Dynamic ORDER BY with CASE statement in SQL Server - data type issues

In Microsoft SQL Server 2005 Transact-SQL (and prior versions), you can make a dynamic ORDER BY based on a variable like so: You can SET @OrderBy = 'CustomerID' or SET @OrderBy = 'Rating' , sorting will fail with SQL error similar to the following: Conversion failed when converting character string to smalldatetime data type. in the first case and Msg 8115, Level 16, State 2, Line 3 Arithmetic overflow error converting expression to data type smalldatetime. in the second if the optimizer...

comments powered by Disqus