> a <- strsplit("x y z", ' ')
> a
[[1]]
[1] "x" "y" "z"
> class(a)
[1] "list"
If you are not that familiar with R, like me, the obvious way to access an element in the list will not work:
> a[1]
[[1]]
[1] "x" "y" "z"
> a[2]
[[1]]
NULL
A collection of computer systems and programming tips that you may find useful.
Brought to you by Craic Computing LLC, a bioinformatics consulting company.
$ unzip *zip
Archive: ipab20080103_wk01.zip
caution: filename not matched: ipab20080110_wk02.zip
caution: filename not matched: ipab20080117_wk03.zip
[...]
$ unzip \*.zip
Archive: ipab20080103_wk01.zip
inflating: ipab20080103.xml
inflating: ipab20080103lst.txt
inflating: ipab20080103rpt.html
Archive: ipab20080110_wk02.zip
inflating: ipab20080110.xml
inflating: ipab20080110lst.txt
inflating: ipab20080110rpt.html
[...]
config.action_mailer.default_url_options = { :host => "craic.com" }The application.rb file applies to all environments. Putting this in development.rb or production.rb lets you use different hosts for each environment.
<%= link_to object.name, mymodel_url(object) %>
...produces...
<a href="http://craic.com/mymodels/1">My Object</a>
A standard HTML multiple Select menu allows the user to select multiple options using Command-Click. But when the list of options is long, requiring the user to scroll, it becomes cumbersome and prone to errors.
An effective solution is to use two select menus in tandem, with buttons allowing options to be swapped between the two.
I'm pleased to announce the release of a new jQuery plugin that makes tandem selects simple to set up and easy to customize.
Tandem Select consists of a JavaScript function that leverages the jQuery library, a CSS file and template HTML code.
More information and live demos can be found on the Project Page and the software can be downloaded from the GitHub repository.
myobjs.sort_by{|a| a.created_at}This works but it is really sorting on the String representation of those dates. That may be good enough for some uses but not if you want to sort down to the minute and second and in particular, if you want to sort in correct descending order.
myobjs.sort_by{|a| a.created_at.to_i}
> today = Date.today
=> Mon, 14 Mar 2011
> today.strftime("%s").to_i
=> 1300060800
$ sudo -E /usr/local/sbin/nginx
[mysqld]
datadir=/usr/local/mysql/data
bind-address = 127.0.0.1
character-set-server = utf8
max_allowed_packet = 32M
[client]
default-character-set = utf8
[mysql]
max_allowed_packet = 32M
mysql> SHOW VARIABLES LIKE 'character\_set\_%';
+--------------------------+--------+
| Variable_name | Value |
+--------------------------+--------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
+--------------------------+--------+
# Configure the default encoding used in templates for Ruby 1.9.MySQL and Rails use different variants of utf8/utf-8 - make sure you are using the right one. And note the comment above this line - this sets up utf-8 encoding for templates ONLY.
config.encoding = "utf-8"
development:Here you are telling the database adapter that the database uses utf-8.
adapter: mysql2
host: localhost
encoding: utf8
[...]
# encoding: UTF-8This tells Ruby that we're using utf-8 in this model. I don't see a way to set this at the application level so you have to have to add it in all relevant model .rb file. I also don't like defining something with a comment line. I can't see how to define this in, say, an irb interactive session.
str.sub!(/ß/, 'β')I gathered up the character mappings that I needed (which were not may in my case) and wrote up a class method that I cloned in each model with the issue. I then ran those in the Rails console to correct the bad characters. The method is:
def self.make_utf8_cleanThis looks at your model and figures out which columns are of type String. It goes through all records and all character mappings, replacing text and updating the database as needed. Your mappings array could be much larger. There may be a better source of these, but this is a start.
mappings = [ ['α', 'α'],
['ß', 'β'],
['β', 'β'],
['’', '’'],
['“', '“'],
['â€\u009D;', '”'],
['â€', '”'],
['ö', 'ö'],
['®', '®']
]
# Get the list of String columns
columns = Array.new
self.columns.each do |column|
if column.type.to_s == 'string'
columns << column
end
end
# Go through each object -> column against all mappings
self.all.each do |obj|
columns.each do |column|
mappings.each do |mapping|
value = obj.attributes[column.name]
if value =~ /#{mapping[0]}/
s = value.gsub(/#{mapping[0]}/, "#{mapping[1]}")
obj.update_attribute(column.name.to_sym, s)
end
end
end
end
end
Loading development environment (Rails 3.0.4)It's a hack but it helped my 'fix' quite a few records that would have been a pain to recreate.
ruby-1.9.2-p0 > YourModel.make_utf8_clean
mysql> describe references;The solution is to prefix the table name with the database name like this:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'references' at line 1
mysql> describe mydb.references;
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
$ brew install postgresql
$ cp /usr/local/Cellar/postgresql/9.0.3/org.postgresql.postgres.plist ~/Library/LaunchAgents
$ launchctl load -w ~/Library/LaunchAgents/org.postgresql.postgres.plist
$ initdb /usr/local/var/postgres
The files belonging to this database system will be owned by user "jones".
This user must also own the server process.
[...]
$ createdb mydb
$ psql mydb
mydb-# select version();
mydb-# \h
$ env ARCHFLAGS="-arch x86_64" gem install pg
$ sudo dscl /Local/Default -append /Groups/staff GroupMembership $USERSimple... Brilliant... I'm sold...
$ ruby -e "$(curl -fsSL https://gist.github.com/raw/323731/install_homebrew.rb)"
$ brew install sqlite
$ gem install sqlite3 -- --with-sqlite3-include=/usr/local/Cellar/sqlite/3.7.5/include \It worked...
--with-sqlite3-lib=/usr/local/Cellar/sqlite/3.7.5/lib
$ gem install taps
$ gem install devise # or in Rails 3 add it to your Gemfile, and 'bundle'
$ rails generate devise:install # follow the instructions given
$ rails generate devise User
$ rails generate devise:views # this generates sign_in, etc views under 'app/views/devise' - not user!
attr_accessible :email, :password, :password_confirmation, :remember_me,
:first_name, :last_name, :active, :role
t.string :first_name
t.string :last_name
t.boolean :active, :default => true
t.string :role, :default => 'user'
<%= f.text_field :first_name %>
etc.
<img id="logo" src="images/logo.png" alt="Logo" />
<script>
$(document).ready(function() {
$('#logo').hover(function(e) {
this.src = this.src.replace('logo', 'logo_highlight');
},
function(e) {
this.src = this.src.replace('logo_highlight', 'logo');
});
});
</script>
$ mongo
> use admin
> db.addUser("your_admin_user", "your_password")
> exit
$ mongod --auth
$ mongo
> use admin
> db.auth("your_admin_user", "your_password")
> show dbs
> use your_db
> db.addUser("your_db_user", "your_password")
> db.system.users.find()
> exit
Mongoid.configure do |config|
name = "your_db"
config.database = Mongo::Connection.new.db(name)
config.database.authenticate("your_db_user", "your_password")
end
$ mongodump -d your_db -o . -u your_db_user -p your_password
[...]
$ mongorestore -u your_db_user -p your_password your_db
[...]/gems/mongo-1.2.1/lib/mongo/cursor.rb:86:in `next_document':
too much data for sort() with no index (Mongo::OperationFailure)
class RssEntry
include Mongoid::Document
field :entry_id
field :title
field :authors, :type => Array
field :timestamp, :type => Time
index :timestamp
index :title
end
#!/usr/bin/env ruby
require 'mongoid'
$:.unshift File.dirname(__FILE__)
require 'mongoid_test_model'
Mongoid.configure do |config|
name = "mongoid_test_db"
host = "localhost"
port = 27017
config.database = Mongo::Connection.new.db(name)
end
[...]
entry = RssEntry.create({
:title => title,
:entry_id => id,
:authors => authors,
:timestamp = Time.new
})
#!/usr/bin/env ruby
require 'mongoid'
$:.unshift File.dirname(__FILE__)
require 'mongoid_test_model'
Mongoid.configure do |config|
name = "mongoid_test"
host = "localhost"
port = 27017
config.database = Mongo::Connection.new.db(name)
end
# Call on each of the relevant models
RssEntry.create_indexes()
$ gem install twitter9: Write a small ruby app. This simple example takes a message on the command line, configures the client with the FOUR OAuth tokens/strings and then updates the private twitter account with the message:
#!/usr/bin/env ruby require 'twitter' abort "Usage: #{$0} message" if ARGV.length == 0 # Hard-wired to my private twitter account Twitter.configure do |config| config.consumer_key = 'your-app_key' config.consumer_secret = 'your_app_secret' config.oauth_token = 'your_account_token' config.oauth_token_secret = 'your_account_secret' end client.update(ARGV[0])10: It's that simple...
<a href="javascript:(function(){ // Get the current selection var s = ''; if (window.getSelection) { s = window.getSelection(); } else if (document.getSelection) { s = document.getSelection(); } else if (document.selection) { s = document.selection.createRange().text; } // Prompt for input if no text selected if (s == '') { s = prompt('Enter your text:'); } // Open the target URL in a new tab if ((s != '') && (s != null)) { window.open('http://example.com/yourapp?id=' + s); } })();">BOOKMARKLET</a>You would want to remove the comments from the bookmarklet, but you don't need to strip the newlines or minify the code.
window.open('http://patsy.craic.com/patsy?id=' + s, '_blank', 'height=600,width=1024,status=1,toolbar=1,directories=1,menubar=1,location=1');The options string in the third argument specifies what the new window should look like. You may need to experiment with these. With Google Chrome on the Mac these do not give me the expected result - the address is not editable and there is no bookmarks bar. I also found that simply using 'status,toolbar,etc' without the '=1' did not work, although you will see this listed as a valid syntax.