repo
string | commit
string | message
string | diff
string |
---|---|---|---|
mattscilipoti/mattscilipoti.github.io
|
1442934707592d20da53832675662b8df065809a
|
Publishing I18n (Part One)
|
diff --git a/_posts/2010-09-14-I18n_Rails3_and_gems.textile b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
index 56e018e..e8fa3bb 100644
--- a/_posts/2010-09-14-I18n_Rails3_and_gems.textile
+++ b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
@@ -1,78 +1,90 @@
---
layout: post
-title: I18n Quick Reference (for Rails 3 and common gems)
+title: I18n for Rails 3 and common gems (Part One)
published: true
---
h1. {{ page.title }}
p(meta). 14 Sept 2010 - Baltimore, MD
+Part One: Discussion
+Part Two: Quick Reference
+
+----
+
You're building a Rails 3 app.
It needs to support internationalization (I18n).
No problem. Rails 3 supports internationalization.
-You can use *translate(key)* or *t(key)*.
+You can use **translate(key)** or **t(key)**.
{% highlight haml %}
%h2= t('hello')
{% endhighlight %}
It looks up the key in config/locales/en.yml:
{% highlight yaml %}
en:
hello:
Hey y'all
{% endhighlight %}
Yielding...
h2. Hey y'all
__(Aside: I will be using en.yml throughout this post, any language file could be used.)__
----
But, we're using Rails. We expect conventions. And smart defaults.
-I shouldn't need to use *t(key)* wherever I need translations.
+I shouldn't need to use **t(key)** wherever I need translations.
h2. My expectations
-# Items that can be internationalized should have smart defaults. I should not have to make an entry like:
-pre.
- labels:
- name: Name
-# Similarly, there should be fallback/common/generic entries. If an error message doesn't exist for this validation, on this specific model, use the generic message for this validation. If a generic message doesn't exist in the localization file, fall back to the smart default.
-pre.
- create_success: "%{model} created"
- create_fail: "The %{model} could not be created:"
+*1.* Items that can be internationalized should have smart defaults. I should not have to make an entry like:
+
+pre. labels:
+ name: Name
+
+*2.* Similarly, there should be fallback/common/generic entries. If an error message doesn't exist for this validation, on this specific model, use the generic message for this validation. If a generic message doesn't exist in the localization file, fall back to the smart default.
+The generic:
- vs.
+pre. create_success: "%{model} created"
+ create_fail: "The %{model} could not be created:"
- tour_versions:
+The specific:
+
+pre. tour_versions:
create:
success: Your tour was successfully published.
-# Where possible, libraries should follow the rails conventions instead of inventing their own. This allows me to switch (or simply remove) libraries and I18n still works.
+
+*3.* Where possible, libraries should follow the rails conventions instead of inventing their own. This allows me to switch (or simply remove) libraries and I18n still works.
h2. What I Found
Platformatec has a "nice listing of Rails I18n conventions":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/.
On our project, we use simple_form, inherited_resources, and cancan.
Each one has a convention for I18n.
Each one different.
Luckily, the functionality doesn't overlap... much.
Rails covers error message defaults, attributes, submit buttons, and labels.
InheritedResources covers flash (using Responders).
SimpleForm deals with label, hint, and error.
cancan presents a 'not authorized' message.
So... expectations #1 & 2 are generally covered. But, sadly, #3 is not.
+
+A Quick Reference for each library will be provided after this commercial break...
+
+!http://www.bigrat.co.uk/images/music/commbreak.jpg!
|
mattscilipoti/mattscilipoti.github.io
|
ad2fbe41f7a5479eaf996a0246bc244dd79b4b1b
|
Add favicon.
|
diff --git a/_layouts/default.html b/_layouts/default.html
index 47e0f04..df1ef93 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,95 +1,98 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="verify-v1" content="e+easLfwnIZ88FY97u1VGgJKvc+p3lXqknL/YNQgDpU=" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
+ <link rel="icon"
+ type="image/png"
+ href="/favicon.png"/>
<link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
<link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">find me on github.com</a><br />
<a href="http://identi.ca/mattscilipoti/">or identi.ca</a><br />
<a href='https://www.ohloh.net/accounts/57627?ref=Tiny'>
<img alt='Ohloh profile for mattscilipoti' height='15' src='https://www.ohloh.net/accounts/57627/widgets/account_tiny.gif' width='80' />
</a>
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
diff --git a/favicon.png b/favicon.png
new file mode 100644
index 0000000..7492db2
Binary files /dev/null and b/favicon.png differ
|
mattscilipoti/mattscilipoti.github.io
|
d39f45a17111f087ef9b755643522312b9414aef
|
placeholder/reminder: conventional_rails
|
diff --git a/_posts/2010-09-16-conventional_rails.md b/_posts/2010-09-16-conventional_rails.md
new file mode 100644
index 0000000..0d9bc70
--- /dev/null
+++ b/_posts/2010-09-16-conventional_rails.md
@@ -0,0 +1,9 @@
+---
+layout: post
+title: Conventional Rails
+published: false
+---
+
+= {{ page.title }}
+
+p(meta). 16 Sept 2010 - Baltimore, MD
|
mattscilipoti/mattscilipoti.github.io
|
e391335b70beeb20430adcdf12ea30b6be28945a
|
Add expectations to I18n post.
|
diff --git a/_posts/2010-09-14-I18n_Rails3_and_gems.textile b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
index 86f6fb2..56e018e 100644
--- a/_posts/2010-09-14-I18n_Rails3_and_gems.textile
+++ b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
@@ -1,52 +1,78 @@
---
layout: post
-title: I18n conventions for Rails 3 and common gems
-published: false
+title: I18n Quick Reference (for Rails 3 and common gems)
+published: true
---
h1. {{ page.title }}
p(meta). 14 Sept 2010 - Baltimore, MD
You're building a Rails 3 app.
-It needs to support internationalization.
+It needs to support internationalization (I18n).
No problem. Rails 3 supports internationalization.
You can use *translate(key)* or *t(key)*.
{% highlight haml %}
%h2= t('hello')
{% endhighlight %}
It looks up the key in config/locales/en.yml:
{% highlight yaml %}
en:
hello:
Hey y'all
{% endhighlight %}
Yielding...
h2. Hey y'all
+__(Aside: I will be using en.yml throughout this post, any language file could be used.)__
+
----
-But, we're in Rails. We expect conventions.
+But, we're using Rails. We expect conventions. And smart defaults.
+I shouldn't need to use *t(key)* wherever I need translations.
+
+h2. My expectations
+
+# Items that can be internationalized should have smart defaults. I should not have to make an entry like:
+pre.
+ labels:
+ name: Name
+# Similarly, there should be fallback/common/generic entries. If an error message doesn't exist for this validation, on this specific model, use the generic message for this validation. If a generic message doesn't exist in the localization file, fall back to the smart default.
+pre.
+ create_success: "%{model} created"
+ create_fail: "The %{model} could not be created:"
+
+ vs.
-Platformatec has a nice "listing of Rails I18n conventions":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/.
+ tour_versions:
+ create:
+ success: Your tour was successfully published.
+# Where possible, libraries should follow the rails conventions instead of inventing their own. This allows me to switch (or simply remove) libraries and I18n still works.
+
+
+h2. What I Found
+
+Platformatec has a "nice listing of Rails I18n conventions":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/.
On our project, we use simple_form, inherited_resources, and cancan.
Each one has a convention for I18n.
Each one different.
Luckily, the functionality doesn't overlap... much.
-Rails covers
-InheritedResources covers flash.
+Rails covers error message defaults, attributes, submit buttons, and labels.
+InheritedResources covers flash (using Responders).
SimpleForm deals with label, hint, and error.
-cancan presents an invalid login message.
\ No newline at end of file
+cancan presents a 'not authorized' message.
+
+So... expectations #1 & 2 are generally covered. But, sadly, #3 is not.
diff --git a/index.html b/index.html
index 58428d8..4db1f74 100644
--- a/index.html
+++ b/index.html
@@ -1,27 +1,27 @@
---
layout: default
title: Matt Scilipoti
---
<div id="home">
<h2>Blog Posts</h2>
<ul class="posts">
{% for post in site.posts %}
<li><span>{{ post.date | date_to_string }}</span> » <a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
<h2>Interviews, Talks, Etc</h2>
<ul class="posts">
<li><span>13 Apr 2010</span> » <a href="http://www.meetup.com/bmore-on-rails/calendar/12834060/?from=list&offset=0">Effective Cucumber (w/George Anderson) at B'more on Rails</a></li>
</ul>
- <h3>Open Source Projects</h3>
+ <h3>Some Open Source Projects I Use/Recommend</h3>
<ul class="posts">
<li><a href="http://github.com/mojombo/jekyll/">Jekyll:</a> A simple, blog aware, static site generator (used for this site).</li>
<li><a href="http://github.com/mojombo/chronic/">Chronic:</a> Ruby natural language date/time parser</li>
</ul>
<h3>My Repos (sources, no forks)</h3>
<p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p>
</div>
|
mattscilipoti/mattscilipoti.github.io
|
244a87dca625cce6ac5f532e064fb95430ff915b
|
Simplify blog:server
|
diff --git a/blog.thor b/blog.thor
index 96a9160..2758eea 100644
--- a/blog.thor
+++ b/blog.thor
@@ -1,12 +1,9 @@
class Blog < Thor
- desc "start", "Starts a server on port:4000, automatically refreshes as site is changed"
- method_options :auto_refresh => true
+ desc "starts a server", "Starts a server on port:4000, automatically refreshes as site is changed"
def server
- auto_refresh = options[:auto]
- cmd = 'jekyll --pygments --server'
- cmd += ' --auto' if auto_refresh
+ cmd = 'jekyll --pygments --server --auto'
exec cmd
end
end
\ No newline at end of file
|
mattscilipoti/mattscilipoti.github.io
|
7615385ac8dd4f4e48124c45b1b49cb829b34e2c
|
A b'more talk.
|
diff --git a/index.html b/index.html
index 6592a88..58428d8 100644
--- a/index.html
+++ b/index.html
@@ -1,27 +1,27 @@
---
layout: default
title: Matt Scilipoti
---
<div id="home">
<h2>Blog Posts</h2>
<ul class="posts">
{% for post in site.posts %}
<li><span>{{ post.date | date_to_string }}</span> » <a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
<h2>Interviews, Talks, Etc</h2>
<ul class="posts">
- <li><span>23 Apr 2009</span> » <a href="http://example.com">Example</a></li>
+ <li><span>13 Apr 2010</span> » <a href="http://www.meetup.com/bmore-on-rails/calendar/12834060/?from=list&offset=0">Effective Cucumber (w/George Anderson) at B'more on Rails</a></li>
</ul>
<h3>Open Source Projects</h3>
<ul class="posts">
<li><a href="http://github.com/mojombo/jekyll/">Jekyll:</a> A simple, blog aware, static site generator (used for this site).</li>
<li><a href="http://github.com/mojombo/chronic/">Chronic:</a> Ruby natural language date/time parser</li>
</ul>
<h3>My Repos (sources, no forks)</h3>
<p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p>
</div>
|
mattscilipoti/mattscilipoti.github.io
|
8499bbb4514af7690bdaee9f049db4d18e324903
|
Add 3 (unpublished) posts
|
diff --git a/_posts/2010-05-25-requirement_or_policy.textile b/_posts/2010-05-25-requirement_or_policy.textile
new file mode 100644
index 0000000..6f3275d
--- /dev/null
+++ b/_posts/2010-05-25-requirement_or_policy.textile
@@ -0,0 +1,24 @@
+---
+layout: post
+title: Requirement? Or Policy?
+published: false
+---
+
+h1. {{ page.title }}
+
+p(meta). 25 May 2010 - Laurel, MD
+
+Here's a "simple" phrase that may save you some headaches.
+
+Code the requirement, pass the policy.
+
+
+
+{% highlight ruby %}
+And 'I have filled out my billing info' do
+ @client.update_attribute :billing_info_valid, true
+
+And 'I have filled out my billing info' do
+ Factory(:payment_card, :user => @client)
+
+{% endhighlight %}
\ No newline at end of file
diff --git a/_posts/2010-07-08-rails_3_plugins_and_initialization.textile b/_posts/2010-07-08-rails_3_plugins_and_initialization.textile
new file mode 100644
index 0000000..5aa007d
--- /dev/null
+++ b/_posts/2010-07-08-rails_3_plugins_and_initialization.textile
@@ -0,0 +1,76 @@
+---
+layout: post
+title: Rails 3 plugins and initialization
+published: false
+---
+
+h1. {{ page.title }}
+
+p(meta). 08 June 2010 - Baltimore, MD
+
+I like using an in-memory database. It's fast AND I don't have to play schema load games. The latest schema is automatically used... if you are using the memory_test_fix plugin.
+
+As of 2010-07-08, this plugin does not support Rails 3. It is a very simple plugin. One file. The code is below. Basically, it ensures the schema is loaded during startup, if you are using an in-memory database. This looked like a perfect opportunity to learn about plugins and rails 3.
+
+This post documents my struggles to upgrade it.
+
+After the appropriate setup (see http://bit.ly/memory_test_fix) with minor updates for Rails 3:
+ rails plugin install http://topfunky.net/svn/plugins/memory_test_fix
+
+Problem: schema is not loaded
+Cause: This condition failed: ENV["RAILS_ENV"] == "test". Rails.env => 'development'
+
+Hypothesis: I should load the plugin after environment AR has initialized.
+Attempt:
+
+
+
+
+== The code
+
+{% highlight ruby %}
+# Update: Looks for the SQLite and SQLite3 adapters for
+# compatibility with Rails 1.2.2 and also older versions.
+def in_memory_database?
+ if ENV["RAILS_ENV"] == "test" and
+ (Rails::Configuration.new.database_configuration['test']['database'] == ':memory:' or
+ Rails::Configuration.new.database_configuration['test']['dbfile'] == ':memory:')
+ begin
+ if ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLite3Adapter
+ return true
+ end
+ rescue NameError => e
+ if ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLiteAdapter
+ return true
+ end
+ end
+ end
+ false
+end
+
+def verbosity
+ Rails::Configuration.new.database_configuration['test']['verbosity']
+end
+
+def inform_using_in_memory
+ puts "Creating sqlite :memory: database"
+end
+
+if in_memory_database?
+ load_schema = lambda {
+ load "#{RAILS_ROOT}/db/schema.rb" # use db agnostic schema by default
+ # ActiveRecord::Migrator.up('db/migrate') # use migrations
+ }
+ case verbosity
+ when "silent"
+ silence_stream(STDOUT, &load_schema)
+ when "quiet"
+ inform_using_in_memory
+ silence_stream(STDOUT, &load_schema)
+ else
+ inform_using_in_memory
+ load_schema.call
+ end
+end
+
+{% endhighlight %}
\ No newline at end of file
diff --git a/_posts/2010-09-14-I18n_Rails3_and_gems.textile b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
new file mode 100644
index 0000000..86f6fb2
--- /dev/null
+++ b/_posts/2010-09-14-I18n_Rails3_and_gems.textile
@@ -0,0 +1,52 @@
+---
+layout: post
+title: I18n conventions for Rails 3 and common gems
+published: false
+---
+
+h1. {{ page.title }}
+
+p(meta). 14 Sept 2010 - Baltimore, MD
+
+You're building a Rails 3 app.
+It needs to support internationalization.
+No problem. Rails 3 supports internationalization.
+
+You can use *translate(key)* or *t(key)*.
+
+{% highlight haml %}
+
+%h2= t('hello')
+
+{% endhighlight %}
+
+It looks up the key in config/locales/en.yml:
+
+{% highlight yaml %}
+
+en:
+ hello:
+ Hey y'all
+
+{% endhighlight %}
+
+Yielding...
+
+h2. Hey y'all
+
+----
+
+But, we're in Rails. We expect conventions.
+
+Platformatec has a nice "listing of Rails I18n conventions":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/.
+
+On our project, we use simple_form, inherited_resources, and cancan.
+Each one has a convention for I18n.
+Each one different.
+
+Luckily, the functionality doesn't overlap... much.
+
+Rails covers
+InheritedResources covers flash.
+SimpleForm deals with label, hint, and error.
+cancan presents an invalid login message.
\ No newline at end of file
|
mattscilipoti/mattscilipoti.github.io
|
c7ff193f9aa7f484e9b37e248e3553e251296772
|
Add thor file w/blog:start
|
diff --git a/blog.thor b/blog.thor
new file mode 100644
index 0000000..96a9160
--- /dev/null
+++ b/blog.thor
@@ -0,0 +1,12 @@
+class Blog < Thor
+
+ desc "start", "Starts a server on port:4000, automatically refreshes as site is changed"
+ method_options :auto_refresh => true
+ def server
+ auto_refresh = options[:auto]
+ cmd = 'jekyll --pygments --server'
+ cmd += ' --auto' if auto_refresh
+ exec cmd
+ end
+
+end
\ No newline at end of file
|
mattscilipoti/mattscilipoti.github.io
|
6273ae59c6cccee1ed4d833eb73b08236faaea45
|
Setup w/rvm & bundler.
|
diff --git a/.rvmrc b/.rvmrc
new file mode 100644
index 0000000..f0d9c29
--- /dev/null
+++ b/.rvmrc
@@ -0,0 +1 @@
+rvm use ree@blog
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..a82b70c
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,5 @@
+# A sample Gemfile
+source "http://rubygems.org"
+
+gem 'jekyll', '0.7.0'
+gem 'RedCloth'
\ No newline at end of file
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..fd93192
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,24 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ RedCloth (4.2.3)
+ classifier (1.3.3)
+ fast-stemmer (>= 1.0.0)
+ directory_watcher (1.3.2)
+ fast-stemmer (1.0.0)
+ jekyll (0.7.0)
+ classifier (>= 1.3.1)
+ directory_watcher (>= 1.1.1)
+ liquid (>= 1.9.0)
+ maruku (>= 0.5.9)
+ liquid (2.2.2)
+ maruku (0.6.0)
+ syntax (>= 1.0.0)
+ syntax (1.0.0)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ RedCloth
+ jekyll (= 0.7.0)
|
mattscilipoti/mattscilipoti.github.io
|
629737cec77663332d3c272d105da79fe1b67a37
|
Fix footer: github & identi.ca
|
diff --git a/_layouts/default.html b/_layouts/default.html
index 95e71f5..47e0f04 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,95 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="verify-v1" content="e+easLfwnIZ88FY97u1VGgJKvc+p3lXqknL/YNQgDpU=" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
<link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
- <a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
- <a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
+ <a href="http://github.com/mattscilipoti/">find me on github.com</a><br />
+ <a href="http://identi.ca/mattscilipoti/">or identi.ca</a><br />
<a href='https://www.ohloh.net/accounts/57627?ref=Tiny'>
<img alt='Ohloh profile for mattscilipoti' height='15' src='https://www.ohloh.net/accounts/57627/widgets/account_tiny.gif' width='80' />
</a>
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
|
mattscilipoti/mattscilipoti.github.io
|
503e6839f652fe439af47b10180f61c4c214d409
|
Add smartpants, typographic magic (http://github.com/blog/706-jekyll-puts-on-smartypants)
|
diff --git a/_config.yml b/_config.yml
index 6d67c09..e989c29 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,2 +1,4 @@
markdown: rdiscount
pygments: true
+rdiscount:
+ extensions: [smart]
|
mattscilipoti/mattscilipoti.github.io
|
c80359873161677eaadded6c2e8047baa81e3804
|
format tweaks.
|
diff --git a/_posts/2010-05-06-heroku_email_socket_error.textile b/_posts/2010-05-06-heroku_email_socket_error.textile
index 23763e6..a4b4278 100644
--- a/_posts/2010-05-06-heroku_email_socket_error.textile
+++ b/_posts/2010-05-06-heroku_email_socket_error.textile
@@ -1,31 +1,30 @@
---
layout: post
title: Email causing SocketError on Heroku?
---
h1. {{ page.title }}
p(meta). 06 May 2010 - Laurel, MD
Getting a SocketError while sending emails on heroku, using sendgrid? It may be some gmail env vars.
-While working on a project that I just inherited, we enabled sendgrid for our heroku app. Upon sending an email, we received:
+While working on a project that I just inherited, we enabled sendgrid for our heroku app. Sending an email raised this error:
+
h2. SocketError (getaddrinfo: Name or service not known)
Google searches indicated ActiveMailer configuration issues, but Heroku was pretty clear:
<pre>Rails apps using ActionMailer will just work, no setup is needed after the addon is installed.</pre>
While ensuring that RACK_ENV was set correctly (when all else fails), I found these two settings:
-<pre>
-GMAIL_SMTP_PASSWORD => #blahblah#
-GMAIL_SMTP_USER => [email protected]
-</pre>
+<pre>GMAIL_SMTP_PASSWORD => #blahblah#
+GMAIL_SMTP_USER => [email protected]</pre>
-Removing them fixed my email.
+Removing them fixed my email. Sendgrid is working fine.
-Armed with this evidence, I found: http://blog.heroku.com/archives/2009/11/9/tech_sending_email_with_gmail/
-And so... someone had (partially) set up the server for gmail, but something about it was failing now.
+Armed with this evidence, I found "tech_sending_email_with_gmail":http://blog.heroku.com/archives/2009/11/9/tech_sending_email_with_gmail/
+And so... someone had set up the server for gmail, but something about it was failing now.
Now I know. And you do too.
-Note: this is just one way to receive this error.
+Note: this is just *one* cause of this error.
|
mattscilipoti/mattscilipoti.github.io
|
c71dc477b81ca207c33d0dd4c79c59d14d9d2ea6
|
New post: heroku email.
|
diff --git a/_posts/2010-05-06-heroku_email_socket_error.textile b/_posts/2010-05-06-heroku_email_socket_error.textile
new file mode 100644
index 0000000..23763e6
--- /dev/null
+++ b/_posts/2010-05-06-heroku_email_socket_error.textile
@@ -0,0 +1,31 @@
+---
+layout: post
+title: Email causing SocketError on Heroku?
+---
+
+h1. {{ page.title }}
+
+p(meta). 06 May 2010 - Laurel, MD
+
+Getting a SocketError while sending emails on heroku, using sendgrid? It may be some gmail env vars.
+
+While working on a project that I just inherited, we enabled sendgrid for our heroku app. Upon sending an email, we received:
+h2. SocketError (getaddrinfo: Name or service not known)
+
+Google searches indicated ActiveMailer configuration issues, but Heroku was pretty clear:
+ <pre>Rails apps using ActionMailer will just work, no setup is needed after the addon is installed.</pre>
+
+While ensuring that RACK_ENV was set correctly (when all else fails), I found these two settings:
+<pre>
+GMAIL_SMTP_PASSWORD => #blahblah#
+GMAIL_SMTP_USER => [email protected]
+</pre>
+
+Removing them fixed my email.
+
+Armed with this evidence, I found: http://blog.heroku.com/archives/2009/11/9/tech_sending_email_with_gmail/
+And so... someone had (partially) set up the server for gmail, but something about it was failing now.
+
+Now I know. And you do too.
+
+Note: this is just one way to receive this error.
|
mattscilipoti/mattscilipoti.github.io
|
364cb2cfe139745586d882a6564bbed68eae4cf6
|
new post: 2010-04-29-postgresql_on_snow_leopard_with_rails_using _homebrew.textile
|
diff --git a/_posts/2010-04-29-postgresql_on_snow_leopard_with_rails_using_homebrew.textile b/_posts/2010-04-29-postgresql_on_snow_leopard_with_rails_using_homebrew.textile
new file mode 100644
index 0000000..19f6d1f
--- /dev/null
+++ b/_posts/2010-04-29-postgresql_on_snow_leopard_with_rails_using_homebrew.textile
@@ -0,0 +1,65 @@
+---
+layout: post
+title: Rails and PostgreSQL on Snow Leopard using homebrew
+---
+
+h1. {{ page.title }}
+
+p(meta). 29 Apr 2010 - Laurel, MD
+
+As we have seen in the past, I couldn't find a definitive, accurate install and use guide for PostgreSQL with Rails on Snow Leopard, using homebrew. In the end, it took less work than any of the existing instruction lists (that I found) indicated.
+
+Of Note: I did NOT need to make any changes to my $PATH or .profile.
+
+Most of this is based on info from:
+ * http://blog.tquadrado.com/?p=215
+ * test
+ * http://www.gregbenedict.com/2009/08/31/installing-postgresql-on-snow-leopard-10-6/
+
+Thank you all for the helpful info.
+
+
+h2. Installation
+
+We assume you have homebrew installed.
+Note: I did not allow incoming network connections. You may, but everything I discuss works without it.
+
+ <code>$ brew install postgresql #postgres is alias</code>
+
+Follow the instructions for initializing (initdb...).
+Follow the instructions for automatic load, if applicable (launchctl...)
+
+That's it. I didn't need any of the mkdir and chown commands some instructions listed.
+
+Install the fast postgres gem:
+ <code> $ gem install pg </code>
+
+Installation complete.
+
+
+h2. Rails
+
+The docs indicate that a superuser named 'postgres' is created by default.
+Instead, my installation created a superuser named after the logged in user: $USER.
+
+To make sharing the database.yml easier, I created another user:
+<code>
+ $ createuser --superuser your_company_name -U $USER
+</code>
+
+Now update your database.yml:
+
+<pre>
+development:
+ adapter: postgresql
+ database: health_crowd_dev
+ username: your_company_name
+ host: localhost
+</pre>
+
+Some instructions list more settings. These worked for me.
+
+You are ready.
+<code> $ rake db:create</code>
+
+fini.
\ No newline at end of file
|
mattscilipoti/mattscilipoti.github.io
|
682570a606ee498b365fe7898a6d9dd4667bc799
|
footer: corrected ohloh banner.
|
diff --git a/_layouts/default.html b/_layouts/default.html
index d2d933b..95e71f5 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,93 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="verify-v1" content="e+easLfwnIZ88FY97u1VGgJKvc+p3lXqknL/YNQgDpU=" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
<link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
- <a href='https://www.ohloh.net/accounts/57627?ref=Tiny'>
+ <a href='https://www.ohloh.net/accounts/57627?ref=Tiny'>
+ <img alt='Ohloh profile for mattscilipoti' height='15' src='https://www.ohloh.net/accounts/57627/widgets/account_tiny.gif' width='80' />
+ </a>
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
|
mattscilipoti/mattscilipoti.github.io
|
58e293cefd0c33a3432c1fdb9d5eeebe942d4df4
|
footer: added ohloh
|
diff --git a/_layouts/default.html b/_layouts/default.html
index 09830a8..d2d933b 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,92 +1,93 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="verify-v1" content="e+easLfwnIZ88FY97u1VGgJKvc+p3lXqknL/YNQgDpU=" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
<link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
+ <a href='https://www.ohloh.net/accounts/57627?ref=Tiny'>
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
|
mattscilipoti/mattscilipoti.github.io
|
ff0b2602ea2d2ad1012be8f184a0343fc6bda9e1
|
post; match false/nil: expanded
|
diff --git a/_posts/2009-08-26-match_false_nil.textile b/_posts/2009-08-26-match_false_nil.textile
index 5b3eb85..c917bfc 100644
--- a/_posts/2009-08-26-match_false_nil.textile
+++ b/_posts/2009-08-26-match_false_nil.textile
@@ -1,14 +1,75 @@
---
published: false
layout: post
-title: match false? or nil?
+title: regex match false? or nil?
---
h1. {{ page.title }}
p(meta). 26 Aug 2009 - Linthicum, MD
+We have some scripts we run which are "instrumented" with messages and progress bars.
-nil =~ 'test' -> false
-'bad' =~ 'test' -> nil
-'test' =~ 'test' -> 0
+Two issues:
+ # These are muddying up our specs
+ # In production, the progress bars can raise "Broken Pipe" errors (std out issues?).
+
+We will probably create some abstraction for this concept, but we started with:
+
+{% highlight ruby %}
+puts "It's working." if show_instrumentation?
+{% endhighlight %}
+
+The specs:
+
+{% highlight ruby %}
+describe '#show_instrumentation?' do
+ it "should default to false" do
+ @it.show_instrumentation?.should be_false
+ #@it.should_not be_show_instrumentation
+ end
+end
+
+describe '#show_instrumentation?' do
+ it "should be true if ENV['INFO']=true" do
+ ENV['INFO'] = true
+ @it.show_instrumentation?.should be_true
+ end
+end
+{% endhighlight %}
+
+The code:
+
+{% highlight ruby %}
+def show_instrumentation?
+ @show_instrumentation ||= (ENV['info'] =~ /true/i)
+end
+{% endhighlight %}
+
+This worked. But sometimes, ENV['INFO'] == 'true' when the first spec was run (spec --reverse). So.. we added the after:
+
+{% highlight ruby %}
+after :each do
+ ENV['info'] = ''
+end
+{% endhighlight %}
+
+Fail. nil is not false.
+
+Turns out:
+
+{% highlight ruby %}
+'' =~ /true/i -> nil
+'false' =~ /true/i -> nil
+'TRUE' =~ /true/i -> 0
+nil =~ /true/i -> false
+{% endhighlight %}
+
+So... how do you return a boolean from =~?
+
+
+{% highlight ruby %}
+def show_instrumentation?
+ @show_instrumentation ||= (ENV['info'] =~ /true/i) >= 0
+end
+{% endhighlight %}
|
mattscilipoti/mattscilipoti.github.io
|
45dde7ef27c9556de7206c2a2add08097f527813
|
new post: jekyll_pygment
|
diff --git a/_posts/2009-08-27-jekyll_pygment.textile b/_posts/2009-08-27-jekyll_pygment.textile
new file mode 100644
index 0000000..4fb3b06
--- /dev/null
+++ b/_posts/2009-08-27-jekyll_pygment.textile
@@ -0,0 +1,24 @@
+---
+published: true
+layout: post
+title: github pages, jekyll, and pygments
+---
+
+h1. {{ page.title }}
+
+p(meta). 27 Aug 2009 - Linthicum, MD
+
+This blog is run on "github pages":http://pages.github.com/. They use "Pygments":http://pygments.org/ for code syntax highlighting.
+
+To test it locally, I run:
+
+{% highlight bash %}jekyll --pygment --auto --server{% endhighlight %}
+
+This requires Pygments, which requires python.
+
+{% highlight sh %}
+sudo apt-get install python-setuptools
+sudo easy_install Pygments
+{% endhighlight %}
+
+
|
mattscilipoti/mattscilipoti.github.io
|
4a61e0fc7e60ba15715e8993fc9de308c212c469
|
post stairwell: correct meta info, so it is no longer published.
|
diff --git a/_posts/2009-06-12-its-lonely-in-the-stairwell.textile b/_posts/2009-06-12-its-lonely-in-the-stairwell.textile
index f5cfe17..e78b5af 100644
--- a/_posts/2009-06-12-its-lonely-in-the-stairwell.textile
+++ b/_posts/2009-06-12-its-lonely-in-the-stairwell.textile
@@ -1,13 +1,13 @@
-----
+---
published: false
layout: post
title: It's lonely in the stairwell.
-----
+---
It's clear to me that... Americans ignore stairs.
Dark, dank, dingy.
h3. For Instance
-There is evidence that hotel steps are only used by staff.
+There is evidence that hotel steps are only used by staff.
* above 1st Floor are well used.
|
mattscilipoti/mattscilipoti.github.io
|
5a9b9da447e2c0662714dd812ee721cc236c290d
|
new post: match_false_nil
|
diff --git a/_posts/2009-08-26-match_false_nil.textile b/_posts/2009-08-26-match_false_nil.textile
new file mode 100644
index 0000000..5b3eb85
--- /dev/null
+++ b/_posts/2009-08-26-match_false_nil.textile
@@ -0,0 +1,14 @@
+---
+published: false
+layout: post
+title: match false? or nil?
+---
+
+h1. {{ page.title }}
+
+p(meta). 26 Aug 2009 - Linthicum, MD
+
+
+nil =~ 'test' -> false
+'bad' =~ 'test' -> nil
+'test' =~ 'test' -> 0
|
mattscilipoti/mattscilipoti.github.io
|
0b4c673309c7a034b6e0d92e51e58173bfba616c
|
new post: moonshine-rmagick-jaunty
|
diff --git a/_posts/2009-08-21-moonshine-rmagick-jaunty.textile b/_posts/2009-08-21-moonshine-rmagick-jaunty.textile
new file mode 100644
index 0000000..e5a911a
--- /dev/null
+++ b/_posts/2009-08-21-moonshine-rmagick-jaunty.textile
@@ -0,0 +1,48 @@
+---
+published: true
+layout: post
+title: moonshine, rmagick, and jaunty
+---
+
+h1. {{ page.title }}
+
+
+p(meta). 21 Aug 2009 - Linthicum, MD
+
+h2. Moonshine
+
+"Moonshine":moonshine is "rails deployment and configuration management done right. ShadowPuppet + Capistrano == crazy delicious"
+
+We are going through a phase of server 'provisioning'. We need a demo server, one for load testing, and an updated ci server. We are also moving some production servers from Windows to Ubuntu. yay!
+
+Moonshine embraces convention and combines *rails* provisioning and deployment in a nice package. We enjoy it.
+
+h2. gem library dependencies
+
+Some gems have system library dependencies (rmagick requires imagemagick, etc). Moonshine already has a "recipes" for a few (see apt_gems.yml). When moonshine is installing a gem, it also installs any libraries listed for that gem. You can easily add your own in your moonshine.yml.
+
+*Gotcha:* Unfortunately (as we just discovered), your moonshine.yml entries do not override existing entries in apt_gems.yml. There are two options for overriding:
+ # replace the entry in the plugin's apt_gems.yml
+ # comment out the entry in the plugin's apt_gems.yml, then add your own entry in moonshine.yml.
+
+We chose #2.
+
+h2. Jaunty & rmagick
+
+While "moonshine":moonshine is, currently, only supported on Ubuntu 8.10 (Intrepid Ibex, really? Not LTS or the latest release? Interesting choice.) We have only found one issue with Jaunty (9.04). New library dependencies for rmagick/imagemagick.
+
+Here are the rmagick dependencies in jaunty:
+
+<pre>
+:apt_gems:
+ rmagick:
+ - imagemagick
+ - libmagickcore-dev
+ - libmagickwand-dev
+</pre>
+
+Note:
+ * We are using the string version, not the symbol (for rmagick). Either may work, we haven't tested the symbol yet.
+ * We are using rmagick -v 2.9.2.
+
+[moonshine]http://github.com/railsmachine/moonshine/tree/master
|
mattscilipoti/mattscilipoti.github.io
|
f8e11d1f7e7ea31ed4d202581dded991137253b8
|
webmaster: add meta verify for google.
|
diff --git a/_layouts/default.html b/_layouts/default.html
index a2e43c1..09830a8 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,91 +1,92 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta name="verify-v1" content="e+easLfwnIZ88FY97u1VGgJKvc+p3lXqknL/YNQgDpU=" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
<link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
|
mattscilipoti/mattscilipoti.github.io
|
96585fb0b37296910f75b105bee7a4ded7bfc195
|
facet post: tweak to test fix for formatting issue #701.
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index 10e4bca..0ce27ca 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,57 +1,56 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
+
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
-<div>
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
-</div>
-<div>
With:
-{% highlight ruby %}config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'{% endhighlight %}
-</div>
+{% highlight ruby %}
+config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
+{% endhighlight %}
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
h2. Update (07/29/2009): funky formatting.
%(update)Update (07/30/2009): using div as workaround.%
I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
Here's a screenshot:
!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
Argh.
Maybe these guys can help: "github support ticket":http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
|
mattscilipoti/mattscilipoti.github.io
|
a4248da82e4c9123dae03115a41a51fe66fdbf6c
|
cron post: tweaks to links.
|
diff --git a/_posts/2009-08-03-rails-script-runner-and-cron.textile b/_posts/2009-08-03-rails-script-runner-and-cron.textile
index 4b473b0..bf18147 100644
--- a/_posts/2009-08-03-rails-script-runner-and-cron.textile
+++ b/_posts/2009-08-03-rails-script-runner-and-cron.textile
@@ -1,74 +1,74 @@
---
published: true
layout: post
title: script/runner and cron
---
h1. {{ page.title }}
p(meta). 03 Aug 2009 - Linthicum, MD
h2. Intermittent processes
We have just started to run some daemon-like processes which check status at various time intervals. We started with a simple ruby script which looped, sleeping between runs. This was quick and easy, and worked fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these processes could not handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
Sample command:
<pre> script/runner ping_em_all.rb | tee -a log/ping.log</pre>
<br/>
h2. Enter cron.
Google research led me to believe that I simply needed to add an entry to cron, with the exact command arguments we used to start them manually (after removing the loop).
With two exceptions:
* we needed to call it with ruby.
* everything needed fully qualified paths.
We made the necessary entry using `crontab -e`.
<pre>
1 * * * * * /usr/bin/env ruby /home/user/projects/.../script/runner /home/user/projects/.../script/ping_em_all.rb >> log/ping.log
</pre>
??{color:red}Fail.?? Silently.
h2. Debugging cron
This was my first use of cron, beyond very basic things which had 'just worked'. This wasn't working and I had no indication of why. After some googling and a call to nevans, I was up to speed.
# Check your email to see the output from cron.
# No email. Of course, no email was setup on this dev box.
# Check syslog to see if the command was called. Check. We see the command. We need email.
# Setup email. More googling. Another call (thanks!). "japhr just did this":http://japhr.blogspot.com/2009/08/moving-past-beta.html. sweet. "setup for google apps":http://serverfault.com/questions/54069/how-to-setup-ubuntu-mail-server-with-google-apps. done.
# test: `echo -e "To: Me\nSubject: ssmtp test\n\nssmtp test" | /usr/sbin/ssmtp [email protected]`. ??{color:green}Pass.??
- # Email arrives from cron, indicating issues: no mail-to address. I add it to `crontab -e`: http://gist.github.com/169729
+ # Email arrives from cron, indicating issues: no mail-to address. I add it to `crontab -e` ("gist":http://gist.github.com/169729).
# Email arrives from cron, listing my failed validations. Nice.
??{color:red}Fail.?? Rails expects things to be run from RAILS_ROOT. We needed a `cd`.
h2. Enter script/local_runner.sh
-We created a simple bash script to change to RAILS_ROOT and run script/runner: http://gist.github.com/169729.
+We created a simple bash script to change to RAILS_ROOT and run script/runner ("gist":http://gist.github.com/169729).
After that, we simply responded to the emails.
# Setup cron to run every minute (*/1).
# First we got to pass with just script/runner.
# Then we added the script.
# It needs $TIPS_ROOT. cron isn't loading my bash.rc and a path with my home dir doesn't belong in /etc, so I add it to crontab -e.
# Then we added the log file.
- # There was an issue including the append output to log file command (>>) in crontab, so I converted the log file to an argument. argh.
+ # There was an issue including the append output to log file command (>>) in crontab, so I converted the log file to an argument. bleh.
??{color:green}PASS.??
-See a working version: http://gist.github.com/169729
+Get the "gist":http://gist.github.com/169729.
h2. A (very) brief intro to cron.
cron - daemon to execute scheduled commands
* edit: `crontab -e`
* list: `crontab -l`
* Sends email with output from each run. Note: this is the only way to debug.
* Logs to syslog (only indicates that entry was run, no output).
* The method to schedule your jobs can be a little confusing at first, but its power and simplicity is soon apparent. Google helps. So do the examples in `cheat cron`.
|
mattscilipoti/mattscilipoti.github.io
|
ef07b0aeff72df3ddb14ecac48919a54adc503fb
|
post cron: tweak and publish.
|
diff --git a/_posts/2009-08-03-rails-script-runner-and-cron.textile b/_posts/2009-08-03-rails-script-runner-and-cron.textile
index a0d39e7..4b473b0 100644
--- a/_posts/2009-08-03-rails-script-runner-and-cron.textile
+++ b/_posts/2009-08-03-rails-script-runner-and-cron.textile
@@ -1,72 +1,74 @@
---
-published: false
+published: true
layout: post
title: script/runner and cron
---
h1. {{ page.title }}
p(meta). 03 Aug 2009 - Linthicum, MD
h2. Intermittent processes
-We have just started to run some daemon-like processes with check status at various time intervals. We started with a simple ruby script which looped, sleeping between runs. This was quick and easy, and worked fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these processes could not handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
-We stared these scripts using commands like this:
+We have just started to run some daemon-like processes which check status at various time intervals. We started with a simple ruby script which looped, sleeping between runs. This was quick and easy, and worked fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these processes could not handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
-<pre>
- script/runner ping_em_all.rb | tee -a log/ping.log
-</pre>
+Sample command:
-h2. Enter cron.
+<pre> script/runner ping_em_all.rb | tee -a log/ping.log</pre>
+<br/>
-Google research led me to believe that I simply needed to add an entry to cron, with the exact command arguments we used to start them manually (after removing the loop). With two exceptions:
+h2. Enter cron.
+Google research led me to believe that I simply needed to add an entry to cron, with the exact command arguments we used to start them manually (after removing the loop).
+With two exceptions:
* we needed to call it with ruby.
* everything needed fully qualified paths.
-Fail. Silently.
+We made the necessary entry using `crontab -e`.
+<pre>
+ 1 * * * * * /usr/bin/env ruby /home/user/projects/.../script/runner /home/user/projects/.../script/ping_em_all.rb >> log/ping.log
+</pre>
+
+??{color:red}Fail.?? Silently.
h2. Debugging cron
This was my first use of cron, beyond very basic things which had 'just worked'. This wasn't working and I had no indication of why. After some googling and a call to nevans, I was up to speed.
- #. Check your email to see the output from cron.
- #. No email. Of course, no email was setup on this dev box.
- #. Check syslog to see if the command was called. Check. We see the command. We need email.
- #. Setup email. More googling. Another call (thanks!). "japhr just did this":http://japhr.blogspot.com/2009/08/moving-past-beta.html. sweet. "setup for google apps":http://serverfault.com/questions/54069/how-to-setup-ubuntu-mail-server-with-google-apps. done.
- #. test: `echo -e "To: Me\nSubject: ssmtp test\n\nssmtp test" | /usr/sbin/ssmtp [email protected]`. Pass.
- #. Email arrives from cron, indicating issues: no mail-to address. I add it to `crontab -e`: http://gist.github.com/169729
- #. Email arrives from cron, listing my failed validations. Nice.
+ # Check your email to see the output from cron.
+ # No email. Of course, no email was setup on this dev box.
+ # Check syslog to see if the command was called. Check. We see the command. We need email.
+ # Setup email. More googling. Another call (thanks!). "japhr just did this":http://japhr.blogspot.com/2009/08/moving-past-beta.html. sweet. "setup for google apps":http://serverfault.com/questions/54069/how-to-setup-ubuntu-mail-server-with-google-apps. done.
+ # test: `echo -e "To: Me\nSubject: ssmtp test\n\nssmtp test" | /usr/sbin/ssmtp [email protected]`. ??{color:green}Pass.??
+ # Email arrives from cron, indicating issues: no mail-to address. I add it to `crontab -e`: http://gist.github.com/169729
+ # Email arrives from cron, listing my failed validations. Nice.
+
+
+??{color:red}Fail.?? Rails expects things to be run from RAILS_ROOT. We needed a `cd`.
- Fail. Rails expects things to be run from RAILS_ROOT. We needed a `cd`.
h2. Enter script/local_runner.sh
We created a simple bash script to change to RAILS_ROOT and run script/runner: http://gist.github.com/169729.
After that, we simply responded to the emails.
- #. Setup cron to run every minute (*/1).
- #. First we got to pass with just script/runner.
- #. Then we added the script.
- #. It needs $TIPS_ROOT. cron isn't loading my bash.rc and a path with my home dir doesn't belong in /etc, so I add it to crontab -e.
- #. Then we added the log file.
- #. There was an issue including the append output to log file command (>>) in crontab, so I converted the log file to an argument. argh.
+ # Setup cron to run every minute (*/1).
+ # First we got to pass with just script/runner.
+ # Then we added the script.
+ # It needs $TIPS_ROOT. cron isn't loading my bash.rc and a path with my home dir doesn't belong in /etc, so I add it to crontab -e.
+ # Then we added the log file.
+ # There was an issue including the append output to log file command (>>) in crontab, so I converted the log file to an argument. argh.
-Pass.
+??{color:green}PASS.??
See a working version: http://gist.github.com/169729
-h2. A brief intro to cron.
+h2. A (very) brief intro to cron.
cron - daemon to execute scheduled commands
- * Sends email with output from each run. Note: this is the only way to debug.
- * Logs to syslog (only indicates that entry was run, no output).
* edit: `crontab -e`
* list: `crontab -l`
+ * Sends email with output from each run. Note: this is the only way to debug.
+ * Logs to syslog (only indicates that entry was run, no output).
* The method to schedule your jobs can be a little confusing at first, but its power and simplicity is soon apparent. Google helps. So do the examples in `cheat cron`.
-
-h2. References:
-
- * `cheat cron`
- *
|
mattscilipoti/mattscilipoti.github.io
|
41666319fb3917c32f3eda20914f1cbba5099ceb
|
Worked on post: script/runner and cron.
|
diff --git a/_posts/2009-08-03-rails-script-runner-and-cron.textile b/_posts/2009-08-03-rails-script-runner-and-cron.textile
index 6d6ffdc..a0d39e7 100644
--- a/_posts/2009-08-03-rails-script-runner-and-cron.textile
+++ b/_posts/2009-08-03-rails-script-runner-and-cron.textile
@@ -1,26 +1,72 @@
---
published: false
layout: post
title: script/runner and cron
---
h1. {{ page.title }}
p(meta). 03 Aug 2009 - Linthicum, MD
-We have a few process that run every 2 hours. We initially created ruby scripts with loops, which slept for 2 hours. This was quick and easy, and workled fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these process couldnât handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
+h2. Intermittent processes
+We have just started to run some daemon-like processes with check status at various time intervals. We started with a simple ruby script which looped, sleeping between runs. This was quick and easy, and worked fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these processes could not handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
We stared these scripts using commands like this:
-
<pre>
script/runner ping_em_all.rb | tee -a log/ping.log
</pre>
h2. Enter cron.
Google research led me to believe that I simply needed to add an entry to cron, with the exact command arguments we used to start them manually (after removing the loop). With two exceptions:
* we needed to call it with ruby.
* everything needed fully qualified paths.
+Fail. Silently.
+
+h2. Debugging cron
+
+This was my first use of cron, beyond very basic things which had 'just worked'. This wasn't working and I had no indication of why. After some googling and a call to nevans, I was up to speed.
+ #. Check your email to see the output from cron.
+ #. No email. Of course, no email was setup on this dev box.
+ #. Check syslog to see if the command was called. Check. We see the command. We need email.
+ #. Setup email. More googling. Another call (thanks!). "japhr just did this":http://japhr.blogspot.com/2009/08/moving-past-beta.html. sweet. "setup for google apps":http://serverfault.com/questions/54069/how-to-setup-ubuntu-mail-server-with-google-apps. done.
+ #. test: `echo -e "To: Me\nSubject: ssmtp test\n\nssmtp test" | /usr/sbin/ssmtp [email protected]`. Pass.
+ #. Email arrives from cron, indicating issues: no mail-to address. I add it to `crontab -e`: http://gist.github.com/169729
+ #. Email arrives from cron, listing my failed validations. Nice.
+
+ Fail. Rails expects things to be run from RAILS_ROOT. We needed a `cd`.
+
+h2. Enter script/local_runner.sh
+
+We created a simple bash script to change to RAILS_ROOT and run script/runner: http://gist.github.com/169729.
+
+After that, we simply responded to the emails.
+ #. Setup cron to run every minute (*/1).
+ #. First we got to pass with just script/runner.
+ #. Then we added the script.
+ #. It needs $TIPS_ROOT. cron isn't loading my bash.rc and a path with my home dir doesn't belong in /etc, so I add it to crontab -e.
+ #. Then we added the log file.
+ #. There was an issue including the append output to log file command (>>) in crontab, so I converted the log file to an argument. argh.
+
+Pass.
+
+See a working version: http://gist.github.com/169729
+
+
+h2. A brief intro to cron.
+
+cron - daemon to execute scheduled commands
+ * Sends email with output from each run. Note: this is the only way to debug.
+ * Logs to syslog (only indicates that entry was run, no output).
+ * edit: `crontab -e`
+ * list: `crontab -l`
+ * The method to schedule your jobs can be a little confusing at first, but its power and simplicity is soon apparent. Google helps. So do the examples in `cheat cron`.
+
+
+h2. References:
+
+ * `cheat cron`
+ *
|
mattscilipoti/mattscilipoti.github.io
|
153c07f05073d971d0326699f6084157a2203768
|
post AR not blank: rough draft.
|
diff --git a/_posts/2009-08-05-AR-allow-nil-but-not-blank.textile b/_posts/2009-08-05-AR-allow-nil-but-not-blank.textile
new file mode 100644
index 0000000..603dd4a
--- /dev/null
+++ b/_posts/2009-08-05-AR-allow-nil-but-not-blank.textile
@@ -0,0 +1,37 @@
+---
+published: false
+layout: post
+title: ActiveRecord field can be nil, can NOT be blank.
+---
+
+h1. {{ page.title }}
+
+p(meta). 05 Aug 2009 - Bethesda, MD
+
+I have this field: url.
+It should not be blank.
+It can be nil.
+
+How do you spec this?
+
+h2. before_save?
+ spec?
+
+h2. validates_presence_of? :allow_nil => true
+ Nope.
+
+h2. before_validaton
+
+{ highlight ruby }
+describe Antibody, 'validations' do
+ it "should convert blank url to nil" do
+ @it = Factory.build :antibody
+ @it.url = " "
+ @it.url.should be_blank
+ @it.valid?
+ @it.url.should be_nil
+ end
+end
+{ endhighlight }
+
+
|
mattscilipoti/mattscilipoti.github.io
|
86898842cdea0de6395a1417644338ddaaa5d667
|
post stairwell: rough draft
|
diff --git a/_posts/2009-06-12-its-lonely-in-the-stairwell.textile b/_posts/2009-06-12-its-lonely-in-the-stairwell.textile
new file mode 100644
index 0000000..f5cfe17
--- /dev/null
+++ b/_posts/2009-06-12-its-lonely-in-the-stairwell.textile
@@ -0,0 +1,13 @@
+----
+published: false
+layout: post
+title: It's lonely in the stairwell.
+----
+It's clear to me that... Americans ignore stairs.
+Dark, dank, dingy.
+
+h3. For Instance
+
+There is evidence that hotel steps are only used by staff.
+ * above 1st Floor are well used.
+
|
mattscilipoti/mattscilipoti.github.io
|
64775df9b52cafdc95e0e26f5838074a3785f3b7
|
cron post: rough draft
|
diff --git a/_posts/2009-08-03-rails-script-runner-and-cron.textile b/_posts/2009-08-03-rails-script-runner-and-cron.textile
new file mode 100644
index 0000000..6d6ffdc
--- /dev/null
+++ b/_posts/2009-08-03-rails-script-runner-and-cron.textile
@@ -0,0 +1,26 @@
+---
+published: false
+layout: post
+title: script/runner and cron
+---
+
+h1. {{ page.title }}
+
+p(meta). 03 Aug 2009 - Linthicum, MD
+
+We have a few process that run every 2 hours. We initially created ruby scripts with loops, which slept for 2 hours. This was quick and easy, and workled fine until the database connection was severed for second. We had a few different issues, all of which were intermittent, but these process couldnât handle them when their nap was over. We noticed that these activities would have performed fine if they had been started every 20 minutes, instead of sleeping during that time.
+
+We stared these scripts using commands like this:
+
+
+<pre>
+ script/runner ping_em_all.rb | tee -a log/ping.log
+</pre>
+
+h2. Enter cron.
+
+Google research led me to believe that I simply needed to add an entry to cron, with the exact command arguments we used to start them manually (after removing the loop). With two exceptions:
+
+ * we needed to call it with ruby.
+ * everything needed fully qualified paths.
+
|
mattscilipoti/mattscilipoti.github.io
|
7988ddd758bd915b70cbed6c12029d0ef0c6fe1f
|
Facets post: use .update
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index db8ac90..10e4bca 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,56 +1,57 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
<div>
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
</div>
<div>
With:
{% highlight ruby %}config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'{% endhighlight %}
</div>
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
h2. Update (07/29/2009): funky formatting.
+ %(update)Update (07/30/2009): using div as workaround.%
I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
Here's a screenshot:
!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
Argh.
Maybe these guys can help: "github support ticket":http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
diff --git a/css/screen.css b/css/screen.css
index 6994ddf..6c4fa45 100644
--- a/css/screen.css
+++ b/css/screen.css
@@ -1,214 +1,217 @@
/*****************************************************************************/
/*
/* Common
/*
/*****************************************************************************/
/* Global Reset */
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
background-color: white;
font: 13.34px helvetica, arial, clean, sans-serif;
*font-size: small;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-size: 100%;
}
h1 {
margin-bottom: 1em;
}
p {
margin: 1em 0;
}
a {
color: #00a;
}
a:hover {
color: black;
}
a:visited {
color: #a0a;
}
table {
font-size: inherit;
font: 100%;
}
/*****************************************************************************/
/*
/* Home
/*
/*****************************************************************************/
ul.posts {
list-style-type: none;
margin-bottom: 2em;
}
ul.posts li {
line-height: 1.75em;
}
ul.posts span {
color: #aaa;
font-family: Monaco, "Courier New", monospace;
font-size: 80%;
}
dl#repos dd {
font-style: italic;
}
/*****************************************************************************/
/*
/* Site
/*
/*****************************************************************************/
.site {
font-size: 110%;
text-align: justify;
width: 40em;
margin: 3em auto 2em auto;
line-height: 1.5em;
}
.title {
color: #a00;
font-weight: bold;
margin-bottom: 2em;
}
.site .title a {
color: #a00;
text-decoration: none;
}
.site .title a:hover {
color: black;
}
.site .title a.extra {
color: #aaa;
text-decoration: none;
margin-left: 1em;
}
.site .title a.extra:hover {
color: black;
}
.site .meta {
color: #aaa;
}
.site .footer {
font-size: 80%;
color: #666;
border-top: 4px solid #eee;
margin-top: 2em;
overflow: hidden;
}
.site .footer .contact {
float: left;
margin-right: 3em;
}
.site .footer .contact a {
color: #8085C1;
}
.site .footer .rss {
margin-top: 1.1em;
margin-right: -.2em;
float: right;
}
.site .footer .rss img {
border: 0;
}
/*****************************************************************************/
/*
/* Posts
/*
/*****************************************************************************/
#post {
}
/* standard */
#post pre {
border: 1px solid #ddd;
background-color: #eef;
padding: 0 .4em;
}
#post ul,
#post ol {
margin-left: 1.25em;
}
#post code {
border: 1px solid #ddd;
background-color: #eef;
font-size: 95%;
padding: 0 .2em;
}
#post pre code {
border: none;
}
/* terminal */
#post pre.terminal {
border: 1px solid black;
background-color: #333;
color: white;
}
#post pre.terminal code {
background-color: #333;
}
#related {
margin-top: 2em;
}
#related h2 {
margin-bottom: 1em;
}
/******************* Misc ***********
************************************/
.badge {
width: 16px;
height: 16px;
}
.screenshot {
border: 1px solid blue;
}
+.update {
+ font-style: italic;
+}
|
mattscilipoti/mattscilipoti.github.io
|
b7c6eec4abfed1ba912a2a000731ca21a8b45a13
|
Facets post: attempt to fix format (using div)
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index dfcd380..db8ac90 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,52 +1,56 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
+<div>
Replace:
+
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
+</div>
+<div>
With:
-{% highlight ruby %}
-config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
-{% endhighlight %}
+
+{% highlight ruby %}config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'{% endhighlight %}
+</div>
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
h2. Update (07/29/2009): funky formatting.
I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
Here's a screenshot:
!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
Argh.
Maybe these guys can help: "github support ticket":http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
|
mattscilipoti/mattscilipoti.github.io
|
650e4408fec2ba039fe9ad027bfc31006f423def
|
Facets post: url in textile.
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index 490c593..dfcd380 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,52 +1,52 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
With:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
{% endhighlight %}
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
h2. Update (07/29/2009): funky formatting.
I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
Here's a screenshot:
!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
Argh.
-Maybe these guys can help: http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
+Maybe these guys can help: "github support ticket":http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
|
mattscilipoti/mattscilipoti.github.io
|
388077c5ebef872613b974d32ddfbb3b4db5a4e5
|
Facets post: add reference to github support ticket.
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index 05295e0..490c593 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,49 +1,52 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
+
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
With:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
{% endhighlight %}
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
h2. Update (07/29/2009): funky formatting.
I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
Here's a screenshot:
!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
Argh.
+
+Maybe these guys can help: http://support.github.com/discussions/site/701-formatting-issues-for-github-pages-pygment-related
|
mattscilipoti/mattscilipoti.github.io
|
559401c73978e04d54e0e9bb3f3b4a738f4212d8
|
facets post: forgot the image.
|
diff --git a/images/Facets_formatted.png b/images/Facets_formatted.png
new file mode 100644
index 0000000..5e8b0fe
Binary files /dev/null and b/images/Facets_formatted.png differ
|
mattscilipoti/mattscilipoti.github.io
|
09cf772fdc07f22ad86102988a1495dcb05e5c50
|
Facets post: github isn't formatting like local.
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index cf598eb..05295e0 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,42 +1,49 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
With:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
{% endhighlight %}
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
+
+h2. Update (07/29/2009): funky formatting.
+
+I see the code format isn't quite right. It works locally (using `jekyll --pygments --auto --server`).
+Here's a screenshot:
+!(screenshot)/images/Facets_formatted.png(Formatted code screenshot)!
+Argh.
diff --git a/css/screen.css b/css/screen.css
index fcb7ab7..6994ddf 100644
--- a/css/screen.css
+++ b/css/screen.css
@@ -1,210 +1,214 @@
/*****************************************************************************/
/*
/* Common
/*
/*****************************************************************************/
/* Global Reset */
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
background-color: white;
font: 13.34px helvetica, arial, clean, sans-serif;
*font-size: small;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-size: 100%;
}
h1 {
margin-bottom: 1em;
}
p {
margin: 1em 0;
}
a {
color: #00a;
}
a:hover {
color: black;
}
a:visited {
color: #a0a;
}
table {
font-size: inherit;
font: 100%;
}
/*****************************************************************************/
/*
/* Home
/*
/*****************************************************************************/
ul.posts {
list-style-type: none;
margin-bottom: 2em;
}
ul.posts li {
line-height: 1.75em;
}
ul.posts span {
color: #aaa;
font-family: Monaco, "Courier New", monospace;
font-size: 80%;
}
dl#repos dd {
font-style: italic;
}
/*****************************************************************************/
/*
/* Site
/*
/*****************************************************************************/
.site {
font-size: 110%;
text-align: justify;
width: 40em;
margin: 3em auto 2em auto;
line-height: 1.5em;
}
.title {
color: #a00;
font-weight: bold;
margin-bottom: 2em;
}
.site .title a {
color: #a00;
text-decoration: none;
}
.site .title a:hover {
color: black;
}
.site .title a.extra {
color: #aaa;
text-decoration: none;
margin-left: 1em;
}
.site .title a.extra:hover {
color: black;
}
.site .meta {
color: #aaa;
}
.site .footer {
font-size: 80%;
color: #666;
border-top: 4px solid #eee;
margin-top: 2em;
overflow: hidden;
}
.site .footer .contact {
float: left;
margin-right: 3em;
}
.site .footer .contact a {
color: #8085C1;
}
.site .footer .rss {
margin-top: 1.1em;
margin-right: -.2em;
float: right;
}
.site .footer .rss img {
border: 0;
}
/*****************************************************************************/
/*
/* Posts
/*
/*****************************************************************************/
#post {
}
/* standard */
#post pre {
border: 1px solid #ddd;
background-color: #eef;
padding: 0 .4em;
}
#post ul,
#post ol {
margin-left: 1.25em;
}
#post code {
border: 1px solid #ddd;
background-color: #eef;
font-size: 95%;
padding: 0 .2em;
}
#post pre code {
border: none;
}
/* terminal */
#post pre.terminal {
border: 1px solid black;
background-color: #333;
color: white;
}
#post pre.terminal code {
background-color: #333;
}
#related {
margin-top: 2em;
}
#related h2 {
margin-bottom: 1em;
}
/******************* Misc ***********
************************************/
.badge {
width: 16px;
height: 16px;
}
+.screenshot {
+ border: 1px solid blue;
+}
+
|
mattscilipoti/mattscilipoti.github.io
|
b6f0a62e903e65ebbe802bee21aacc711c89e9ec
|
Facets post: attempt to fix formatting.
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
index 461560e..cf598eb 100644
--- a/_posts/2009-07-29-a-facet-of-Facets.textile
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -1,41 +1,42 @@
---
layout: post
title: a facet of Facets
---
h1. {{ page.title }}
p(meta). 29 Jul 2009 - Bethesda, MD
I just updated to Rails 2.3.3 and my controllers screamed:
<pre>
undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
</pre>
Turns out Facets #tap is stomping on another #tap.
h2. Enter facet library loading.
Instead of loading the entire Facets library, load what you need.
I knew this. You knew this. It was just convenient to ignore it.
I'm using Facets for ergo. That's it. No need for the kitchen sink.
Replace:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2'
{% endhighlight %}
+
With:
{% highlight ruby %}
config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
{% endhighlight %}
Done. Error averted. Tiny library loaded.
h2. Now... what about specs?
I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
This issue broke many existing specs, so I feel that I am covered.
Still... it would be nice to have something which identifies this particular issue AND the fix for it.
|
mattscilipoti/mattscilipoti.github.io
|
0389fe684f96837556fa188b4d734ee7871b642e
|
ignore RubyMine project dir (.idea)
|
diff --git a/.gitignore b/.gitignore
index f9d4643..868e353 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,4 @@
_drafts/
_site/
+#IDE
+.idea
|
mattscilipoti/mattscilipoti.github.io
|
9f36e1365b7ae543c67f1ecfe663c97ee60751ec
|
new post: facets
|
diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile
new file mode 100644
index 0000000..461560e
--- /dev/null
+++ b/_posts/2009-07-29-a-facet-of-Facets.textile
@@ -0,0 +1,41 @@
+---
+layout: post
+title: a facet of Facets
+---
+
+h1. {{ page.title }}
+
+p(meta). 29 Jul 2009 - Bethesda, MD
+
+I just updated to Rails 2.3.3 and my controllers screamed:
+<pre>
+undefined local variable or method `set_test_assigns' for #<ActionController::TestResponse:0xb5d0b488>
+/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `instance_eval'
+/home/matt/.gem/ruby/1.8/gems/facets-2.5.2/lib/core/facets/kernel/tap.rb:9:in `tap'
+/home/matt/develop/clients/nih/mpr.ror/trunk/spec/controllers/about_controller_spec.rb:11:
+</pre>
+
+Turns out Facets #tap is stomping on another #tap.
+
+h2. Enter facet library loading.
+
+Instead of loading the entire Facets library, load what you need.
+I knew this. You knew this. It was just convenient to ignore it.
+I'm using Facets for ergo. That's it. No need for the kitchen sink.
+
+Replace:
+{% highlight ruby %}
+config.gem 'facets', :version => '=2.5.2'
+{% endhighlight %}
+With:
+{% highlight ruby %}
+config.gem 'facets', :version => '=2.5.2', :lib => 'facets/kernel/ergo'
+{% endhighlight %}
+
+Done. Error averted. Tiny library loaded.
+
+h2. Now... what about specs?
+
+I prefer to write a failing spec that identifies a "bug" and then write code to make it pass.
+This issue broke many existing specs, so I feel that I am covered.
+Still... it would be nice to have something which identifies this particular issue AND the fix for it.
|
mattscilipoti/mattscilipoti.github.io
|
35859444f120f8ff69c06ec81ede1ae70fbd8420
|
Moving to blog.clearto.me
|
diff --git a/CNAME b/CNAME
new file mode 100644
index 0000000..1be7ee1
--- /dev/null
+++ b/CNAME
@@ -0,0 +1 @@
+blog.clearto.me
diff --git a/_layouts/default.html b/_layouts/default.html
index 0320c68..a2e43c1 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,90 +1,91 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
- <link href="http://feeds.feedburner.com/matt-scilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
+ <link rel="copyright" href="http://creativecommons.org/licenses/by-nc-sa/3.0/" type="text/html;charset=utf-8"/>
+ <link href="http://feeds.feedburner.com/mattscilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
<script src="http://www.google.com/jsapi"></script>
<script>
// from henrik.github.com
google.load("jquery", "1");
google.setOnLoadCallback(function() {
getRepos('mattscilipoti', function(repos) {
if (!repos.length) return;
$('#repos').replaceWith('<dl id="repos"></dl>');
repos.each(function() {
var escapedDesc = $('<div/>').text(this.description).html();
$('#repos').append(
'<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
'<dd>'+escapedDesc+'</dd>'
);
});
});
function getRepos(username, callback) {
$.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
var repos = data.user.repositories;
repos = $.grep(repos, function(r) { return !r.fork });
repos.sort(function(a, b) { return b.watchers - a.watchers });
repos = $(repos);
callback(repos);
});
}
});
</script>
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
</p>
</div>
<div class="rss">
- <a href="http://feeds.feedburner.com/matt-scilipoti">
+ <a href="http://feeds.feedburner.com/mattscilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
diff --git a/atom.xml b/atom.xml
index 39a5ed2..996b5a5 100644
--- a/atom.xml
+++ b/atom.xml
@@ -1,27 +1,27 @@
---
layout: nil
---
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Matt Scilipoti</title>
- <link href="http://blog.clear2.me/atom.xml" rel="self"/>
- <link href="http://blog.clear2.me/"/>
+ <link href="http://blog.clearto.me/atom.xml" rel="self"/>
+ <link href="http://blog.clearto.me/"/>
<updated>{{ site.time | date_to_xmlschema }}</updated>
<id>http://blog.clear2.me/</id>
<author>
<name>Matt Scilipoti</name>
<email>[email protected]</email>
</author>
{% for post in site.posts %}
<entry>
<title>{{ post.title }}</title>
- <link href="http://blog.clear2.me{{ post.url }}"/>
+ <link href="http://blog.clearto.me{{ post.url }}"/>
<updated>{{ post.date | date_to_xmlschema }}</updated>
<id>http://blog.clear2.me{{ post.id }}</id>
<content type="html">{{ post.content | xml_escape }}</content>
</entry>
{% endfor %}
</feed>
|
mattscilipoti/mattscilipoti.github.io
|
8dfcb7ea9b415285c5052c019a47c83ffeb55811
|
Added My Git Repos.
|
diff --git a/_layouts/default.html b/_layouts/default.html
index b1f4641..0320c68 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,57 +1,90 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link href="http://feeds.feedburner.com/matt-scilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
+
+ <script src="http://www.google.com/jsapi"></script>
+ <script>
+ // from henrik.github.com
+ google.load("jquery", "1");
+ google.setOnLoadCallback(function() {
+
+ getRepos('mattscilipoti', function(repos) {
+ if (!repos.length) return;
+
+ $('#repos').replaceWith('<dl id="repos"></dl>');
+ repos.each(function() {
+ var escapedDesc = $('<div/>').text(this.description).html();
+ $('#repos').append(
+ '<dt><a href="'+this.url+'">'+this.name+'</a> ('+this.watchers+')</dt>'+
+ '<dd>'+escapedDesc+'</dd>'
+ );
+ });
+ });
+
+ function getRepos(username, callback) {
+ $.getJSON('http://github.com/api/v1/json/'+username+'?callback=?', function(data) {
+ var repos = data.user.repositories;
+ repos = $.grep(repos, function(r) { return !r.fork });
+ repos.sort(function(a, b) { return b.watchers - a.watchers });
+ repos = $(repos);
+ callback(repos);
+ });
+ }
+ });
+
+ </script>
+
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
<a href='http://www.catb.org/hacker-emblem/'>
<img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/matt-scilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
diff --git a/css/screen.css b/css/screen.css
index e07558a..fcb7ab7 100644
--- a/css/screen.css
+++ b/css/screen.css
@@ -1,207 +1,210 @@
/*****************************************************************************/
/*
/* Common
/*
/*****************************************************************************/
/* Global Reset */
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
background-color: white;
font: 13.34px helvetica, arial, clean, sans-serif;
*font-size: small;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-size: 100%;
}
h1 {
margin-bottom: 1em;
}
p {
margin: 1em 0;
}
a {
color: #00a;
}
a:hover {
color: black;
}
a:visited {
color: #a0a;
}
table {
font-size: inherit;
font: 100%;
}
/*****************************************************************************/
/*
/* Home
/*
/*****************************************************************************/
ul.posts {
list-style-type: none;
margin-bottom: 2em;
}
ul.posts li {
line-height: 1.75em;
}
ul.posts span {
color: #aaa;
font-family: Monaco, "Courier New", monospace;
font-size: 80%;
}
+ dl#repos dd {
+ font-style: italic;
+ }
/*****************************************************************************/
/*
/* Site
/*
/*****************************************************************************/
.site {
font-size: 110%;
text-align: justify;
width: 40em;
margin: 3em auto 2em auto;
line-height: 1.5em;
}
.title {
color: #a00;
font-weight: bold;
margin-bottom: 2em;
}
.site .title a {
color: #a00;
text-decoration: none;
}
.site .title a:hover {
color: black;
}
.site .title a.extra {
color: #aaa;
text-decoration: none;
margin-left: 1em;
}
.site .title a.extra:hover {
color: black;
}
.site .meta {
color: #aaa;
}
.site .footer {
font-size: 80%;
color: #666;
border-top: 4px solid #eee;
margin-top: 2em;
overflow: hidden;
}
.site .footer .contact {
float: left;
margin-right: 3em;
}
.site .footer .contact a {
color: #8085C1;
}
.site .footer .rss {
margin-top: 1.1em;
margin-right: -.2em;
float: right;
}
.site .footer .rss img {
border: 0;
}
/*****************************************************************************/
/*
/* Posts
/*
/*****************************************************************************/
#post {
}
/* standard */
#post pre {
border: 1px solid #ddd;
background-color: #eef;
padding: 0 .4em;
}
#post ul,
#post ol {
margin-left: 1.25em;
}
#post code {
border: 1px solid #ddd;
background-color: #eef;
font-size: 95%;
padding: 0 .2em;
}
#post pre code {
border: none;
}
/* terminal */
#post pre.terminal {
border: 1px solid black;
background-color: #333;
color: white;
}
#post pre.terminal code {
background-color: #333;
}
#related {
margin-top: 2em;
}
#related h2 {
margin-bottom: 1em;
}
/******************* Misc ***********
************************************/
.badge {
width: 16px;
height: 16px;
}
diff --git a/index.html b/index.html
index 5582a11..6592a88 100644
--- a/index.html
+++ b/index.html
@@ -1,25 +1,27 @@
---
layout: default
title: Matt Scilipoti
---
<div id="home">
- <h1>Blog Posts</h1>
+ <h2>Blog Posts</h2>
<ul class="posts">
{% for post in site.posts %}
<li><span>{{ post.date | date_to_string }}</span> » <a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
- <h1>Interviews, Talks, Etc</h1>
+ <h2>Interviews, Talks, Etc</h2>
<ul class="posts">
<li><span>23 Apr 2009</span> » <a href="http://example.com">Example</a></li>
</ul>
- <h1>Open Source Projects</h1>
+ <h3>Open Source Projects</h3>
<ul class="posts">
<li><a href="http://github.com/mojombo/jekyll/">Jekyll:</a> A simple, blog aware, static site generator (used for this site).</li>
<li><a href="http://github.com/mojombo/chronic/">Chronic:</a> Ruby natural language date/time parser</li>
</ul>
+ <h3>My Repos (sources, no forks)</h3>
+ <p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p>
</div>
|
mattscilipoti/mattscilipoti.github.io
|
64eea37bcd24e21746ccaa83190bb3f4d4fba36b
|
blog_engines post: re-wording
|
diff --git a/_posts/2009-06-11-blog_engines_detect.textile b/_posts/2009-06-11-blog_engines_detect.textile
index 7ee9717..87ed9ae 100644
--- a/_posts/2009-06-11-blog_engines_detect.textile
+++ b/_posts/2009-06-11-blog_engines_detect.textile
@@ -1,32 +1,32 @@
---
layout: post
title: blog_engines.detect {|engine| engine.not_engine?}
---
h1. {{ page.title }}
p(meta). 11 Jun 2009 - Reston, VA
-I wanted to start a blog. I didn't want to use a formal engine (too much work) or a dead simple static file system (too lame). Then I found http://pages.github.com/. It was simple, with functionality: <code> for post in site.posts </code>
+I wanted to start a blog. I did not want to use a formal engine (too much work) or a dead simple static file system (too lame). Then I found http://pages.github.com/. It was simple, with functionality: <code> for post in site.posts </code>
h2. Choose.
* http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html
* http://github.com/mojombo/tpw/tree/master
* http://github.com/blog/272-github-pages
h2. Write.
* http://hobix.com/textile/
* http://daringfireball.net/projects/markdown/syntax#overview
* http://github.com/mojombo/jekyll/tree/master
* http://github.com/rtomayko/rdiscount/
Update (2009-06-12 17:18)
-I, incorrectly, created my repo as mattscilipoti instead of mattscilipoti.github.com. After staring at "Page does not exist!" for a few hours, I put in a support request. After a short wait, <a href='http://support.github.com/discussions/repos/907-github-pages-not-found-for-mattscilipotigithubcom'>I was informed that:</a>
+I, incorrectly, created my repo as mattscilipoti instead of mattscilipoti.github.com. After staring at "Page does not exist!" for a few hours, I put in a support request. A short wait and <a href='http://support.github.com/discussions/repos/907-github-pages-not-found-for-mattscilipotigithubcom'>I had my answer:</a>
<blockquote>
"I don't think Pages setup fires on a repo rename, only the initial create. Delete your repo, recreate it, and re-push and you should get a PM that the page has built."
</blockquote>
Edit. Delete. Create. git push. Wait a few minutes. tada. What you see.
|
mattscilipoti/mattscilipoti.github.io
|
7865d03fab820ecba3435bb127a3062e705078ed
|
first post: in Reston, not Laurel.
|
diff --git a/_posts/2009-06-11-blog_engines_detect.textile b/_posts/2009-06-11-blog_engines_detect.textile
index c9ec25c..7ee9717 100644
--- a/_posts/2009-06-11-blog_engines_detect.textile
+++ b/_posts/2009-06-11-blog_engines_detect.textile
@@ -1,32 +1,32 @@
---
layout: post
title: blog_engines.detect {|engine| engine.not_engine?}
---
h1. {{ page.title }}
-p(meta). 11 Jun 2009 - Laurel, MD
+p(meta). 11 Jun 2009 - Reston, VA
I wanted to start a blog. I didn't want to use a formal engine (too much work) or a dead simple static file system (too lame). Then I found http://pages.github.com/. It was simple, with functionality: <code> for post in site.posts </code>
h2. Choose.
* http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html
* http://github.com/mojombo/tpw/tree/master
* http://github.com/blog/272-github-pages
h2. Write.
* http://hobix.com/textile/
* http://daringfireball.net/projects/markdown/syntax#overview
* http://github.com/mojombo/jekyll/tree/master
* http://github.com/rtomayko/rdiscount/
Update (2009-06-12 17:18)
I, incorrectly, created my repo as mattscilipoti instead of mattscilipoti.github.com. After staring at "Page does not exist!" for a few hours, I put in a support request. After a short wait, <a href='http://support.github.com/discussions/repos/907-github-pages-not-found-for-mattscilipotigithubcom'>I was informed that:</a>
<blockquote>
"I don't think Pages setup fires on a repo rename, only the initial create. Delete your repo, recreate it, and re-push and you should get a PM that the page has built."
</blockquote>
Edit. Delete. Create. git push. Wait a few minutes. tada. What you see.
|
mattscilipoti/mattscilipoti.github.io
|
95abd1dd19662a3af5d5855a6107ba5186d778a4
|
layout: smaller badge.
|
diff --git a/_layouts/default.html b/_layouts/default.html
index f3ab48a..b1f4641 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,57 +1,57 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>{{ page.title }}</title>
<meta name="author" content="Matt Scilipoti" />
<link href="http://feeds.feedburner.com/matt-scilipoti" rel="alternate" title="Matt Scilipoti" type="application/atom+xml" />
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="/css/syntax.css" type="text/css" />
<!-- Homepage CSS -->
<link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
</head>
<body>
<div class="site">
<div class="title">
<a href="/">Matt Scilipoti</a>
<a class="extra" href="/">home</a>
</div>
{{ content }}
<div class="footer">
<div class="contact">
<p>
Matt Scilipoti<br />
Founder of <a href="http://possiamo.com/">Possiamo Consulting LLC</a><br />
[email protected]
-<a id='hacker_badge' class = 'badge' href='http://www.catb.org/hacker-emblem/'>
-<img src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
+<a href='http://www.catb.org/hacker-emblem/'>
+ <img id='hacker_badqe' class='badge' src='http://www.catb.org/hacker-emblem/glider.png' alt='hacker emblem' /></a>
</p>
</div>
<div class="contact">
<p>
<a href="http://github.com/mattscilipoti/">github.com/mojombo</a><br />
<a href="http://identi.ca/mattscilipoti/">identi.ca/mattscilipoti</a><br />
</p>
</div>
<div class="rss">
<a href="http://feeds.feedburner.com/matt-scilipoti">
<img src="/images/rss.png" alt="Subscribe to RSS Feed" />
</a>
</div>
</div>
</div>
<a href="http://github.com/mattscilipoti"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a>
</body>
</html>
|
robolson/simplesem
|
39b51c9c108e16d54f49b0f0e7c376593d6475fd
|
Releasing version 0.1.4
|
diff --git a/Manifest b/Manifest
index 578e0f2..b0fd413 100644
--- a/Manifest
+++ b/Manifest
@@ -1,17 +1,18 @@
-bin/simplesem
-test/test_helper.rb
-test/simplesem_test.rb
-sample_programs/case-statement.txt
-sample_programs/while-loop.txt
-sample_programs/gcd.txt
-sample_programs/hello-world.txt
-simplesem.gemspec
LICENSE
+Manifest
+README.textile
Rakefile
+bin/simplesem
lib/simplesem.rb
-lib/simplesem/arithmetic_node_classes.rb
lib/simplesem/arithmetic.treetop
+lib/simplesem/arithmetic_node_classes.rb
lib/simplesem/simple_sem.treetop
lib/simplesem/simplesem_program.rb
-README.textile
-Manifest
+lib/simplesem/version.rb
+lib/trollop/trollop.rb
+sample_programs/case-statement.txt
+sample_programs/gcd.txt
+sample_programs/hello-world.txt
+sample_programs/while-loop.txt
+test/simplesem_test.rb
+test/test_helper.rb
diff --git a/README.textile b/README.textile
index 463a2c7..eca61a9 100644
--- a/README.textile
+++ b/README.textile
@@ -1,152 +1,152 @@
h1. SIMPLESEM Interpreter
Author: "Rob Olson":http://thinkingdigitally.com
h2. Description
Interpreter for the SIMPLESEM language.
SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
bc. $ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
bc. $ simplesem simplesem_file.txt
h3. Command Line Options
The simplesem executable accepts a couple optional command line options which will display the values in the Data array at the time the program exits.
-pre. --help Print help message
- --inspect Print values in the data array on exit
- --inspect-history Print values in the data array with change history on exit
+pre. --help Print help message
+--inspect Print values in the data array on exit
+--inspect-history Print values in the data array with change history on exit
Use @--inspect@ if you only want to see the ending value at each position in the Data array, otherwise use @--inspect-history@ to see each data location's history.
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
bc. set 0, 4 * 2
Assign the value stored at location 0 into location 2:
bc. set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
bc. set write, D[0]
Get input from the user and store it at location 1:
bc. set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
bc. jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
bc. jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Comments
SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
bc. // This is line number 0.
- set write, "foo" // a comment after a statement
+set write, "foo" // a comment after a statement
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
bc. set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
bc. set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
bc. set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre>
<code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</code>
</pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
-<pre>
-<code>
+<pre><code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
-</code>
-</pre>
+</code></pre>
-pre.. $ simplesem --inspect-history sample_programs/gcd.txt
+Running the above program on the command line will give the following output:
+<pre>
+$ simplesem --inspect-history sample_programs/gcd.txt
input: 15
input: 35
5
DATA:
0: [15, 10, 5]
1: [35, 20, 5]
2: [4]
-
+</pre>
diff --git a/Rakefile b/Rakefile
index 56ba983..44ecba3 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,11 +1,11 @@
require 'rake'
require 'echoe'
-Echoe.new('simplesem', '0.1.3') do |p|
+Echoe.new('simplesem', '0.1.4') do |p|
p.summary = "SIMPLESEM Interpreter"
p.description = "Interpreter for parsing and executing SIMPLESEM programs"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
p.email = "[email protected]"
p.runtime_dependencies = ["treetop >=1.2.4"]
end
diff --git a/lib/simplesem/version.rb b/lib/simplesem/version.rb
index 82d081e..86612b2 100644
--- a/lib/simplesem/version.rb
+++ b/lib/simplesem/version.rb
@@ -1,5 +1,5 @@
module SimpleSem
unless defined? SimpleSem::VERSION
- VERSION = '0.1.3'
+ VERSION = '0.1.4'
end
end
diff --git a/simplesem.gemspec b/simplesem.gemspec
index 5a8513a..b9316e8 100644
--- a/simplesem.gemspec
+++ b/simplesem.gemspec
@@ -1,37 +1,36 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{simplesem}
- s.version = "0.1.3"
+ s.version = "0.1.4"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Rob Olson"]
- s.date = %q{2009-04-01}
+ s.date = %q{2009-09-27}
s.default_executable = %q{simplesem}
- s.description = %q{SIMPLESEM Interpreter}
- s.email = %q{[email protected]}
+ s.description = %q{Interpreter for parsing and executing SIMPLESEM programs}
+ s.email = %q{[email protected]}
s.executables = ["simplesem"]
- s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
- s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
- s.has_rdoc = true
+ s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem/version.rb", "lib/trollop/trollop.rb"]
+ s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem/version.rb", "lib/trollop/trollop.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "test/simplesem_test.rb", "test/test_helper.rb"]
s.homepage = %q{http://github.com/robolson/simplesem}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Simplesem", "--main", "README.textile"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{simplesem}
- s.rubygems_version = %q{1.3.1}
+ s.rubygems_version = %q{1.3.5}
s.summary = %q{SIMPLESEM Interpreter}
- s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
+ s.test_files = ["test/test_helper.rb", "test/simplesem_test.rb"]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
- s.specification_version = 2
+ s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<treetop>, [">= 1.2.4"])
else
s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
else
s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
end
|
robolson/simplesem
|
130b723df4e6410fad13139cb4b228887b857b61
|
Use trollop for command line parsing
|
diff --git a/README.textile b/README.textile
index c6f4c02..463a2c7 100644
--- a/README.textile
+++ b/README.textile
@@ -1,152 +1,152 @@
h1. SIMPLESEM Interpreter
Author: "Rob Olson":http://thinkingdigitally.com
h2. Description
Interpreter for the SIMPLESEM language.
SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
bc. $ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
bc. $ simplesem simplesem_file.txt
h3. Command Line Options
-The simplesem executable accepts a couple command line options which will display the values in the Data array at the time the program exits.
+The simplesem executable accepts a couple optional command line options which will display the values in the Data array at the time the program exits.
-pre. -h Print help message
- -t Print Data array on exit
- -v Print Data array with change history on exit. Supersedes -t if it is also specified.
+pre. --help Print help message
+ --inspect Print values in the data array on exit
+ --inspect-history Print values in the data array with change history on exit
-Use -t if you only want to see the ending value at each position in the Data array, otherwise use -v to see each data location's history. If neither -t or -v is used the program will not display the data array.
+Use @--inspect@ if you only want to see the ending value at each position in the Data array, otherwise use @--inspect-history@ to see each data location's history.
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
bc. set 0, 4 * 2
Assign the value stored at location 0 into location 2:
bc. set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
bc. set write, D[0]
Get input from the user and store it at location 1:
bc. set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
bc. jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
bc. jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Comments
SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
bc. // This is line number 0.
set write, "foo" // a comment after a statement
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
bc. set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
bc. set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
bc. set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre>
<code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</code>
</pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<pre>
<code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</code>
</pre>
-pre.. $ simplesem -v sample_programs/gcd.txt
+pre.. $ simplesem --inspect-history sample_programs/gcd.txt
input: 15
input: 35
5
DATA:
0: [15, 10, 5]
1: [35, 20, 5]
2: [4]
diff --git a/bin/simplesem b/bin/simplesem
index c4e3c75..ab46d58 100755
--- a/bin/simplesem
+++ b/bin/simplesem
@@ -1,60 +1,36 @@
#!/usr/bin/env ruby
-#= Overview
-#
-# Interpreter for the SIMPLESEM language
-#
-#= Usage
-#
-# simplesem [-t|-v] filename
-#
-# Options:
-# -h Print this message
-# -t Print Data array on exit
-# -v Print Data array with change history on exit. Supersedes -t
-# if it is also specified.
-#
-
-require 'rdoc/usage'
-require 'getoptlong'
# The gem packager will properly add the lib dir to LOAD_PATH when
# executing the gem but load path manipulation is needed during development
unless $LOAD_PATH.include?(File.expand_path('../../lib', __FILE__))
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
end
-require 'simplesem' # must execute after manipulating the load path
-
-opts = GetoptLong.new(
- [ '-h', '--help', GetoptLong::NO_ARGUMENT ],
- [ '-t', GetoptLong::NO_ARGUMENT ],
- [ '-v', GetoptLong::NO_ARGUMENT ]
-)
-
-verbosity = 0 # by default do not print what is in Data
-
-opts.each do |opt, arg|
- case opt
- when '-h'
- RDoc::usage
- when '-t'
- verbosity = 1
- when '-v'
- verbosity = 2
- end
-end
+require 'simplesem'
+require 'trollop/trollop'
+
+opts = Trollop::options do
+ version SimpleSem::VERSION
+ banner <<-EOS
+Interpreter for the SIMPLESEM language by Rob Olson
+
+Usage: simplesem [options] filename
-if ARGV.length != 1
- puts "Missing filename argument (try --help)"
- exit 0
+Options:
+EOS
+
+ opt :inspect, "Print values in the data array on exit"
+ opt :inspect_history, "Print values in the data array with change history on exit"
+ conflicts :inspect, :inspect_history
end
+Trollop::die "must specify a single filename" if ARGV.length != 1
+
ssp = SimpleSem::Program.new(ARGV.shift)
ssp.run
-case verbosity
-when 1
+if opts[:inspect_history]
puts "\nDATA: \n" + ssp.inspect_data
-when 2
+elsif opts[:inspect]
puts "\nDATA: \n" + ssp.inspect_data_with_history
end
diff --git a/lib/trollop/trollop.rb b/lib/trollop/trollop.rb
new file mode 100644
index 0000000..1f182d2
--- /dev/null
+++ b/lib/trollop/trollop.rb
@@ -0,0 +1,695 @@
+## lib/trollop.rb -- trollop command-line processing library
+## Author:: William Morgan (mailto: [email protected])
+## Copyright:: Copyright 2007 William Morgan
+## License:: GNU GPL version 2
+
+module Trollop
+
+VERSION = "1.10.2"
+
+## Thrown by Parser in the event of a commandline error. Not needed if
+## you're using the Trollop::options entry.
+class CommandlineError < StandardError; end
+
+## Thrown by Parser if the user passes in '-h' or '--help'. Handled
+## automatically by Trollop#options.
+class HelpNeeded < StandardError; end
+
+## Thrown by Parser if the user passes in '-h' or '--version'. Handled
+## automatically by Trollop#options.
+class VersionNeeded < StandardError; end
+
+## Regex for floating point numbers
+FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))$/
+
+## Regex for parameters
+PARAM_RE = /^-(-|\.$|[^\d\.])/
+
+## The commandline parser. In typical usage, the methods in this class
+## will be handled internally by Trollop::options. In this case, only the
+## #opt, #banner and #version, #depends, and #conflicts methods will
+## typically be called.
+##
+## If it's necessary to instantiate this class (for more complicated
+## argument-parsing situations), be sure to call #parse to actually
+## produce the output hash.
+class Parser
+
+ ## The set of values that indicate a flag option when passed as the
+ ## +:type+ parameter of #opt.
+ FLAG_TYPES = [:flag, :bool, :boolean]
+
+ ## The set of values that indicate a single-parameter option when
+ ## passed as the +:type+ parameter of #opt.
+ ##
+ ## A value of +io+ corresponds to a readable IO resource, including
+ ## a filename, URI, or the strings 'stdin' or '-'.
+ SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io]
+
+ ## The set of values that indicate a multiple-parameter option when
+ ## passed as the +:type+ parameter of #opt.
+ MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios]
+
+ ## The complete set of legal values for the +:type+ parameter of #opt.
+ TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
+
+ INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc:
+
+ ## The values from the commandline that were not interpreted by #parse.
+ attr_reader :leftovers
+
+ ## The complete configuration hashes for each option. (Mainly useful
+ ## for testing.)
+ attr_reader :specs
+
+ ## Initializes the parser, and instance-evaluates any block given.
+ def initialize *a, &b
+ @version = nil
+ @leftovers = []
+ @specs = {}
+ @long = {}
+ @short = {}
+ @order = []
+ @constraints = []
+ @stop_words = []
+ @stop_on_unknown = false
+
+ #instance_eval(&b) if b # can't take arguments
+ cloaker(&b).bind(self).call(*a) if b
+ end
+
+ ## Define an option. +name+ is the option name, a unique identifier
+ ## for the option that you will use internally, which should be a
+ ## symbol or a string. +desc+ is a string description which will be
+ ## displayed in help messages.
+ ##
+ ## Takes the following optional arguments:
+ ##
+ ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
+ ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
+ ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
+ ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
+ ## [+:required+] If set to +true+, the argument must be provided on the commandline.
+ ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
+ ##
+ ## Note that there are two types of argument multiplicity: an argument
+ ## can take multiple values, e.g. "--arg 1 2 3". An argument can also
+ ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
+ ##
+ ## Arguments that take multiple values should have a +:type+ parameter
+ ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
+ ## value of an array of the correct type (e.g. [String]). The
+ ## value of this argument will be an array of the parameters on the
+ ## commandline.
+ ##
+ ## Arguments that can occur multiple times should be marked with
+ ## +:multi+ => +true+. The value of this argument will also be an array.
+ ##
+ ## These two attributes can be combined (e.g. +:type+ => +:strings+,
+ ## +:multi+ => +true+), in which case the value of the argument will be
+ ## an array of arrays.
+ ##
+ ## There's one ambiguous case to be aware of: when +:multi+: is true and a
+ ## +:default+ is set to an array (of something), it's ambiguous whether this
+ ## is a multi-value argument as well as a multi-occurrence argument.
+ ## In thise case, Trollop assumes that it's not a multi-value argument.
+ ## If you want a multi-value, multi-occurrence argument with a default
+ ## value, you must specify +:type+ as well.
+
+ def opt name, desc="", opts={}
+ raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
+
+ ## fill in :type
+ opts[:type] = # normalize
+ case opts[:type]
+ when :boolean, :bool; :flag
+ when :integer; :int
+ when :integers; :ints
+ when :double; :float
+ when :doubles; :floats
+ when Class
+ case opts[:type].to_s # sigh... there must be a better way to do this
+ when 'TrueClass', 'FalseClass'; :flag
+ when 'String'; :string
+ when 'Integer'; :int
+ when 'Float'; :float
+ when 'IO'; :io
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
+ end
+ when nil; nil
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
+ opts[:type]
+ end
+
+ ## for options with :multi => true, an array default doesn't imply
+ ## a multi-valued argument. for that you have to specify a :type
+ ## as well. (this is how we disambiguate an ambiguous situation;
+ ## see the docs for Parser#opt for details.)
+ disambiguated_default =
+ if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
+ opts[:default].first
+ else
+ opts[:default]
+ end
+
+ type_from_default =
+ case disambiguated_default
+ when Integer; :int
+ when Numeric; :float
+ when TrueClass, FalseClass; :flag
+ when String; :string
+ when IO; :io
+ when Array
+ if opts[:default].empty?
+ raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
+ end
+ case opts[:default][0] # the first element determines the types
+ when Integer; :ints
+ when Numeric; :floats
+ when String; :strings
+ when IO; :ios
+ else
+ raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
+ end
+ when nil; nil
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
+ end
+
+ raise ArgumentError, ":type specification and default type don't match" if opts[:type] && type_from_default && opts[:type] != type_from_default
+
+ opts[:type] = opts[:type] || type_from_default || :flag
+
+ ## fill in :long
+ opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
+ opts[:long] =
+ case opts[:long]
+ when /^--([^-].*)$/
+ $1
+ when /^[^-]/
+ opts[:long]
+ else
+ raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
+ end
+ raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
+
+ ## fill in :short
+ opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
+ opts[:short] =
+ case opts[:short]
+ when nil
+ c = opts[:long].split(//).find { |c| c !~ INVALID_SHORT_ARG_REGEX && [email protected]?(c) }
+ raise ArgumentError, "can't generate a short option name for #{opts[:long].inspect}: out of unique characters" unless c
+ c
+ when /^-(.)$/
+ $1
+ when /^.$/
+ opts[:short]
+ when :none
+ nil
+ else
+ raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
+ end
+ if opts[:short]
+ raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
+ raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
+ end
+
+ ## fill in :default for flags
+ opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
+
+ ## autobox :default for :multi (multi-occurrence) arguments
+ opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
+
+ ## fill in :multi
+ opts[:multi] ||= false
+
+ opts[:desc] ||= desc
+ @long[opts[:long]] = name
+ @short[opts[:short]] = name if opts[:short]
+ @specs[name] = opts
+ @order << [:opt, name]
+ end
+
+ ## Sets the version string. If set, the user can request the version
+ ## on the commandline. Should probably be of the form "<program name>
+ ## <version number>".
+ def version s=nil; @version = s if s; @version end
+
+ ## Adds text to the help display. Can be interspersed with calls to
+ ## #opt to build a multi-section help page.
+ def banner s; @order << [:text, s] end
+ alias :text :banner
+
+ ## Marks two (or more!) options as requiring each other. Only handles
+ ## undirected (i.e., mutual) dependencies. Directed dependencies are
+ ## better modeled with Trollop::die.
+ def depends *syms
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
+ @constraints << [:depends, syms]
+ end
+
+ ## Marks two (or more!) options as conflicting.
+ def conflicts *syms
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
+ @constraints << [:conflicts, syms]
+ end
+
+ ## Defines a set of words which cause parsing to terminate when
+ ## encountered, such that any options to the left of the word are
+ ## parsed as usual, and options to the right of the word are left
+ ## intact.
+ ##
+ ## A typical use case would be for subcommand support, where these
+ ## would be set to the list of subcommands. A subsequent Trollop
+ ## invocation would then be used to parse subcommand options, after
+ ## shifting the subcommand off of ARGV.
+ def stop_on *words
+ @stop_words = [*words].flatten
+ end
+
+ ## Similar to #stop_on, but stops on any unknown word when encountered
+ ## (unless it is a parameter for an argument). This is useful for
+ ## cases where you don't know the set of subcommands ahead of time,
+ ## i.e., without first parsing the global options.
+ def stop_on_unknown
+ @stop_on_unknown = true
+ end
+
+ ## yield successive arg, parameter pairs
+ def each_arg args # :nodoc:
+ remains = []
+ i = 0
+
+ until i >= args.length
+ if @stop_words.member? args[i]
+ remains += args[i .. -1]
+ return remains
+ end
+ case args[i]
+ when /^--$/ # arg terminator
+ remains += args[(i + 1) .. -1]
+ return remains
+ when /^--(\S+?)=(\S+)$/ # long argument with equals
+ yield "--#{$1}", [$2]
+ i += 1
+ when /^--(\S+)$/ # long argument
+ params = collect_argument_parameters(args, i + 1)
+ unless params.empty?
+ num_params_taken = yield args[i], params
+ unless num_params_taken
+ if @stop_on_unknown
+ remains += args[i + 1 .. -1]
+ return remains
+ else
+ remains += params
+ end
+ end
+ i += 1 + num_params_taken
+ else # long argument no parameter
+ yield args[i], nil
+ i += 1
+ end
+ when /^-(\S+)$/ # one or more short arguments
+ shortargs = $1.split(//)
+ shortargs.each_with_index do |a, j|
+ if j == (shortargs.length - 1)
+ params = collect_argument_parameters(args, i + 1)
+ unless params.empty?
+ num_params_taken = yield "-#{a}", params
+ unless num_params_taken
+ if @stop_on_unknown
+ remains += args[i + 1 .. -1]
+ return remains
+ else
+ remains += params
+ end
+ end
+ i += 1 + num_params_taken
+ else # argument no parameter
+ yield "-#{a}", nil
+ i += 1
+ end
+ else
+ yield "-#{a}", nil
+ end
+ end
+ else
+ if @stop_on_unknown
+ remains += args[i .. -1]
+ return remains
+ else
+ remains << args[i]
+ i += 1
+ end
+ end
+ end
+
+ remains
+ end
+
+ ## Parses the commandline. Typically called by Trollop::options.
+ def parse cmdline=ARGV
+ vals = {}
+ required = {}
+
+ opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
+ opt :help, "Show this message" unless @specs[:help] || @long["help"]
+
+ @specs.each do |sym, opts|
+ required[sym] = true if opts[:required]
+ vals[sym] = opts[:default]
+ end
+
+ ## resolve symbols
+ given_args = {}
+ @leftovers = each_arg cmdline do |arg, params|
+ sym =
+ case arg
+ when /^-([^-])$/
+ @short[$1]
+ when /^--([^-]\S*)$/
+ @long[$1]
+ else
+ raise CommandlineError, "invalid argument syntax: '#{arg}'"
+ end
+ raise CommandlineError, "unknown argument '#{arg}'" unless sym
+
+ if given_args.include?(sym) && !@specs[sym][:multi]
+ raise CommandlineError, "option '#{arg}' specified multiple times"
+ end
+
+ given_args[sym] ||= {}
+
+ given_args[sym][:arg] = arg
+ given_args[sym][:params] ||= []
+
+ # The block returns the number of parameters taken.
+ num_params_taken = 0
+
+ unless params.nil?
+ if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
+ given_args[sym][:params] << params[0, 1] # take the first parameter
+ num_params_taken = 1
+ elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
+ given_args[sym][:params] << params # take all the parameters
+ num_params_taken = params.size
+ end
+ end
+
+ num_params_taken
+ end
+
+ ## check for version and help args
+ raise VersionNeeded if given_args.include? :version
+ raise HelpNeeded if given_args.include? :help
+
+ ## check constraint satisfaction
+ @constraints.each do |type, syms|
+ constraint_sym = syms.find { |sym| given_args[sym] }
+ next unless constraint_sym
+
+ case type
+ when :depends
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
+ when :conflicts
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
+ end
+ end
+
+ required.each do |sym, val|
+ raise CommandlineError, "option '#{sym}' must be specified" unless given_args.include? sym
+ end
+
+ ## parse parameters
+ given_args.each do |sym, given_data|
+ arg = given_data[:arg]
+ params = given_data[:params]
+
+ opts = @specs[sym]
+ raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
+
+ case opts[:type]
+ when :flag
+ vals[sym] = !opts[:default]
+ when :int, :ints
+ vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
+ when :float, :floats
+ vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
+ when :string, :strings
+ vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
+ when :io, :ios
+ vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
+ end
+
+ if SINGLE_ARG_TYPES.include?(opts[:type])
+ unless opts[:multi] # single parameter
+ vals[sym] = vals[sym][0][0]
+ else # multiple options, each with a single parameter
+ vals[sym] = vals[sym].map { |p| p[0] }
+ end
+ elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
+ vals[sym] = vals[sym][0] # single option, with multiple parameters
+ end
+ # else: multiple options, with multiple parameters
+ end
+
+ ## allow openstruct-style accessors
+ class << vals
+ def method_missing(m, *args)
+ self[m] || self[m.to_s]
+ end
+ end
+ vals
+ end
+
+ def parse_integer_parameter param, arg #:nodoc:
+ raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^\d+$/
+ param.to_i
+ end
+
+ def parse_float_parameter param, arg #:nodoc:
+ raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
+ param.to_f
+ end
+
+ def parse_io_parameter param, arg #:nodoc:
+ case param
+ when /^(stdin|-)$/i; $stdin
+ else
+ require 'open-uri'
+ begin
+ open param
+ rescue SystemCallError => e
+ raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
+ end
+ end
+ end
+
+ def collect_argument_parameters args, start_at #:nodoc:
+ params = []
+ pos = start_at
+ while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
+ params << args[pos]
+ pos += 1
+ end
+ params
+ end
+
+ def width #:nodoc:
+ @width ||=
+ if $stdout.tty?
+ begin
+ require 'curses'
+ Curses::init_screen
+ x = Curses::cols
+ Curses::close_screen
+ x
+ rescue Exception
+ 80
+ end
+ else
+ 80
+ end
+ end
+
+ ## Print the help message to +stream+.
+ def educate stream=$stdout
+ width # just calculate it now; otherwise we have to be careful not to
+ # call this unless the cursor's at the beginning of a line.
+
+ left = {}
+ @specs.each do |name, spec|
+ left[name] = "--#{spec[:long]}" +
+ (spec[:short] ? ", -#{spec[:short]}" : "") +
+ case spec[:type]
+ when :flag; ""
+ when :int; " <i>"
+ when :ints; " <i+>"
+ when :string; " <s>"
+ when :strings; " <s+>"
+ when :float; " <f>"
+ when :floats; " <f+>"
+ when :io; " <filename/uri>"
+ when :ios; " <filename/uri+>"
+ end
+ end
+
+ leftcol_width = left.values.map { |s| s.length }.max || 0
+ rightcol_start = leftcol_width + 6 # spaces
+
+ unless @order.size > 0 && @order.first.first == :text
+ stream.puts "#@version\n" if @version
+ stream.puts "Options:"
+ end
+
+ @order.each do |what, opt|
+ if what == :text
+ stream.puts wrap(opt)
+ next
+ end
+
+ spec = @specs[opt]
+ stream.printf " %#{leftcol_width}s: ", left[opt]
+ desc = spec[:desc] + begin
+ default_s = case spec[:default]
+ when $stdout; "<stdout>"
+ when $stdin; "<stdin>"
+ when $stderr; "<stderr>"
+ when Array
+ spec[:default].join(", ")
+ else
+ spec[:default].to_s
+ end
+
+ if spec[:default]
+ if spec[:desc] =~ /\.$/
+ " (Default: #{default_s})"
+ else
+ " (default: #{default_s})"
+ end
+ else
+ ""
+ end
+ end
+ stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
+ end
+ end
+
+ def wrap_line str, opts={} # :nodoc:
+ prefix = opts[:prefix] || 0
+ width = opts[:width] || (self.width - 1)
+ start = 0
+ ret = []
+ until start > str.length
+ nextt =
+ if start + width >= str.length
+ str.length
+ else
+ x = str.rindex(/\s/, start + width)
+ x = str.index(/\s/, start) if x && x < start
+ x || str.length
+ end
+ ret << (ret.empty? ? "" : " " * prefix) + str[start ... nextt]
+ start = nextt + 1
+ end
+ ret
+ end
+
+ def wrap str, opts={} # :nodoc:
+ if str == ""
+ [""]
+ else
+ str.split("\n").map { |s| wrap_line s, opts }.flatten
+ end
+ end
+
+ ## instance_eval but with ability to handle block arguments
+ ## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html
+ def cloaker &b #:nodoc:
+ (class << self; self; end).class_eval do
+ define_method :cloaker_, &b
+ meth = instance_method :cloaker_
+ remove_method :cloaker_
+ meth
+ end
+ end
+end
+
+## The top-level entry method into Trollop. Creates a Parser object,
+## passes the block to it, then parses +args+ with it, handling any
+## errors or requests for help or version information appropriately (and
+## then exiting). Modifies +args+ in place. Returns a hash of option
+## values.
+##
+## The block passed in should contain zero or more calls to +opt+
+## (Parser#opt), zero or more calls to +text+ (Parser#text), and
+## probably a call to +version+ (Parser#version).
+##
+## Example:
+##
+## require 'trollop'
+## opts = Trollop::options do
+## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
+## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
+## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
+## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
+## end
+##
+## p opts # returns a hash: { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
+##
+## See more examples at http://trollop.rubyforge.org.
+def options args = ARGV, *a, &b
+ @p = Parser.new(*a, &b)
+ begin
+ vals = @p.parse args
+ args.clear
+ @p.leftovers.each { |l| args << l }
+ vals
+ rescue CommandlineError => e
+ $stderr.puts "Error: #{e.message}."
+ $stderr.puts "Try --help for help."
+ exit(-1)
+ rescue HelpNeeded
+ @p.educate
+ exit
+ rescue VersionNeeded
+ puts @p.version
+ exit
+ end
+end
+
+## Informs the user that their usage of 'arg' was wrong, as detailed by
+## 'msg', and dies. Example:
+##
+## options do
+## opt :volume, :default => 0.0
+## end
+##
+## die :volume, "too loud" if opts[:volume] > 10.0
+## die :volume, "too soft" if opts[:volume] < 0.1
+##
+## In the one-argument case, simply print that message, a notice
+## about -h, and die. Example:
+##
+## options do
+## opt :whatever # ...
+## end
+##
+## Trollop::die "need at least one filename" if ARGV.empty?
+def die arg, msg=nil
+ if msg
+ $stderr.puts "Error: argument --#{@p.specs[arg][:long]} #{msg}."
+ else
+ $stderr.puts "Error: #{arg}."
+ end
+ $stderr.puts "Try --help for help."
+ exit(-1)
+end
+
+module_function :options, :die
+
+end # module
+
|
robolson/simplesem
|
609a425db4f850e947eb9fa23fc047cb0de12138
|
Use proper textile formating in README
|
diff --git a/README.textile b/README.textile
index fa708b0..c6f4c02 100644
--- a/README.textile
+++ b/README.textile
@@ -1,154 +1,152 @@
h1. SIMPLESEM Interpreter
Author: "Rob Olson":http://thinkingdigitally.com
h2. Description
Interpreter for the SIMPLESEM language.
SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs.
-This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
+This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
- $ sudo gem install robolson-simplesem
+bc. $ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
- $ simplesem simplesem_file.txt
+bc. $ simplesem simplesem_file.txt
h3. Command Line Options
The simplesem executable accepts a couple command line options which will display the values in the Data array at the time the program exits.
- -h Print help message
+pre. -h Print help message
-t Print Data array on exit
-v Print Data array with change history on exit. Supersedes -t if it is also specified.
Use -t if you only want to see the ending value at each position in the Data array, otherwise use -v to see each data location's history. If neither -t or -v is used the program will not display the data array.
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
- set 0, 4 * 2
+bc. set 0, 4 * 2
Assign the value stored at location 0 into location 2:
- set 2, D[0]
+bc. set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
- set write, D[0]
+bc. set write, D[0]
Get input from the user and store it at location 1:
- set 0, read
+bc. set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
- jump D[0]
+bc. jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
- jumpt 7, D[1] = D[0]
+bc. jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Comments
SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
- // This is line number 0.
- set write, "foo" // a comment after a statement
+bc. // This is line number 0.
+ set write, "foo" // a comment after a statement
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
- set 5, D[D[0]+1]
+bc. set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
- set D[10], D[15]
+bc. set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
- set 1, 2+3*4
+bc. set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre>
<code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</code>
</pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<pre>
<code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</code>
</pre>
-<pre>
-$ simplesem -v sample_programs/gcd.txt
+pre.. $ simplesem -v sample_programs/gcd.txt
input: 15
input: 35
5
-DATA:
+DATA:
0: [15, 10, 5]
1: [35, 20, 5]
2: [4]
-</pre>
|
robolson/simplesem
|
4880d123faaa45376e121b4c5eea35c46124aaf8
|
Namespace all classes inside of a SimpleSem module.
|
diff --git a/bin/simplesem b/bin/simplesem
index 6c2d501..c4e3c75 100755
--- a/bin/simplesem
+++ b/bin/simplesem
@@ -1,59 +1,60 @@
#!/usr/bin/env ruby
#= Overview
#
# Interpreter for the SIMPLESEM language
#
#= Usage
#
# simplesem [-t|-v] filename
#
# Options:
# -h Print this message
# -t Print Data array on exit
# -v Print Data array with change history on exit. Supersedes -t
# if it is also specified.
#
require 'rdoc/usage'
require 'getoptlong'
# The gem packager will properly add the lib dir to LOAD_PATH when
# executing the gem but load path manipulation is needed during development
unless $LOAD_PATH.include?(File.expand_path('../../lib', __FILE__))
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
end
require 'simplesem' # must execute after manipulating the load path
opts = GetoptLong.new(
[ '-h', '--help', GetoptLong::NO_ARGUMENT ],
[ '-t', GetoptLong::NO_ARGUMENT ],
[ '-v', GetoptLong::NO_ARGUMENT ]
)
verbosity = 0 # by default do not print what is in Data
opts.each do |opt, arg|
case opt
- when '-h'
- RDoc::usage
- when '-t'
- verbosity = 1
- when '-v'
- verbosity = 2
+ when '-h'
+ RDoc::usage
+ when '-t'
+ verbosity = 1
+ when '-v'
+ verbosity = 2
end
end
if ARGV.length != 1
puts "Missing filename argument (try --help)"
exit 0
end
-ssp = SimpleSemProgram.new(ARGV.shift)
+ssp = SimpleSem::Program.new(ARGV.shift)
ssp.run
-if (verbosity == 1)
+case verbosity
+when 1
puts "\nDATA: \n" + ssp.inspect_data
-elsif (verbosity == 2)
+when 2
puts "\nDATA: \n" + ssp.inspect_data_with_history
end
diff --git a/lib/simplesem.rb b/lib/simplesem.rb
index db68f77..0e1be0e 100644
--- a/lib/simplesem.rb
+++ b/lib/simplesem.rb
@@ -1 +1,2 @@
+require 'simplesem/version'
require 'simplesem/simplesem_program'
diff --git a/lib/simplesem/arithmetic.treetop b/lib/simplesem/arithmetic.treetop
index 1d0b0b4..04fd9b4 100644
--- a/lib/simplesem/arithmetic.treetop
+++ b/lib/simplesem/arithmetic.treetop
@@ -1,99 +1,101 @@
-grammar Arithmetic
- rule expression
- comparative / additive
- end
-
- rule comparative
- operand_1:additive space operator:comparison_op space operand_2:additive <BinaryOperation>
- end
-
- rule comparison_op
- '>=' {
- def apply(a, b)
- a >= b
- end
- }
- /
- '<=' {
- def apply(a, b)
- a <= b
- end
- }
- /
- '>' {
- def apply(a, b)
- a > b
- end
- }
- /
- '<' {
- def apply(a, b)
- a < b
- end
- }
- /
- '!=' {
- def apply(a, b)
- a != b
- end
- }
- /
- '=' {
- def apply(a, b)
- a == b
- end
- }
- end
-
- rule additive
- operand_1:multitive space operator:additive_op space operand_2:additive <BinaryOperation>
- /
- multitive
- end
-
- rule additive_op
- '+' {
- def apply(a, b)
- a + b
- end
- }
- /
- '-' {
- def apply(a, b)
- a - b
- end
- }
- end
+module SimpleSem
+ grammar Arithmetic
+ rule expression
+ comparative / additive
+ end
- rule multitive
- operand_1:primary space operator:multitive_op space operand_2:multitive <BinaryOperation>
- /
- primary
- end
-
- rule multitive_op
- '*' {
- def apply(a, b)
- a * b
- end
- }
- /
- '/' {
- def apply(a, b)
- a / b
- end
- }
- end
+ rule comparative
+ operand_1:additive space operator:comparison_op space operand_2:additive <BinaryOperation>
+ end
- rule number
- ('-'? [1-9] [0-9]* / '0') {
- def eval(env={})
- text_value.to_i
- end
- }
- end
-
- rule space
- ' '*
+ rule comparison_op
+ '>=' {
+ def apply(a, b)
+ a >= b
+ end
+ }
+ /
+ '<=' {
+ def apply(a, b)
+ a <= b
+ end
+ }
+ /
+ '>' {
+ def apply(a, b)
+ a > b
+ end
+ }
+ /
+ '<' {
+ def apply(a, b)
+ a < b
+ end
+ }
+ /
+ '!=' {
+ def apply(a, b)
+ a != b
+ end
+ }
+ /
+ '=' {
+ def apply(a, b)
+ a == b
+ end
+ }
+ end
+
+ rule additive
+ operand_1:multitive space operator:additive_op space operand_2:additive <BinaryOperation>
+ /
+ multitive
+ end
+
+ rule additive_op
+ '+' {
+ def apply(a, b)
+ a + b
+ end
+ }
+ /
+ '-' {
+ def apply(a, b)
+ a - b
+ end
+ }
+ end
+
+ rule multitive
+ operand_1:primary space operator:multitive_op space operand_2:multitive <BinaryOperation>
+ /
+ primary
+ end
+
+ rule multitive_op
+ '*' {
+ def apply(a, b)
+ a * b
+ end
+ }
+ /
+ '/' {
+ def apply(a, b)
+ a / b
+ end
+ }
+ end
+
+ rule number
+ ('-'? [1-9] [0-9]* / '0') {
+ def eval(env={})
+ text_value.to_i
+ end
+ }
+ end
+
+ rule space
+ ' '*
+ end
end
-end
\ No newline at end of file
+end
diff --git a/lib/simplesem/arithmetic_node_classes.rb b/lib/simplesem/arithmetic_node_classes.rb
index 63a6012..9012b81 100644
--- a/lib/simplesem/arithmetic_node_classes.rb
+++ b/lib/simplesem/arithmetic_node_classes.rb
@@ -1,7 +1,11 @@
-module Arithmetic
- class BinaryOperation < Treetop::Runtime::SyntaxNode
- def eval(env={})
- operator.apply(operand_1.eval(env), operand_2.eval(env))
+module SimpleSem
+ module Arithmetic
+
+ class BinaryOperation < Treetop::Runtime::SyntaxNode
+ def eval(env={})
+ operator.apply(operand_1.eval(env), operand_2.eval(env))
+ end
end
+
end
-end
\ No newline at end of file
+end
diff --git a/lib/simplesem/simple_sem.treetop b/lib/simplesem/simple_sem.treetop
index 04c5dab..906c19a 100644
--- a/lib/simplesem/simple_sem.treetop
+++ b/lib/simplesem/simple_sem.treetop
@@ -1,117 +1,118 @@
-grammar SimpleSem
- include Arithmetic
-
- rule statement
- set_stmt / jump_stmt / jumpt_stmt / halt
- end
-
- rule halt
- 'halt' {
- def execute(env={})
- raise ProgramHalt
- end
- }
- end
-
- rule set_stmt
- set_stmt_assign / set_stmt_write / set_stmt_read
- end
+module SimpleSem
+ grammar SimpleSem
+ include Arithmetic
+
+ rule statement
+ set_stmt / jump_stmt / jumpt_stmt / halt
+ end
- rule set_stmt_assign
- 'set' space loc:additive comma value:additive {
- def execute(env)
- evaled_loc = loc.eval(env)
- evaled_value = value.eval(env)
- if env.data[evaled_loc].nil?
- env.data[evaled_loc] = Array[evaled_value]
- else
- env.data[evaled_loc] << evaled_value
+ rule halt
+ 'halt' {
+ def execute(env={})
+ raise ProgramHalt
end
- end
- }
- end
-
- rule set_stmt_write
- 'set' space 'write' comma expression {
- def execute(env)
- puts expression.eval(env)
- end
- }
- /
- 'set' space 'write' comma '"' string:(!'"' . )* '"' {
- def execute(env)
- puts string.text_value
- end
- }
- end
-
- rule set_stmt_read
- 'set' space loc:additive comma 'read' {
- def execute(env)
- print "input: "
-
- evaled_loc = loc.eval(env)
- input_value = $stdin.gets.strip.to_i
-
- if env.data[evaled_loc].nil?
- env.data[evaled_loc] = Array[input_value]
- else
- env.data[evaled_loc] << input_value
+ }
+ end
+
+ rule set_stmt
+ set_stmt_assign / set_stmt_write / set_stmt_read
+ end
+
+ rule set_stmt_assign
+ 'set' space loc:additive comma value:additive {
+ def execute(env)
+ evaled_loc = loc.eval(env)
+ evaled_value = value.eval(env)
+ if env.data[evaled_loc].nil?
+ env.data[evaled_loc] = Array[evaled_value]
+ else
+ env.data[evaled_loc] << evaled_value
+ end
end
- end
- }
- end
-
- rule jump_stmt
- 'jump' space loc:additive {
- def execute(env)
- env.pc = loc.eval(env)
- end
- }
- end
-
- rule jumpt_stmt
- 'jumpt' space loc:additive comma expression {
- def execute(env)
- if expression.eval(env)
+ }
+ end
+
+ rule set_stmt_write
+ 'set' space 'write' comma expression {
+ def execute(env)
+ puts expression.eval(env)
+ end
+ }
+ /
+ 'set' space 'write' comma '"' string:(!'"' . )* '"' {
+ def execute(env)
+ puts string.text_value
+ end
+ }
+ end
+
+ rule set_stmt_read
+ 'set' space loc:additive comma 'read' {
+ def execute(env)
+ print "input: "
+
+ evaled_loc = loc.eval(env)
+ input_value = $stdin.gets.strip.to_i
+
+ if env.data[evaled_loc].nil?
+ env.data[evaled_loc] = Array[input_value]
+ else
+ env.data[evaled_loc] << input_value
+ end
+ end
+ }
+ end
+
+ rule jump_stmt
+ 'jump' space loc:additive {
+ def execute(env)
env.pc = loc.eval(env)
end
- end
- }
- end
-
- rule primary
- ip
- /
- data_lookup
- /
- number
- /
- '(' space expression space ')' {
- def eval(env={})
- expression.eval(env)
- end
- }
- end
-
- rule data_lookup
- 'D[' expr:additive ']' {
- def eval(env)
- env.data[expr.eval(env)].last
- end
- }
- end
-
- rule ip
- 'ip' {
- def eval(env)
- env.pc
- end
- }
- end
-
- rule comma
- space ',' space
+ }
+ end
+
+ rule jumpt_stmt
+ 'jumpt' space loc:additive comma expression {
+ def execute(env)
+ if expression.eval(env)
+ env.pc = loc.eval(env)
+ end
+ end
+ }
+ end
+
+ rule primary
+ ip
+ /
+ data_lookup
+ /
+ number
+ /
+ '(' space expression space ')' {
+ def eval(env={})
+ expression.eval(env)
+ end
+ }
+ end
+
+ rule data_lookup
+ 'D[' expr:additive ']' {
+ def eval(env)
+ env.data[expr.eval(env)].last
+ end
+ }
+ end
+
+ rule ip
+ 'ip' {
+ def eval(env)
+ env.pc
+ end
+ }
+ end
+
+ rule comma
+ space ',' space
+ end
end
-
-end
\ No newline at end of file
+end
diff --git a/lib/simplesem/simplesem_program.rb b/lib/simplesem/simplesem_program.rb
index da55f66..7e43f3e 100644
--- a/lib/simplesem/simplesem_program.rb
+++ b/lib/simplesem/simplesem_program.rb
@@ -1,56 +1,59 @@
require 'treetop'
require 'simplesem/arithmetic_node_classes'
dir = File.dirname(__FILE__)
Treetop.load File.expand_path(File.join(dir, 'arithmetic'))
Treetop.load File.expand_path(File.join(dir, 'simple_sem'))
-class ProgramHalt < Exception
-end
+module SimpleSem
+
+ class ProgramHalt < Exception
+ end
+
+ class Program
+ attr_reader :code
+ attr_accessor :data, :pc
-class SimpleSemProgram
- attr_reader :code
- attr_accessor :data, :pc
-
- # Create a SimpleSemProgram instance
- # Params:
- # (String)filepath: path to SimpleSem source file.
- # Optional because it's useful to use in tests without needing to load a file
- def initialize filepath=nil
- @code = Array.new
- if filepath
- IO.foreach(filepath) do |line|
- @code << line.split("//", 2)[0].strip # seperate the comment from the code
+ # Create a SimpleSemProgram instance
+ # Params:
+ # (String)filepath: path to SimpleSem source file.
+ # Optional because it's useful to use in tests without needing to load a file
+ def initialize filepath=nil
+ @code = Array.new
+ if filepath
+ IO.foreach(filepath) do |line|
+ @code << line.split("//", 2)[0].strip # seperate the comment from the code
+ end
end
+
+ @data = Array.new
+ @pc = 0
end
-
- @data = Array.new
- @pc = 0
- end
-
- def run
- @parser = SimpleSemParser.new
-
- @pc = 0
- loop do
- instruction = @code[@pc] # fetch
- @pc += 1 # increment
- begin
- @parser.parse(instruction).execute(self) # decode and execute
- rescue ProgramHalt
- break
+
+ def run
+ @parser = SimpleSemParser.new
+
+ @pc = 0
+ loop do
+ instruction = @code[@pc] # fetch
+ @pc += 1 # increment
+ begin
+ @parser.parse(instruction).execute(self) # decode and execute
+ rescue ProgramHalt
+ break
+ end
end
end
- end
-
- def inspect_data
- res = String.new
- @data.each_with_index {|loc, i| res += "#{i}: #{loc.last}\n" }
- res
- end
-
- def inspect_data_with_history
- res = String.new
- @data.each_with_index {|loc, i| res += "#{i}: #{loc.inspect}\n" }
- res
+
+ def inspect_data
+ res = String.new
+ @data.each_with_index {|loc, i| res += "#{i}: #{loc.last}\n" }
+ res
+ end
+
+ def inspect_data_with_history
+ res = String.new
+ @data.each_with_index {|loc, i| res += "#{i}: #{loc.inspect}\n" }
+ res
+ end
end
end
diff --git a/lib/simplesem/version.rb b/lib/simplesem/version.rb
new file mode 100644
index 0000000..82d081e
--- /dev/null
+++ b/lib/simplesem/version.rb
@@ -0,0 +1,5 @@
+module SimpleSem
+ unless defined? SimpleSem::VERSION
+ VERSION = '0.1.3'
+ end
+end
diff --git a/test/simplesem_test.rb b/test/simplesem_test.rb
index f446a3c..603cafc 100644
--- a/test/simplesem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,136 +1,140 @@
require 'test_helper'
require 'simplesem'
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
- @parser = SimpleSemParser.new
- @ssp = SimpleSemProgram.new
+ @parser = SimpleSem::SimpleSemParser.new
+ @ssp = SimpleSem::Program.new
@ssp.data[0] = [1]
end
+
+ def test_version_constant_is_set
+ assert_not_nil SimpleSem::VERSION
+ end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [[1], [1]], @ssp.data
end
def test_set_stmt_write_string
out = capture_stdout do
parse('set write, "Hello World!"').execute(@ssp)
end
assert_equal "Hello World!\n", out.string
end
def test_set_stmt_write_expr
out = capture_stdout do
parse('set write, 2 > 1').execute(@ssp)
end
assert_equal "true\n", out.string
end
def test_set_stmt_read
fake_in = StringIO.new("2\n3\n")
$stdin = fake_in
capture_stdout do # capture_stdout because we do not want "input:"'s in the test output
parse('set 1, read').execute(@ssp)
parse('set 1, read').execute(@ssp)
end
assert_equal [2, 3], @ssp.data[1]
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1].last
end
def test_complex_expr
@ssp.data[1] = [2]
parse('set 2, D[0]+D[1]*2').execute(@ssp)
assert_equal 5, @ssp.data[2].last
end
def test_parenthesis
@ssp.data[1] = [2]
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
assert_equal 6, @ssp.data[2].last
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0].last
end
def test_nested_data_lookup
@ssp.data[0] = [0]
@ssp.data[1] = [1]
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2].last
end
def test_instruction_pointer
# manually incrementing the program counter is required here
@ssp.pc = 1
parse('set 0, ip').execute(@ssp)
assert_equal 1, @ssp.data[0].last # checking that the parser was able to evaluate ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = [2]
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = [1]
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = [1]
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0].last
end
def test_halt
- assert_raise ProgramHalt do
+ assert_raise SimpleSem::ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
|
robolson/simplesem
|
300a5b9e9aee72aeff1abd42ee3efc9522511c10
|
Remove all requires of 'rubygems'.
|
diff --git a/.gitignore b/.gitignore
index 35fe601..56bce49 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,2 @@
-.DS_Store
coverage/
pkg/
diff --git a/Rakefile b/Rakefile
index 95596bc..56ba983 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,12 +1,11 @@
-require 'rubygems'
require 'rake'
require 'echoe'
Echoe.new('simplesem', '0.1.3') do |p|
- p.summary = "SIMPLESEM Interpreter"
- p.description = "Interpreter for parsing and executing SIMPLESEM programs"
- p.url = "http://github.com/robolson/simplesem"
- p.author = "Rob Olson"
- p.email = "[email protected]"
+ p.summary = "SIMPLESEM Interpreter"
+ p.description = "Interpreter for parsing and executing SIMPLESEM programs"
+ p.url = "http://github.com/robolson/simplesem"
+ p.author = "Rob Olson"
+ p.email = "[email protected]"
p.runtime_dependencies = ["treetop >=1.2.4"]
end
diff --git a/bin/simplesem b/bin/simplesem
index af43185..6c2d501 100755
--- a/bin/simplesem
+++ b/bin/simplesem
@@ -1,55 +1,59 @@
#!/usr/bin/env ruby
#= Overview
#
# Interpreter for the SIMPLESEM language
#
#= Usage
#
# simplesem [-t|-v] filename
#
# Options:
# -h Print this message
# -t Print Data array on exit
# -v Print Data array with change history on exit. Supersedes -t
# if it is also specified.
#
-require 'rubygems'
require 'rdoc/usage'
require 'getoptlong'
-$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
-require 'simplesem'
+# The gem packager will properly add the lib dir to LOAD_PATH when
+# executing the gem but load path manipulation is needed during development
+unless $LOAD_PATH.include?(File.expand_path('../../lib', __FILE__))
+ $LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
+end
+
+require 'simplesem' # must execute after manipulating the load path
opts = GetoptLong.new(
[ '-h', '--help', GetoptLong::NO_ARGUMENT ],
[ '-t', GetoptLong::NO_ARGUMENT ],
[ '-v', GetoptLong::NO_ARGUMENT ]
)
verbosity = 0 # by default do not print what is in Data
opts.each do |opt, arg|
case opt
when '-h'
RDoc::usage
when '-t'
verbosity = 1
when '-v'
verbosity = 2
end
end
if ARGV.length != 1
puts "Missing filename argument (try --help)"
exit 0
end
ssp = SimpleSemProgram.new(ARGV.shift)
ssp.run
if (verbosity == 1)
puts "\nDATA: \n" + ssp.inspect_data
elsif (verbosity == 2)
puts "\nDATA: \n" + ssp.inspect_data_with_history
-end
\ No newline at end of file
+end
diff --git a/lib/simplesem.rb b/lib/simplesem.rb
index b9958e9..db68f77 100644
--- a/lib/simplesem.rb
+++ b/lib/simplesem.rb
@@ -1,2 +1 @@
-dir = File.dirname(__FILE__)
-require "#{dir}/simplesem/simplesem_program"
\ No newline at end of file
+require 'simplesem/simplesem_program'
diff --git a/lib/simplesem/simplesem_program.rb b/lib/simplesem/simplesem_program.rb
index 6da736f..da55f66 100644
--- a/lib/simplesem/simplesem_program.rb
+++ b/lib/simplesem/simplesem_program.rb
@@ -1,57 +1,56 @@
-require 'rubygems'
require 'treetop'
+require 'simplesem/arithmetic_node_classes'
dir = File.dirname(__FILE__)
-require File.expand_path("#{dir}/arithmetic_node_classes")
-Treetop.load File.expand_path("#{dir}/arithmetic")
-Treetop.load File.expand_path("#{dir}/simple_sem")
+Treetop.load File.expand_path(File.join(dir, 'arithmetic'))
+Treetop.load File.expand_path(File.join(dir, 'simple_sem'))
class ProgramHalt < Exception
end
class SimpleSemProgram
attr_reader :code
attr_accessor :data, :pc
# Create a SimpleSemProgram instance
# Params:
# (String)filepath: path to SimpleSem source file.
# Optional because it's useful to use in tests without needing to load a file
def initialize filepath=nil
@code = Array.new
if filepath
IO.foreach(filepath) do |line|
@code << line.split("//", 2)[0].strip # seperate the comment from the code
end
end
@data = Array.new
@pc = 0
end
def run
@parser = SimpleSemParser.new
@pc = 0
loop do
instruction = @code[@pc] # fetch
@pc += 1 # increment
begin
@parser.parse(instruction).execute(self) # decode and execute
rescue ProgramHalt
break
end
end
end
def inspect_data
res = String.new
@data.each_with_index {|loc, i| res += "#{i}: #{loc.last}\n" }
res
end
def inspect_data_with_history
res = String.new
@data.each_with_index {|loc, i| res += "#{i}: #{loc.inspect}\n" }
res
end
-end
\ No newline at end of file
+end
diff --git a/sample_programs/gcd.txt b/sample_programs/gcd.txt
index aa96001..24f5220 100644
--- a/sample_programs/gcd.txt
+++ b/sample_programs/gcd.txt
@@ -1,12 +1,12 @@
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 6
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 10, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 11
set 0, D[0]-D[1]
-jump 6
\ No newline at end of file
+jump 6
diff --git a/sample_programs/hello-world.txt b/sample_programs/hello-world.txt
index 85aefa6..dfab7d2 100644
--- a/sample_programs/hello-world.txt
+++ b/sample_programs/hello-world.txt
@@ -1,5 +1,5 @@
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
-halt
\ No newline at end of file
+halt
diff --git a/sample_programs/while-loop.txt b/sample_programs/while-loop.txt
index 35508f5..8892335 100644
--- a/sample_programs/while-loop.txt
+++ b/sample_programs/while-loop.txt
@@ -1,14 +1,14 @@
set 0, 4
set 1, 1
set 2, -1
jumpt 10, D[0] <= D[2]
jumpt 7, D[0] != 0
set write, D[1]
jump 8
set 1, D[1]+D[0]
set 0, D[0] - 1
jump 3
set write, D[0]
set write, D[1]
set write, D[2]
-halt
\ No newline at end of file
+halt
diff --git a/test/simplesem_test.rb b/test/simplesem_test.rb
index 16defa9..f446a3c 100644
--- a/test/simplesem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,138 +1,136 @@
-dir = File.dirname(__FILE__)
-require File.expand_path("#{dir}/test_helper")
-libdir = dir + "/../lib"
-require File.expand_path("#{libdir}/simplesem")
+require 'test_helper'
+require 'simplesem'
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = [1]
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [[1], [1]], @ssp.data
end
def test_set_stmt_write_string
out = capture_stdout do
parse('set write, "Hello World!"').execute(@ssp)
end
assert_equal "Hello World!\n", out.string
end
def test_set_stmt_write_expr
out = capture_stdout do
parse('set write, 2 > 1').execute(@ssp)
end
assert_equal "true\n", out.string
end
def test_set_stmt_read
fake_in = StringIO.new("2\n3\n")
$stdin = fake_in
capture_stdout do # capture_stdout because we do not want "input:"'s in the test output
parse('set 1, read').execute(@ssp)
parse('set 1, read').execute(@ssp)
end
assert_equal [2, 3], @ssp.data[1]
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1].last
end
def test_complex_expr
@ssp.data[1] = [2]
parse('set 2, D[0]+D[1]*2').execute(@ssp)
assert_equal 5, @ssp.data[2].last
end
def test_parenthesis
@ssp.data[1] = [2]
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
assert_equal 6, @ssp.data[2].last
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0].last
end
def test_nested_data_lookup
@ssp.data[0] = [0]
@ssp.data[1] = [1]
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2].last
end
def test_instruction_pointer
# manually incrementing the program counter is required here
@ssp.pc = 1
parse('set 0, ip').execute(@ssp)
assert_equal 1, @ssp.data[0].last # checking that the parser was able to evaluate ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = [2]
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = [1]
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = [1]
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0].last
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
-end
\ No newline at end of file
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 3b359fc..513f178 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,29 +1,28 @@
require 'test/unit'
require 'stringio'
-require 'rubygems'
require 'treetop'
module ParserTestHelper
def assert_evals_to_self(input)
assert_evals_to(input, input)
end
def parse(input)
result = @parser.parse(input)
unless result
puts @parser.terminal_failures.join("\n")
end
assert !result.nil?
result
end
end
module Kernel
def capture_stdout
out = StringIO.new
$stdout = out
yield
$stdout = STDOUT
return out
end
end
|
robolson/simplesem
|
b602cfa98c1f31f7138860ec3b4f8d00180f0a97
|
Add explicit require to stringio for running the tests in Ruby 1.9
|
diff --git a/Rakefile b/Rakefile
index 8199196..95596bc 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,11 +1,12 @@
require 'rubygems'
require 'rake'
require 'echoe'
Echoe.new('simplesem', '0.1.3') do |p|
- p.description = "SIMPLESEM Interpreter"
+ p.summary = "SIMPLESEM Interpreter"
+ p.description = "Interpreter for parsing and executing SIMPLESEM programs"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
- p.email = "[email protected]"
+ p.email = "[email protected]"
p.runtime_dependencies = ["treetop >=1.2.4"]
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 41df8de..3b359fc 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,28 +1,29 @@
require 'test/unit'
+require 'stringio'
require 'rubygems'
require 'treetop'
module ParserTestHelper
def assert_evals_to_self(input)
assert_evals_to(input, input)
end
def parse(input)
result = @parser.parse(input)
unless result
puts @parser.terminal_failures.join("\n")
end
assert !result.nil?
result
end
end
module Kernel
def capture_stdout
out = StringIO.new
$stdout = out
yield
$stdout = STDOUT
return out
end
-end
\ No newline at end of file
+end
|
robolson/simplesem
|
c939992a6eb3f53bf0d206b2d508c68a668cd8e1
|
Adding Manifest to SCM
|
diff --git a/.gitignore b/.gitignore
index 3d424a2..35fe601 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,3 @@
.DS_Store
coverage/
pkg/
-Manifest
diff --git a/Manifest b/Manifest
new file mode 100644
index 0000000..578e0f2
--- /dev/null
+++ b/Manifest
@@ -0,0 +1,17 @@
+bin/simplesem
+test/test_helper.rb
+test/simplesem_test.rb
+sample_programs/case-statement.txt
+sample_programs/while-loop.txt
+sample_programs/gcd.txt
+sample_programs/hello-world.txt
+simplesem.gemspec
+LICENSE
+Rakefile
+lib/simplesem.rb
+lib/simplesem/arithmetic_node_classes.rb
+lib/simplesem/arithmetic.treetop
+lib/simplesem/simple_sem.treetop
+lib/simplesem/simplesem_program.rb
+README.textile
+Manifest
diff --git a/Rakefile b/Rakefile
index ef7ab9e..8199196 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,13 +1,11 @@
require 'rubygems'
require 'rake'
require 'echoe'
Echoe.new('simplesem', '0.1.3') do |p|
p.description = "SIMPLESEM Interpreter"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
p.email = "[email protected]"
p.runtime_dependencies = ["treetop >=1.2.4"]
end
-
-Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
|
robolson/simplesem
|
832cfe4fb0e63cc78db9e26b34ae0f8b073b4391
|
Superfluous change to the readme
|
diff --git a/README.textile b/README.textile
index be6597a..fa708b0 100644
--- a/README.textile
+++ b/README.textile
@@ -1,150 +1,154 @@
h1. SIMPLESEM Interpreter
Author: "Rob Olson":http://thinkingdigitally.com
h2. Description
Interpreter for the SIMPLESEM language.
SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem simplesem_file.txt
h3. Command Line Options
The simplesem executable accepts a couple command line options which will display the values in the Data array at the time the program exits.
-h Print help message
-t Print Data array on exit
-v Print Data array with change history on exit. Supersedes -t if it is also specified.
Use -t if you only want to see the ending value at each position in the Data array, otherwise use -v to see each data location's history. If neither -t or -v is used the program will not display the data array.
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
set 0, 4 * 2
Assign the value stored at location 0 into location 2:
set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
set write, D[0]
Get input from the user and store it at location 1:
set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Comments
SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
// This is line number 0.
set write, "foo" // a comment after a statement
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
-<pre><code>
+<pre>
+<code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
-</code></pre>
+</code>
+</pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
-<pre><code>
+<pre>
+<code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
-</code></pre>
+</code>
+</pre>
<pre>
$ simplesem -v sample_programs/gcd.txt
input: 15
input: 35
5
DATA:
0: [15, 10, 5]
1: [35, 20, 5]
2: [4]
</pre>
|
robolson/simplesem
|
ca2605face086724557a13588854b7e1a40ae5ca
|
Version number bump to 0.1.3
|
diff --git a/Rakefile b/Rakefile
index ed220b6..ef7ab9e 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,13 +1,13 @@
require 'rubygems'
require 'rake'
require 'echoe'
-Echoe.new('simplesem', '0.1.2') do |p|
+Echoe.new('simplesem', '0.1.3') do |p|
p.description = "SIMPLESEM Interpreter"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
p.email = "[email protected]"
p.runtime_dependencies = ["treetop >=1.2.4"]
end
Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
diff --git a/simplesem.gemspec b/simplesem.gemspec
index 59518cc..5a8513a 100644
--- a/simplesem.gemspec
+++ b/simplesem.gemspec
@@ -1,37 +1,37 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{simplesem}
- s.version = "0.1.2"
+ s.version = "0.1.3"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Rob Olson"]
- s.date = %q{2009-03-06}
+ s.date = %q{2009-04-01}
s.default_executable = %q{simplesem}
s.description = %q{SIMPLESEM Interpreter}
s.email = %q{[email protected]}
s.executables = ["simplesem"]
s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
s.has_rdoc = true
s.homepage = %q{http://github.com/robolson/simplesem}
- s.rdoc_options = ["--line-numbers", "--title", "Simplesem", "--main", "README.textile"]
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Simplesem", "--main", "README.textile"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{simplesem}
s.rubygems_version = %q{1.3.1}
s.summary = %q{SIMPLESEM Interpreter}
s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<treetop>, [">= 1.2.4"])
else
s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
else
s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
end
|
robolson/simplesem
|
4fd08444d34e60c698b828d44ecae015453843ed
|
Added command line options (-t,-v) for viewing change history of the Data array
|
diff --git a/README.textile b/README.textile
index 9101118..be6597a 100644
--- a/README.textile
+++ b/README.textile
@@ -1,137 +1,150 @@
h1. SIMPLESEM Interpreter
Author: "Rob Olson":http://thinkingdigitally.com
h2. Description
Interpreter for the SIMPLESEM language.
-SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
+SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem simplesem_file.txt
+h3. Command Line Options
+
+The simplesem executable accepts a couple command line options which will display the values in the Data array at the time the program exits.
+
+ -h Print help message
+ -t Print Data array on exit
+ -v Print Data array with change history on exit. Supersedes -t if it is also specified.
+
+Use -t if you only want to see the ending value at each position in the Data array, otherwise use -v to see each data location's history. If neither -t or -v is used the program will not display the data array.
+
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
set 0, 4 * 2
Assign the value stored at location 0 into location 2:
set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
set write, D[0]
Get input from the user and store it at location 1:
set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Comments
SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
// This is line number 0.
set write, "foo" // a comment after a statement
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre><code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</code></pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<pre><code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</code></pre>
<pre>
-$ simplesem sample_programs/gcd.txt
+$ simplesem -v sample_programs/gcd.txt
input: 15
input: 35
5
-DATA: [5, 5, 4]
+DATA:
+0: [15, 10, 5]
+1: [35, 20, 5]
+2: [4]
</pre>
diff --git a/bin/simplesem b/bin/simplesem
index a76fc2a..af43185 100755
--- a/bin/simplesem
+++ b/bin/simplesem
@@ -1,15 +1,55 @@
#!/usr/bin/env ruby
+#= Overview
+#
+# Interpreter for the SIMPLESEM language
+#
+#= Usage
+#
+# simplesem [-t|-v] filename
+#
+# Options:
+# -h Print this message
+# -t Print Data array on exit
+# -v Print Data array with change history on exit. Supersedes -t
+# if it is also specified.
+#
+
require 'rubygems'
+require 'rdoc/usage'
+require 'getoptlong'
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
require 'simplesem'
-if ARGV.empty?
- puts "Usage:\n\nsimplesem simplesem_file.txt\n\n"
- exit
+opts = GetoptLong.new(
+ [ '-h', '--help', GetoptLong::NO_ARGUMENT ],
+ [ '-t', GetoptLong::NO_ARGUMENT ],
+ [ '-v', GetoptLong::NO_ARGUMENT ]
+)
+
+verbosity = 0 # by default do not print what is in Data
+
+opts.each do |opt, arg|
+ case opt
+ when '-h'
+ RDoc::usage
+ when '-t'
+ verbosity = 1
+ when '-v'
+ verbosity = 2
+ end
+end
+
+if ARGV.length != 1
+ puts "Missing filename argument (try --help)"
+ exit 0
end
ssp = SimpleSemProgram.new(ARGV.shift)
ssp.run
-puts "\nDATA: " + ssp.data.inspect
\ No newline at end of file
+if (verbosity == 1)
+ puts "\nDATA: \n" + ssp.inspect_data
+elsif (verbosity == 2)
+ puts "\nDATA: \n" + ssp.inspect_data_with_history
+end
\ No newline at end of file
diff --git a/lib/simplesem/simplesem_program.rb b/lib/simplesem/simplesem_program.rb
index f377dfd..6da736f 100644
--- a/lib/simplesem/simplesem_program.rb
+++ b/lib/simplesem/simplesem_program.rb
@@ -1,45 +1,57 @@
require 'rubygems'
require 'treetop'
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class ProgramHalt < Exception
end
class SimpleSemProgram
attr_reader :code
attr_accessor :data, :pc
# Create a SimpleSemProgram instance
# Params:
# (String)filepath: path to SimpleSem source file.
# Optional because it's useful to use in tests without needing to load a file
def initialize filepath=nil
@code = Array.new
if filepath
IO.foreach(filepath) do |line|
@code << line.split("//", 2)[0].strip # seperate the comment from the code
end
end
@data = Array.new
@pc = 0
end
def run
@parser = SimpleSemParser.new
@pc = 0
loop do
instruction = @code[@pc] # fetch
@pc += 1 # increment
begin
@parser.parse(instruction).execute(self) # decode and execute
rescue ProgramHalt
break
end
end
end
+
+ def inspect_data
+ res = String.new
+ @data.each_with_index {|loc, i| res += "#{i}: #{loc.last}\n" }
+ res
+ end
+
+ def inspect_data_with_history
+ res = String.new
+ @data.each_with_index {|loc, i| res += "#{i}: #{loc.inspect}\n" }
+ res
+ end
end
\ No newline at end of file
|
robolson/simplesem
|
69ef6013a031a806ebca35d87ffc79ea22472cdf
|
maintain history of changes to the data array
|
diff --git a/lib/simplesem/simple_sem.treetop b/lib/simplesem/simple_sem.treetop
index 18ee634..04c5dab 100644
--- a/lib/simplesem/simple_sem.treetop
+++ b/lib/simplesem/simple_sem.treetop
@@ -1,103 +1,117 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
raise ProgramHalt
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
'set' space loc:additive comma value:additive {
def execute(env)
- env.data[loc.eval(env)] = value.eval(env)
+ evaled_loc = loc.eval(env)
+ evaled_value = value.eval(env)
+ if env.data[evaled_loc].nil?
+ env.data[evaled_loc] = Array[evaled_value]
+ else
+ env.data[evaled_loc] << evaled_value
+ end
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
/
'set' space 'write' comma '"' string:(!'"' . )* '"' {
def execute(env)
puts string.text_value
end
}
end
rule set_stmt_read
'set' space loc:additive comma 'read' {
def execute(env)
print "input: "
- env.data[loc.eval(env)] = $stdin.gets.strip.to_i
+
+ evaled_loc = loc.eval(env)
+ input_value = $stdin.gets.strip.to_i
+
+ if env.data[evaled_loc].nil?
+ env.data[evaled_loc] = Array[input_value]
+ else
+ env.data[evaled_loc] << input_value
+ end
end
}
end
rule jump_stmt
'jump' space loc:additive {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:additive comma expression {
def execute(env)
if expression.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule primary
ip
/
data_lookup
/
number
/
'(' space expression space ')' {
def eval(env={})
expression.eval(env)
end
}
end
rule data_lookup
'D[' expr:additive ']' {
def eval(env)
- env.data[expr.eval(env)]
+ env.data[expr.eval(env)].last
end
}
end
rule ip
'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
end
\ No newline at end of file
diff --git a/test/simplesem_test.rb b/test/simplesem_test.rb
index f6058d4..16defa9 100644
--- a/test/simplesem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,127 +1,138 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
libdir = dir + "/../lib"
require File.expand_path("#{libdir}/simplesem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
- @ssp.data[0] = 1
+ @ssp.data[0] = [1]
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
- assert_equal [1, 1], @ssp.data
+ assert_equal [[1], [1]], @ssp.data
end
def test_set_stmt_write_string
out = capture_stdout do
parse('set write, "Hello World!"').execute(@ssp)
end
assert_equal "Hello World!\n", out.string
end
def test_set_stmt_write_expr
out = capture_stdout do
parse('set write, 2 > 1').execute(@ssp)
end
assert_equal "true\n", out.string
end
+ def test_set_stmt_read
+ fake_in = StringIO.new("2\n3\n")
+ $stdin = fake_in
+
+ capture_stdout do # capture_stdout because we do not want "input:"'s in the test output
+ parse('set 1, read').execute(@ssp)
+ parse('set 1, read').execute(@ssp)
+ end
+ assert_equal [2, 3], @ssp.data[1]
+ end
+
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
- assert_equal 2, @ssp.data[1]
+ assert_equal 2, @ssp.data[1].last
end
def test_complex_expr
- @ssp.data[1] = 2
+ @ssp.data[1] = [2]
parse('set 2, D[0]+D[1]*2').execute(@ssp)
- assert_equal 5, @ssp.data[2]
+ assert_equal 5, @ssp.data[2].last
end
def test_parenthesis
- @ssp.data[1] = 2
+ @ssp.data[1] = [2]
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
- assert_equal 6, @ssp.data[2]
+ assert_equal 6, @ssp.data[2].last
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
- assert_equal 2, @ssp.data[0]
+ assert_equal 2, @ssp.data[0].last
end
def test_nested_data_lookup
- @ssp.data[0] = 0
- @ssp.data[1] = 1
+ @ssp.data[0] = [0]
+ @ssp.data[1] = [1]
parse('set 2, D[D[0]+1]').execute(@ssp)
- assert_equal 1, @ssp.data[2]
+ assert_equal 1, @ssp.data[2].last
end
def test_instruction_pointer
# manually incrementing the program counter is required here
@ssp.pc = 1
parse('set 0, ip').execute(@ssp)
- assert_equal 1, @ssp.data[0] # check that the parser was able to evaluate ip correctly
+ assert_equal 1, @ssp.data[0].last # checking that the parser was able to evaluate ip correctly
end
def test_jump_to_data_loc
- @ssp.data[0] = 2
+ @ssp.data[0] = [2]
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
- @ssp.data[0] = 1
+ @ssp.data[0] = [1]
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
- @ssp.data[0] = 1
+ @ssp.data[0] = [1]
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
- assert_equal -1, @ssp.data[0]
+ assert_equal -1, @ssp.data[0].last
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
\ No newline at end of file
|
robolson/simplesem
|
00fe4cb61f3683ec9afd1f80ed457d788e5e62d0
|
Ripped out InternalPuts class and replaced with a Kernel level capture_stdout
|
diff --git a/test/simplesem_test.rb b/test/simplesem_test.rb
index 860be16..f6058d4 100644
--- a/test/simplesem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,127 +1,127 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
libdir = dir + "/../lib"
require File.expand_path("#{libdir}/simplesem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write_string
- out = InternalPuts.capture do
+ out = capture_stdout do
parse('set write, "Hello World!"').execute(@ssp)
end
- assert_equal "Hello World!\n", out
+ assert_equal "Hello World!\n", out.string
end
def test_set_stmt_write_expr
- out = InternalPuts.capture do
+ out = capture_stdout do
parse('set write, 2 > 1').execute(@ssp)
end
- assert_equal "true\n", out
+ assert_equal "true\n", out.string
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_complex_expr
@ssp.data[1] = 2
parse('set 2, D[0]+D[1]*2').execute(@ssp)
assert_equal 5, @ssp.data[2]
end
def test_parenthesis
@ssp.data[1] = 2
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
assert_equal 6, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
def test_nested_data_lookup
@ssp.data[0] = 0
@ssp.data[1] = 1
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2]
end
def test_instruction_pointer
# manually incrementing the program counter is required here
@ssp.pc = 1
parse('set 0, ip').execute(@ssp)
assert_equal 1, @ssp.data[0] # check that the parser was able to evaluate ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
\ No newline at end of file
diff --git a/test/test_helper.rb b/test/test_helper.rb
index fe6a03a..41df8de 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,37 +1,28 @@
require 'test/unit'
require 'rubygems'
require 'treetop'
module ParserTestHelper
def assert_evals_to_self(input)
assert_evals_to(input, input)
end
def parse(input)
result = @parser.parse(input)
unless result
puts @parser.terminal_failures.join("\n")
end
assert !result.nil?
result
end
end
-class InternalPuts
- attr_reader :out
-
- def self.capture
- $stdout = instance = new
+module Kernel
+ def capture_stdout
+ out = StringIO.new
+ $stdout = out
yield
$stdout = STDOUT
- return instance.out
- end
-
- def initialize
- @out = String.new
+ return out
end
-
- def write(str)
- @out << str
- end
end
\ No newline at end of file
|
robolson/simplesem
|
591a402360d6752e60cdce684cffd5382e105975
|
Added a much more effective test for "set write" commands
|
diff --git a/test/simplesem_test.rb b/test/simplesem_test.rb
index e6ac282..860be16 100644
--- a/test/simplesem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,119 +1,127 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
libdir = dir + "/../lib"
require File.expand_path("#{libdir}/simplesem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
- def test_set_stmt_write
- assert_nil parse('set write, "hello world!"').execute(@ssp)
+ def test_set_stmt_write_string
+ out = InternalPuts.capture do
+ parse('set write, "Hello World!"').execute(@ssp)
+ end
+ assert_equal "Hello World!\n", out
+ end
+
+ def test_set_stmt_write_expr
+ out = InternalPuts.capture do
+ parse('set write, 2 > 1').execute(@ssp)
+ end
+ assert_equal "true\n", out
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_complex_expr
@ssp.data[1] = 2
parse('set 2, D[0]+D[1]*2').execute(@ssp)
assert_equal 5, @ssp.data[2]
end
def test_parenthesis
@ssp.data[1] = 2
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
assert_equal 6, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
def test_nested_data_lookup
@ssp.data[0] = 0
@ssp.data[1] = 1
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2]
end
def test_instruction_pointer
- # run two dummy instructions, manually incrementing the program counter
+ # manually incrementing the program counter is required here
@ssp.pc = 1
- parse('set 0, 0').execute(@ssp)
- @ssp.pc = 2
parse('set 0, ip').execute(@ssp)
- assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
+ assert_equal 1, @ssp.data[0] # check that the parser was able to evaluate ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
\ No newline at end of file
diff --git a/test/test_helper.rb b/test/test_helper.rb
index bfdb7ad..fe6a03a 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,18 +1,37 @@
require 'test/unit'
require 'rubygems'
require 'treetop'
module ParserTestHelper
def assert_evals_to_self(input)
assert_evals_to(input, input)
end
def parse(input)
result = @parser.parse(input)
unless result
puts @parser.terminal_failures.join("\n")
end
assert !result.nil?
result
end
+end
+
+class InternalPuts
+ attr_reader :out
+
+ def self.capture
+ $stdout = instance = new
+ yield
+ $stdout = STDOUT
+ return instance.out
+ end
+
+ def initialize
+ @out = String.new
+ end
+
+ def write(str)
+ @out << str
+ end
end
\ No newline at end of file
|
robolson/simplesem
|
3217be93cf52d065b054c08da0bde60bd1c82e13
|
Version 0.1.2 added treetop as runtime dependency
|
diff --git a/Rakefile b/Rakefile
index de4d129..ed220b6 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,13 +1,13 @@
require 'rubygems'
require 'rake'
require 'echoe'
-Echoe.new('simplesem', '0.1.1') do |p|
+Echoe.new('simplesem', '0.1.2') do |p|
p.description = "SIMPLESEM Interpreter"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
p.email = "[email protected]"
- p.development_dependencies = ['treetop']
+ p.runtime_dependencies = ["treetop >=1.2.4"]
end
Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
diff --git a/simplesem.gemspec b/simplesem.gemspec
index bcd59a3..59518cc 100644
--- a/simplesem.gemspec
+++ b/simplesem.gemspec
@@ -1,37 +1,37 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{simplesem}
- s.version = "0.1.1"
+ s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Rob Olson"]
s.date = %q{2009-03-06}
s.default_executable = %q{simplesem}
s.description = %q{SIMPLESEM Interpreter}
s.email = %q{[email protected]}
s.executables = ["simplesem"]
- s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
- s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
+ s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
+ s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
s.has_rdoc = true
s.homepage = %q{http://github.com/robolson/simplesem}
s.rdoc_options = ["--line-numbers", "--title", "Simplesem", "--main", "README.textile"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{simplesem}
s.rubygems_version = %q{1.3.1}
s.summary = %q{SIMPLESEM Interpreter}
s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
- s.add_development_dependency(%q<treetop>, [">= 0"])
+ s.add_runtime_dependency(%q<treetop>, [">= 1.2.4"])
else
- s.add_dependency(%q<treetop>, [">= 0"])
+ s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
else
- s.add_dependency(%q<treetop>, [">= 0"])
+ s.add_dependency(%q<treetop>, [">= 1.2.4"])
end
end
|
robolson/simplesem
|
c2123ff85f5cffc93c8aa4bd346c0e039190deea
|
Bump version numberto 0.1.1
|
diff --git a/Rakefile b/Rakefile
index f650dae..de4d129 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,13 +1,13 @@
require 'rubygems'
require 'rake'
require 'echoe'
-Echoe.new('simplesem', '0.1.0') do |p|
+Echoe.new('simplesem', '0.1.1') do |p|
p.description = "SIMPLESEM Interpreter"
p.url = "http://github.com/robolson/simplesem"
p.author = "Rob Olson"
p.email = "[email protected]"
p.development_dependencies = ['treetop']
end
Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
diff --git a/simplesem.gemspec b/simplesem.gemspec
index ba39b7d..bcd59a3 100644
--- a/simplesem.gemspec
+++ b/simplesem.gemspec
@@ -1,37 +1,37 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{simplesem}
- s.version = "0.1.0"
+ s.version = "0.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Rob Olson"]
- s.date = %q{2009-02-26}
+ s.date = %q{2009-03-06}
s.default_executable = %q{simplesem}
s.description = %q{SIMPLESEM Interpreter}
s.email = %q{[email protected]}
s.executables = ["simplesem"]
- s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
- s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
+ s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
+ s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.rb", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
s.has_rdoc = true
s.homepage = %q{http://github.com/robolson/simplesem}
- s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Simplesem", "--main", "README.textile"]
+ s.rdoc_options = ["--line-numbers", "--title", "Simplesem", "--main", "README.textile"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{simplesem}
s.rubygems_version = %q{1.3.1}
s.summary = %q{SIMPLESEM Interpreter}
s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<treetop>, [">= 0"])
else
s.add_dependency(%q<treetop>, [">= 0"])
end
else
s.add_dependency(%q<treetop>, [">= 0"])
end
end
|
robolson/simplesem
|
3caff67b8d74321e4b2a3e9d668a9d9ca6241e71
|
Generating static ruby code for treetop grammar files so that the treetop gem is not required for usage.
|
diff --git a/lib/simplesem/arithmetic.rb b/lib/simplesem/arithmetic.rb
new file mode 100644
index 0000000..02cd93e
--- /dev/null
+++ b/lib/simplesem/arithmetic.rb
@@ -0,0 +1,601 @@
+module Arithmetic
+ include Treetop::Runtime
+
+ def root
+ @root || :expression
+ end
+
+ def _nt_expression
+ start_index = index
+ if node_cache[:expression].has_key?(index)
+ cached = node_cache[:expression][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ r1 = _nt_comparative
+ if r1
+ r0 = r1
+ else
+ r2 = _nt_additive
+ if r2
+ r0 = r2
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:expression][start_index] = r0
+
+ return r0
+ end
+
+ module Comparative0
+ def operand_1
+ elements[0]
+ end
+
+ def space
+ elements[1]
+ end
+
+ def operator
+ elements[2]
+ end
+
+ def space
+ elements[3]
+ end
+
+ def operand_2
+ elements[4]
+ end
+ end
+
+ def _nt_comparative
+ start_index = index
+ if node_cache[:comparative].has_key?(index)
+ cached = node_cache[:comparative][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ r1 = _nt_additive
+ s0 << r1
+ if r1
+ r2 = _nt_space
+ s0 << r2
+ if r2
+ r3 = _nt_comparison_op
+ s0 << r3
+ if r3
+ r4 = _nt_space
+ s0 << r4
+ if r4
+ r5 = _nt_additive
+ s0 << r5
+ end
+ end
+ end
+ end
+ if s0.last
+ r0 = (BinaryOperation).new(input, i0...index, s0)
+ r0.extend(Comparative0)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:comparative][start_index] = r0
+
+ return r0
+ end
+
+ module ComparisonOp0
+ def apply(a, b)
+ a >= b
+ end
+ end
+
+ module ComparisonOp1
+ def apply(a, b)
+ a <= b
+ end
+ end
+
+ module ComparisonOp2
+ def apply(a, b)
+ a > b
+ end
+ end
+
+ module ComparisonOp3
+ def apply(a, b)
+ a < b
+ end
+ end
+
+ module ComparisonOp4
+ def apply(a, b)
+ a != b
+ end
+ end
+
+ module ComparisonOp5
+ def apply(a, b)
+ a == b
+ end
+ end
+
+ def _nt_comparison_op
+ start_index = index
+ if node_cache[:comparison_op].has_key?(index)
+ cached = node_cache[:comparison_op][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ if input.index('>=', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 2))
+ r1.extend(ComparisonOp0)
+ @index += 2
+ else
+ terminal_parse_failure('>=')
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ if input.index('<=', index) == index
+ r2 = (SyntaxNode).new(input, index...(index + 2))
+ r2.extend(ComparisonOp1)
+ @index += 2
+ else
+ terminal_parse_failure('<=')
+ r2 = nil
+ end
+ if r2
+ r0 = r2
+ else
+ if input.index('>', index) == index
+ r3 = (SyntaxNode).new(input, index...(index + 1))
+ r3.extend(ComparisonOp2)
+ @index += 1
+ else
+ terminal_parse_failure('>')
+ r3 = nil
+ end
+ if r3
+ r0 = r3
+ else
+ if input.index('<', index) == index
+ r4 = (SyntaxNode).new(input, index...(index + 1))
+ r4.extend(ComparisonOp3)
+ @index += 1
+ else
+ terminal_parse_failure('<')
+ r4 = nil
+ end
+ if r4
+ r0 = r4
+ else
+ if input.index('!=', index) == index
+ r5 = (SyntaxNode).new(input, index...(index + 2))
+ r5.extend(ComparisonOp4)
+ @index += 2
+ else
+ terminal_parse_failure('!=')
+ r5 = nil
+ end
+ if r5
+ r0 = r5
+ else
+ if input.index('=', index) == index
+ r6 = (SyntaxNode).new(input, index...(index + 1))
+ r6.extend(ComparisonOp5)
+ @index += 1
+ else
+ terminal_parse_failure('=')
+ r6 = nil
+ end
+ if r6
+ r0 = r6
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+ end
+ end
+ end
+ end
+
+ node_cache[:comparison_op][start_index] = r0
+
+ return r0
+ end
+
+ module Additive0
+ def operand_1
+ elements[0]
+ end
+
+ def space
+ elements[1]
+ end
+
+ def operator
+ elements[2]
+ end
+
+ def space
+ elements[3]
+ end
+
+ def operand_2
+ elements[4]
+ end
+ end
+
+ def _nt_additive
+ start_index = index
+ if node_cache[:additive].has_key?(index)
+ cached = node_cache[:additive][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ i1, s1 = index, []
+ r2 = _nt_multitive
+ s1 << r2
+ if r2
+ r3 = _nt_space
+ s1 << r3
+ if r3
+ r4 = _nt_additive_op
+ s1 << r4
+ if r4
+ r5 = _nt_space
+ s1 << r5
+ if r5
+ r6 = _nt_additive
+ s1 << r6
+ end
+ end
+ end
+ end
+ if s1.last
+ r1 = (BinaryOperation).new(input, i1...index, s1)
+ r1.extend(Additive0)
+ else
+ self.index = i1
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ r7 = _nt_multitive
+ if r7
+ r0 = r7
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:additive][start_index] = r0
+
+ return r0
+ end
+
+ module AdditiveOp0
+ def apply(a, b)
+ a + b
+ end
+ end
+
+ module AdditiveOp1
+ def apply(a, b)
+ a - b
+ end
+ end
+
+ def _nt_additive_op
+ start_index = index
+ if node_cache[:additive_op].has_key?(index)
+ cached = node_cache[:additive_op][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ if input.index('+', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 1))
+ r1.extend(AdditiveOp0)
+ @index += 1
+ else
+ terminal_parse_failure('+')
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ if input.index('-', index) == index
+ r2 = (SyntaxNode).new(input, index...(index + 1))
+ r2.extend(AdditiveOp1)
+ @index += 1
+ else
+ terminal_parse_failure('-')
+ r2 = nil
+ end
+ if r2
+ r0 = r2
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:additive_op][start_index] = r0
+
+ return r0
+ end
+
+ module Multitive0
+ def operand_1
+ elements[0]
+ end
+
+ def space
+ elements[1]
+ end
+
+ def operator
+ elements[2]
+ end
+
+ def space
+ elements[3]
+ end
+
+ def operand_2
+ elements[4]
+ end
+ end
+
+ def _nt_multitive
+ start_index = index
+ if node_cache[:multitive].has_key?(index)
+ cached = node_cache[:multitive][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ i1, s1 = index, []
+ r2 = _nt_primary
+ s1 << r2
+ if r2
+ r3 = _nt_space
+ s1 << r3
+ if r3
+ r4 = _nt_multitive_op
+ s1 << r4
+ if r4
+ r5 = _nt_space
+ s1 << r5
+ if r5
+ r6 = _nt_multitive
+ s1 << r6
+ end
+ end
+ end
+ end
+ if s1.last
+ r1 = (BinaryOperation).new(input, i1...index, s1)
+ r1.extend(Multitive0)
+ else
+ self.index = i1
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ r7 = _nt_primary
+ if r7
+ r0 = r7
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:multitive][start_index] = r0
+
+ return r0
+ end
+
+ module MultitiveOp0
+ def apply(a, b)
+ a * b
+ end
+ end
+
+ module MultitiveOp1
+ def apply(a, b)
+ a / b
+ end
+ end
+
+ def _nt_multitive_op
+ start_index = index
+ if node_cache[:multitive_op].has_key?(index)
+ cached = node_cache[:multitive_op][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ if input.index('*', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 1))
+ r1.extend(MultitiveOp0)
+ @index += 1
+ else
+ terminal_parse_failure('*')
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ if input.index('/', index) == index
+ r2 = (SyntaxNode).new(input, index...(index + 1))
+ r2.extend(MultitiveOp1)
+ @index += 1
+ else
+ terminal_parse_failure('/')
+ r2 = nil
+ end
+ if r2
+ r0 = r2
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:multitive_op][start_index] = r0
+
+ return r0
+ end
+
+ module Number0
+ end
+
+ module Number1
+ def eval(env={})
+ text_value.to_i
+ end
+ end
+
+ def _nt_number
+ start_index = index
+ if node_cache[:number].has_key?(index)
+ cached = node_cache[:number][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ i1, s1 = index, []
+ if input.index('-', index) == index
+ r3 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('-')
+ r3 = nil
+ end
+ if r3
+ r2 = r3
+ else
+ r2 = SyntaxNode.new(input, index...index)
+ end
+ s1 << r2
+ if r2
+ if input.index(Regexp.new('[1-9]'), index) == index
+ r4 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ r4 = nil
+ end
+ s1 << r4
+ if r4
+ s5, i5 = [], index
+ loop do
+ if input.index(Regexp.new('[0-9]'), index) == index
+ r6 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ r6 = nil
+ end
+ if r6
+ s5 << r6
+ else
+ break
+ end
+ end
+ r5 = SyntaxNode.new(input, i5...index, s5)
+ s1 << r5
+ end
+ end
+ if s1.last
+ r1 = (SyntaxNode).new(input, i1...index, s1)
+ r1.extend(Number0)
+ else
+ self.index = i1
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ r0.extend(Number1)
+ else
+ if input.index('0', index) == index
+ r7 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('0')
+ r7 = nil
+ end
+ if r7
+ r0 = r7
+ r0.extend(Number1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:number][start_index] = r0
+
+ return r0
+ end
+
+ def _nt_space
+ start_index = index
+ if node_cache[:space].has_key?(index)
+ cached = node_cache[:space][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ s0, i0 = [], index
+ loop do
+ if input.index(' ', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure(' ')
+ r1 = nil
+ end
+ if r1
+ s0 << r1
+ else
+ break
+ end
+ end
+ r0 = SyntaxNode.new(input, i0...index, s0)
+
+ node_cache[:space][start_index] = r0
+
+ return r0
+ end
+
+end
+
+class ArithmeticParser < Treetop::Runtime::CompiledParser
+ include Arithmetic
+end
diff --git a/lib/simplesem/simple_sem.rb b/lib/simplesem/simple_sem.rb
new file mode 100644
index 0000000..d2107d4
--- /dev/null
+++ b/lib/simplesem/simple_sem.rb
@@ -0,0 +1,823 @@
+module SimpleSem
+ include Treetop::Runtime
+
+ def root
+ @root || :statement
+ end
+
+ include Arithmetic
+
+ def _nt_statement
+ start_index = index
+ if node_cache[:statement].has_key?(index)
+ cached = node_cache[:statement][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ r1 = _nt_set_stmt
+ if r1
+ r0 = r1
+ else
+ r2 = _nt_jump_stmt
+ if r2
+ r0 = r2
+ else
+ r3 = _nt_jumpt_stmt
+ if r3
+ r0 = r3
+ else
+ r4 = _nt_halt
+ if r4
+ r0 = r4
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+ end
+ end
+
+ node_cache[:statement][start_index] = r0
+
+ return r0
+ end
+
+ module Halt0
+ def execute(env={})
+ raise ProgramHalt
+ end
+ end
+
+ def _nt_halt
+ start_index = index
+ if node_cache[:halt].has_key?(index)
+ cached = node_cache[:halt][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ if input.index('halt', index) == index
+ r0 = (SyntaxNode).new(input, index...(index + 4))
+ r0.extend(Halt0)
+ @index += 4
+ else
+ terminal_parse_failure('halt')
+ r0 = nil
+ end
+
+ node_cache[:halt][start_index] = r0
+
+ return r0
+ end
+
+ def _nt_set_stmt
+ start_index = index
+ if node_cache[:set_stmt].has_key?(index)
+ cached = node_cache[:set_stmt][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ r1 = _nt_set_stmt_assign
+ if r1
+ r0 = r1
+ else
+ r2 = _nt_set_stmt_write
+ if r2
+ r0 = r2
+ else
+ r3 = _nt_set_stmt_read
+ if r3
+ r0 = r3
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+ end
+
+ node_cache[:set_stmt][start_index] = r0
+
+ return r0
+ end
+
+ module SetStmtAssign0
+ def space
+ elements[1]
+ end
+
+ def loc
+ elements[2]
+ end
+
+ def comma
+ elements[3]
+ end
+
+ def value
+ elements[4]
+ end
+ end
+
+ module SetStmtAssign1
+ def execute(env)
+ env.data[loc.eval(env)] = value.eval(env)
+ end
+ end
+
+ def _nt_set_stmt_assign
+ start_index = index
+ if node_cache[:set_stmt_assign].has_key?(index)
+ cached = node_cache[:set_stmt_assign][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ if input.index('set', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 3))
+ @index += 3
+ else
+ terminal_parse_failure('set')
+ r1 = nil
+ end
+ s0 << r1
+ if r1
+ r2 = _nt_space
+ s0 << r2
+ if r2
+ r3 = _nt_additive
+ s0 << r3
+ if r3
+ r4 = _nt_comma
+ s0 << r4
+ if r4
+ r5 = _nt_additive
+ s0 << r5
+ end
+ end
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(SetStmtAssign0)
+ r0.extend(SetStmtAssign1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:set_stmt_assign][start_index] = r0
+
+ return r0
+ end
+
+ module SetStmtWrite0
+ def space
+ elements[1]
+ end
+
+ def comma
+ elements[3]
+ end
+
+ def expression
+ elements[4]
+ end
+ end
+
+ module SetStmtWrite1
+ def execute(env)
+ puts expression.eval(env)
+ end
+ end
+
+ module SetStmtWrite2
+ end
+
+ module SetStmtWrite3
+ def space
+ elements[1]
+ end
+
+ def comma
+ elements[3]
+ end
+
+ def string
+ elements[5]
+ end
+
+ end
+
+ module SetStmtWrite4
+ def execute(env)
+ puts string.text_value
+ end
+ end
+
+ def _nt_set_stmt_write
+ start_index = index
+ if node_cache[:set_stmt_write].has_key?(index)
+ cached = node_cache[:set_stmt_write][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ i1, s1 = index, []
+ if input.index('set', index) == index
+ r2 = (SyntaxNode).new(input, index...(index + 3))
+ @index += 3
+ else
+ terminal_parse_failure('set')
+ r2 = nil
+ end
+ s1 << r2
+ if r2
+ r3 = _nt_space
+ s1 << r3
+ if r3
+ if input.index('write', index) == index
+ r4 = (SyntaxNode).new(input, index...(index + 5))
+ @index += 5
+ else
+ terminal_parse_failure('write')
+ r4 = nil
+ end
+ s1 << r4
+ if r4
+ r5 = _nt_comma
+ s1 << r5
+ if r5
+ r6 = _nt_expression
+ s1 << r6
+ end
+ end
+ end
+ end
+ if s1.last
+ r1 = (SyntaxNode).new(input, i1...index, s1)
+ r1.extend(SetStmtWrite0)
+ r1.extend(SetStmtWrite1)
+ else
+ self.index = i1
+ r1 = nil
+ end
+ if r1
+ r0 = r1
+ else
+ i7, s7 = index, []
+ if input.index('set', index) == index
+ r8 = (SyntaxNode).new(input, index...(index + 3))
+ @index += 3
+ else
+ terminal_parse_failure('set')
+ r8 = nil
+ end
+ s7 << r8
+ if r8
+ r9 = _nt_space
+ s7 << r9
+ if r9
+ if input.index('write', index) == index
+ r10 = (SyntaxNode).new(input, index...(index + 5))
+ @index += 5
+ else
+ terminal_parse_failure('write')
+ r10 = nil
+ end
+ s7 << r10
+ if r10
+ r11 = _nt_comma
+ s7 << r11
+ if r11
+ if input.index('"', index) == index
+ r12 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('"')
+ r12 = nil
+ end
+ s7 << r12
+ if r12
+ s13, i13 = [], index
+ loop do
+ i14, s14 = index, []
+ i15 = index
+ if input.index('"', index) == index
+ r16 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('"')
+ r16 = nil
+ end
+ if r16
+ r15 = nil
+ else
+ self.index = i15
+ r15 = SyntaxNode.new(input, index...index)
+ end
+ s14 << r15
+ if r15
+ if index < input_length
+ r17 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure("any character")
+ r17 = nil
+ end
+ s14 << r17
+ end
+ if s14.last
+ r14 = (SyntaxNode).new(input, i14...index, s14)
+ r14.extend(SetStmtWrite2)
+ else
+ self.index = i14
+ r14 = nil
+ end
+ if r14
+ s13 << r14
+ else
+ break
+ end
+ end
+ r13 = SyntaxNode.new(input, i13...index, s13)
+ s7 << r13
+ if r13
+ if input.index('"', index) == index
+ r18 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('"')
+ r18 = nil
+ end
+ s7 << r18
+ end
+ end
+ end
+ end
+ end
+ end
+ if s7.last
+ r7 = (SyntaxNode).new(input, i7...index, s7)
+ r7.extend(SetStmtWrite3)
+ r7.extend(SetStmtWrite4)
+ else
+ self.index = i7
+ r7 = nil
+ end
+ if r7
+ r0 = r7
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+
+ node_cache[:set_stmt_write][start_index] = r0
+
+ return r0
+ end
+
+ module SetStmtRead0
+ def space
+ elements[1]
+ end
+
+ def loc
+ elements[2]
+ end
+
+ def comma
+ elements[3]
+ end
+
+ end
+
+ module SetStmtRead1
+ def execute(env)
+ print "input: "
+ env.data[loc.eval(env)] = $stdin.gets.strip.to_i
+ end
+ end
+
+ def _nt_set_stmt_read
+ start_index = index
+ if node_cache[:set_stmt_read].has_key?(index)
+ cached = node_cache[:set_stmt_read][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ if input.index('set', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 3))
+ @index += 3
+ else
+ terminal_parse_failure('set')
+ r1 = nil
+ end
+ s0 << r1
+ if r1
+ r2 = _nt_space
+ s0 << r2
+ if r2
+ r3 = _nt_additive
+ s0 << r3
+ if r3
+ r4 = _nt_comma
+ s0 << r4
+ if r4
+ if input.index('read', index) == index
+ r5 = (SyntaxNode).new(input, index...(index + 4))
+ @index += 4
+ else
+ terminal_parse_failure('read')
+ r5 = nil
+ end
+ s0 << r5
+ end
+ end
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(SetStmtRead0)
+ r0.extend(SetStmtRead1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:set_stmt_read][start_index] = r0
+
+ return r0
+ end
+
+ module JumpStmt0
+ def space
+ elements[1]
+ end
+
+ def loc
+ elements[2]
+ end
+ end
+
+ module JumpStmt1
+ def execute(env)
+ env.pc = loc.eval(env)
+ end
+ end
+
+ def _nt_jump_stmt
+ start_index = index
+ if node_cache[:jump_stmt].has_key?(index)
+ cached = node_cache[:jump_stmt][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ if input.index('jump', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 4))
+ @index += 4
+ else
+ terminal_parse_failure('jump')
+ r1 = nil
+ end
+ s0 << r1
+ if r1
+ r2 = _nt_space
+ s0 << r2
+ if r2
+ r3 = _nt_additive
+ s0 << r3
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(JumpStmt0)
+ r0.extend(JumpStmt1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:jump_stmt][start_index] = r0
+
+ return r0
+ end
+
+ module JumptStmt0
+ def space
+ elements[1]
+ end
+
+ def loc
+ elements[2]
+ end
+
+ def comma
+ elements[3]
+ end
+
+ def expression
+ elements[4]
+ end
+ end
+
+ module JumptStmt1
+ def execute(env)
+ if expression.eval(env)
+ env.pc = loc.eval(env)
+ end
+ end
+ end
+
+ def _nt_jumpt_stmt
+ start_index = index
+ if node_cache[:jumpt_stmt].has_key?(index)
+ cached = node_cache[:jumpt_stmt][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ if input.index('jumpt', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 5))
+ @index += 5
+ else
+ terminal_parse_failure('jumpt')
+ r1 = nil
+ end
+ s0 << r1
+ if r1
+ r2 = _nt_space
+ s0 << r2
+ if r2
+ r3 = _nt_additive
+ s0 << r3
+ if r3
+ r4 = _nt_comma
+ s0 << r4
+ if r4
+ r5 = _nt_expression
+ s0 << r5
+ end
+ end
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(JumptStmt0)
+ r0.extend(JumptStmt1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:jumpt_stmt][start_index] = r0
+
+ return r0
+ end
+
+ module Primary0
+ def space
+ elements[1]
+ end
+
+ def expression
+ elements[2]
+ end
+
+ def space
+ elements[3]
+ end
+
+ end
+
+ module Primary1
+ def eval(env={})
+ expression.eval(env)
+ end
+ end
+
+ def _nt_primary
+ start_index = index
+ if node_cache[:primary].has_key?(index)
+ cached = node_cache[:primary][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0 = index
+ r1 = _nt_ip
+ if r1
+ r0 = r1
+ else
+ r2 = _nt_data_lookup
+ if r2
+ r0 = r2
+ else
+ r3 = _nt_number
+ if r3
+ r0 = r3
+ else
+ i4, s4 = index, []
+ if input.index('(', index) == index
+ r5 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure('(')
+ r5 = nil
+ end
+ s4 << r5
+ if r5
+ r6 = _nt_space
+ s4 << r6
+ if r6
+ r7 = _nt_expression
+ s4 << r7
+ if r7
+ r8 = _nt_space
+ s4 << r8
+ if r8
+ if input.index(')', index) == index
+ r9 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure(')')
+ r9 = nil
+ end
+ s4 << r9
+ end
+ end
+ end
+ end
+ if s4.last
+ r4 = (SyntaxNode).new(input, i4...index, s4)
+ r4.extend(Primary0)
+ r4.extend(Primary1)
+ else
+ self.index = i4
+ r4 = nil
+ end
+ if r4
+ r0 = r4
+ else
+ self.index = i0
+ r0 = nil
+ end
+ end
+ end
+ end
+
+ node_cache[:primary][start_index] = r0
+
+ return r0
+ end
+
+ module DataLookup0
+ def expr
+ elements[1]
+ end
+
+ end
+
+ module DataLookup1
+ def eval(env)
+ env.data[expr.eval(env)]
+ end
+ end
+
+ def _nt_data_lookup
+ start_index = index
+ if node_cache[:data_lookup].has_key?(index)
+ cached = node_cache[:data_lookup][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ if input.index('D[', index) == index
+ r1 = (SyntaxNode).new(input, index...(index + 2))
+ @index += 2
+ else
+ terminal_parse_failure('D[')
+ r1 = nil
+ end
+ s0 << r1
+ if r1
+ r2 = _nt_additive
+ s0 << r2
+ if r2
+ if input.index(']', index) == index
+ r3 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure(']')
+ r3 = nil
+ end
+ s0 << r3
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(DataLookup0)
+ r0.extend(DataLookup1)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:data_lookup][start_index] = r0
+
+ return r0
+ end
+
+ module Ip0
+ def eval(env)
+ env.pc
+ end
+ end
+
+ def _nt_ip
+ start_index = index
+ if node_cache[:ip].has_key?(index)
+ cached = node_cache[:ip][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ if input.index('ip', index) == index
+ r0 = (SyntaxNode).new(input, index...(index + 2))
+ r0.extend(Ip0)
+ @index += 2
+ else
+ terminal_parse_failure('ip')
+ r0 = nil
+ end
+
+ node_cache[:ip][start_index] = r0
+
+ return r0
+ end
+
+ module Comma0
+ def space
+ elements[0]
+ end
+
+ def space
+ elements[2]
+ end
+ end
+
+ def _nt_comma
+ start_index = index
+ if node_cache[:comma].has_key?(index)
+ cached = node_cache[:comma][index]
+ @index = cached.interval.end if cached
+ return cached
+ end
+
+ i0, s0 = index, []
+ r1 = _nt_space
+ s0 << r1
+ if r1
+ if input.index(',', index) == index
+ r2 = (SyntaxNode).new(input, index...(index + 1))
+ @index += 1
+ else
+ terminal_parse_failure(',')
+ r2 = nil
+ end
+ s0 << r2
+ if r2
+ r3 = _nt_space
+ s0 << r3
+ end
+ end
+ if s0.last
+ r0 = (SyntaxNode).new(input, i0...index, s0)
+ r0.extend(Comma0)
+ else
+ self.index = i0
+ r0 = nil
+ end
+
+ node_cache[:comma][start_index] = r0
+
+ return r0
+ end
+
+end
+
+class SimpleSemParser < Treetop::Runtime::CompiledParser
+ include SimpleSem
+end
|
robolson/simplesem
|
db69e0e4cbc9102ebfd3819314c726521a45fe39
|
Added documentation for comments to the README
|
diff --git a/README.textile b/README.textile
index 92346c4..9101118 100644
--- a/README.textile
+++ b/README.textile
@@ -1,122 +1,137 @@
h1. SIMPLESEM Interpreter
+Author: "Rob Olson":http://thinkingdigitally.com
+
h2. Description
Interpreter for the SIMPLESEM language.
-Author: "Rob Olson":http://thinkingdigitally.com
-
-SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
+SIMPLESEM is used in the CS141 Programming Languages course taught by Professor "Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem simplesem_file.txt
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
set 0, 4 * 2
Assign the value stored at location 0 into location 2:
set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
set write, D[0]
Get input from the user and store it at location 1:
set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
+h3. Comments
+
+SIMPLESEM comments begin with two forward slashes. Everything on the line following @//@ is considered a comment and is ignored by the interpreter. *Important*: Comments still consume line numbers! Keep this in mind when writing jump statements.
+
+ // This is line number 0.
+ set write, "foo" // a comment after a statement
+
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre><code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</code></pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<pre><code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</code></pre>
+<pre>
+$ simplesem sample_programs/gcd.txt
+input: 15
+input: 35
+5
+
+DATA: [5, 5, 4]
+</pre>
|
robolson/simplesem
|
e19462855687788e8baec0bc814ecac0779d28ea
|
Renamed test-ip sample program to hello-world. README adjustments.
|
diff --git a/README.textile b/README.textile
index d3c9494..92346c4 100644
--- a/README.textile
+++ b/README.textile
@@ -1,122 +1,122 @@
h1. SIMPLESEM Interpreter
h2. Description
Interpreter for the SIMPLESEM language.
Author: "Rob Olson":http://thinkingdigitally.com
SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem simplesem_file.txt
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
set 0, 4 * 2
Assign the value stored at location 0 into location 2:
set 2, D[0]
h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
set write, D[0]
Get input from the user and store it at location 1:
set 0, read
h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
jump D[0]
h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
jumpt 7, D[1] = D[0]
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h2. Slightly More Advanced Features of SIMPLESEM
h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
set 5, D[D[0]+1]
h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
set D[10], D[15]
h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
set 1, 2+3*4
h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
-The following program will output the text "hello world!" five times and than exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
+The following program will output the text "hello world!" five times and then exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<pre><code>
- set 0, 0
- set write, "hello world!"
- set 0, D[0]+1
- jumpt ip-3, D[0] < 5
- halt
+set 0, 0
+set write, "hello world!"
+set 0, D[0]+1
+jumpt ip-3, D[0] < 5
+halt
</code></pre>
h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<pre><code>
- set 0, read // first number 'n'
- set 1, read // second number 'm'
- set 2, ip + 1 // return pointer for call to GCD
- jump 8
- set write, D[0] // print the GCD
- halt
- jumpt D[2], D[0] = D[1] // while(m != n)
- jumpt 12, D[1] < D[0] // if(m < n)
- set 1, D[1]-D[0]
- jump 13
- set 0, D[0]-D[1]
- jump 8
+set 0, read // first number 'n'
+set 1, read // second number 'm'
+set 2, ip + 1 // return pointer for call to GCD
+jump 8
+set write, D[0] // print the GCD
+halt
+jumpt D[2], D[0] = D[1] // while(m != n)
+jumpt 12, D[1] < D[0] // if(m < n)
+set 1, D[1]-D[0]
+jump 13
+set 0, D[0]-D[1]
+jump 8
</code></pre>
diff --git a/sample_programs/test-ip.txt b/sample_programs/hello-world.txt
similarity index 100%
rename from sample_programs/test-ip.txt
rename to sample_programs/hello-world.txt
diff --git a/simplesem.gemspec b/simplesem.gemspec
index 9331195..ba39b7d 100644
--- a/simplesem.gemspec
+++ b/simplesem.gemspec
@@ -1,37 +1,37 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{simplesem}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Rob Olson"]
- s.date = %q{2009-02-25}
+ s.date = %q{2009-02-26}
s.default_executable = %q{simplesem}
s.description = %q{SIMPLESEM Interpreter}
s.email = %q{[email protected]}
s.executables = ["simplesem"]
s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
- s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/test-ip.txt", "sample_programs/while-loop.txt", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb", "simplesem.gemspec"]
+ s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/hello-world.txt", "sample_programs/while-loop.txt", "simplesem.gemspec", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb"]
s.has_rdoc = true
s.homepage = %q{http://github.com/robolson/simplesem}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Simplesem", "--main", "README.textile"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{simplesem}
s.rubygems_version = %q{1.3.1}
s.summary = %q{SIMPLESEM Interpreter}
s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<treetop>, [">= 0"])
else
s.add_dependency(%q<treetop>, [">= 0"])
end
else
s.add_dependency(%q<treetop>, [">= 0"])
end
end
|
robolson/simplesem
|
dab2251377d3938ec117bfa1e927cc04262b097f
|
Adjusted README formatting to display better on GitHub
|
diff --git a/README.textile b/README.textile
index 8c7646c..d3c9494 100644
--- a/README.textile
+++ b/README.textile
@@ -1,142 +1,122 @@
h1. SIMPLESEM Interpreter
h2. Description
Interpreter for the SIMPLESEM language.
Author: "Rob Olson":http://thinkingdigitally.com
SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem simplesem_file.txt
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
-h3. SIMPLESEM Instructions
-
-h4. SET
+h3. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
-<code>
set 0, 4 * 2
-</code>
Assign the value stored at location 0 into location 2:
-<code>
set 2, D[0]
-</code>
-h4. Input/Output with SET
+h3. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
-<code>
set write, D[0]
-</code>
Get input from the user and store it at location 1:
-<code>
-set 0, read
-</code>
+ set 0, read
-h4. JUMP
+h3. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
-<code>
jump D[0]
-</code>
-h4. JUMPT
+h3. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
-<code>
jumpt 7, D[1] = D[0]
-</code>
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
-h3. Slightly More Advanced Features of SIMPLESEM
+h2. Slightly More Advanced Features of SIMPLESEM
-h4. Nested Data Lookups
+h3. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
-<code>
set 5, D[D[0]+1]
-</code>
-h4. Indirect Addressing
+h3. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
-<code>
set D[10], D[15]
-</code>
-h4. Complex Math Expressions
+h3. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
-<code>
set 1, 2+3*4
-</code>
-h4. Using The Instruction Pointer Variable
+h3. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and than exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
-<code><pre>
+<pre><code>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
-</pre></code>
+</code></pre>
-h3. Sample SIMPLESEM Program
+h3. A Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
-<code><pre>
+<pre><code>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
-</pre></code>
+</code></pre>
|
robolson/simplesem
|
dcfc5f43de1a6523d50a93b771698918239194da
|
Added simplesem.gemspec for publishing the gem on GitHub
|
diff --git a/.gitignore b/.gitignore
index 35fe601..3d424a2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
.DS_Store
coverage/
pkg/
+Manifest
diff --git a/Manifest b/Manifest
deleted file mode 100644
index 41d236a..0000000
--- a/Manifest
+++ /dev/null
@@ -1,16 +0,0 @@
-README.textile
-Rakefile
-bin/simplesem
-lib/simplesem/arithmetic.treetop
-lib/simplesem/arithmetic_node_classes.rb
-lib/simplesem/simple_sem.treetop
-lib/simplesem/simplesem_program.rb
-lib/simplesem.rb
-sample_programs/case-statement.txt
-sample_programs/gcd.txt
-sample_programs/test-ip.txt
-sample_programs/while-loop.txt
-simplesem.tmproj
-test/simplesem_test.rb
-test/test_helper.rb
-Manifest
diff --git a/simplesem.gemspec b/simplesem.gemspec
new file mode 100644
index 0000000..9331195
--- /dev/null
+++ b/simplesem.gemspec
@@ -0,0 +1,37 @@
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{simplesem}
+ s.version = "0.1.0"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Rob Olson"]
+ s.date = %q{2009-02-25}
+ s.default_executable = %q{simplesem}
+ s.description = %q{SIMPLESEM Interpreter}
+ s.email = %q{[email protected]}
+ s.executables = ["simplesem"]
+ s.extra_rdoc_files = ["LICENSE", "README.textile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb"]
+ s.files = ["LICENSE", "Manifest", "README.textile", "Rakefile", "bin/simplesem", "lib/simplesem/arithmetic.treetop", "lib/simplesem/arithmetic_node_classes.rb", "lib/simplesem/simple_sem.treetop", "lib/simplesem/simplesem_program.rb", "lib/simplesem.rb", "sample_programs/case-statement.txt", "sample_programs/gcd.txt", "sample_programs/test-ip.txt", "sample_programs/while-loop.txt", "simplesem.tmproj", "test/simplesem_test.rb", "test/test_helper.rb", "simplesem.gemspec"]
+ s.has_rdoc = true
+ s.homepage = %q{http://github.com/robolson/simplesem}
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Simplesem", "--main", "README.textile"]
+ s.require_paths = ["lib"]
+ s.rubyforge_project = %q{simplesem}
+ s.rubygems_version = %q{1.3.1}
+ s.summary = %q{SIMPLESEM Interpreter}
+ s.test_files = ["test/simplesem_test.rb", "test/test_helper.rb"]
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 2
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_development_dependency(%q<treetop>, [">= 0"])
+ else
+ s.add_dependency(%q<treetop>, [">= 0"])
+ end
+ else
+ s.add_dependency(%q<treetop>, [">= 0"])
+ end
+end
|
robolson/simplesem
|
532990315194a1acf26153b2c7a155726c047c93
|
Gemified simplesem. Rearranged directory structure for packaging as a gem.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..35fe601
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.DS_Store
+coverage/
+pkg/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..96a108b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,183 @@
+Academic Free License (AFL) v. 3.0
+
+This Academic Free License (the "License") applies to any original work
+of authorship (the "Original Work") whose owner (the "Licensor") has
+placed the following licensing notice adjacent to the copyright notice
+for the Original Work:
+
+Licensed under the Academic Free License version 3.0
+
+1) Grant of Copyright License. Licensor grants You a worldwide,
+royalty-free, non-exclusive, sublicensable license, for the duration of
+the copyright, to do the following:
+
+a) to reproduce the Original Work in copies, either alone or as part of
+a collective work;
+
+b) to translate, adapt, alter, transform, modify, or arrange the
+Original Work, thereby creating derivative works ("Derivative Works")
+based upon the Original Work;
+
+c) to distribute or communicate copies of the Original Work and
+Derivative Works to the public, under any license of your choice that
+does not contradict the terms and conditions, including Licensor's
+reserved rights and remedies, in this Academic Free License;
+
+d) to perform the Original Work publicly; and
+
+e) to display the Original Work publicly.
+
+2) Grant of Patent License. Licensor grants You a worldwide,
+royalty-free, non-exclusive, sublicensable license, under patent claims
+owned or controlled by the Licensor that are embodied in the Original
+Work as furnished by the Licensor, for the duration of the patents, to
+make, use, sell, offer for sale, have made, and import the Original Work
+and Derivative Works.
+
+3) Grant of Source Code License. The term "Source Code" means the
+preferred form of the Original Work for making modifications to it and
+all available documentation describing how to modify the Original Work.
+Licensor agrees to provide a machine-readable copy of the Source Code of
+the Original Work along with each copy of the Original Work that
+Licensor distributes. Licensor reserves the right to satisfy this
+obligation by placing a machine-readable copy of the Source Code in an
+information repository reasonably calculated to permit inexpensive and
+convenient access by You for as long as Licensor continues to distribute
+the Original Work.
+
+4) Exclusions From License Grant. Neither the names of Licensor, nor the
+names of any contributors to the Original Work, nor any of their
+trademarks or service marks, may be used to endorse or promote products
+derived from this Original Work without express prior permission of the
+Licensor. Except as expressly stated herein, nothing in this License
+grants any license to Licensor's trademarks, copyrights, patents, trade
+secrets or any other intellectual property. No patent license is granted
+to make, use, sell, offer for sale, have made, or import embodiments of
+any patent claims other than the licensed claims defined in Section 2.
+No license is granted to the trademarks of Licensor even if such marks
+are included in the Original Work. Nothing in this License shall be
+interpreted to prohibit Licensor from licensing under terms different
+from this License any Original Work that Licensor otherwise would have a
+right to license.
+
+5) External Deployment. The term "External Deployment" means the use,
+distribution, or communication of the Original Work or Derivative Works
+in any way such that the Original Work or Derivative Works may be used
+by anyone other than You, whether those works are distributed or
+communicated to those persons or made available as an application
+intended for use over a network. As an express condition for the grants
+of license hereunder, You must treat any External Deployment by You of
+the Original Work or a Derivative Work as a distribution under section
+1(c).
+
+6) Attribution Rights. You must retain, in the Source Code of any
+Derivative Works that You create, all copyright, patent, or trademark
+notices from the Source Code of the Original Work, as well as any
+notices of licensing and any descriptive text identified therein as an
+"Attribution Notice." You must cause the Source Code for any Derivative
+Works that You create to carry a prominent Attribution Notice reasonably
+calculated to inform recipients that You have modified the Original
+Work.
+
+7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants
+that the copyright in and to the Original Work and the patent rights
+granted herein by Licensor are owned by the Licensor or are sublicensed
+to You under the terms of this License with the permission of the
+contributor(s) of those copyrights and patent rights. Except as
+expressly stated in the immediately preceding sentence, the Original
+Work is provided under this License on an "AS IS" BASIS and WITHOUT
+WARRANTY, either express or implied, including, without limitation, the
+warranties of non-infringement, merchantability or fitness for a
+particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL
+WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential
+part of this License. No license to the Original Work is granted by this
+License except under this disclaimer.
+
+8) Limitation of Liability. Under no circumstances and under no legal
+theory, whether in tort (including negligence), contract, or otherwise,
+shall the Licensor be liable to anyone for any indirect, special,
+incidental, or consequential damages of any character arising as a
+result of this License or the use of the Original Work including,
+without limitation, damages for loss of goodwill, work stoppage,
+computer failure or malfunction, or any and all other commercial damages
+or losses. This limitation of liability shall not apply to the extent
+applicable law prohibits such limitation.
+
+9) Acceptance and Termination. If, at any time, You expressly assented
+to this License, that assent indicates your clear and irrevocable
+acceptance of this License and all of its terms and conditions. If You
+distribute or communicate copies of the Original Work or a Derivative
+Work, You must make a reasonable effort under the circumstances to
+obtain the express assent of recipients to the terms of this License.
+This License conditions your rights to undertake the activities listed
+in Section 1, including your right to create Derivative Works based upon
+the Original Work, and doing so without honoring these terms and
+conditions is prohibited by copyright law and international treaty.
+Nothing in this License is intended to affect copyright exceptions and
+limitations (including "fair use" or "fair dealing"). This License shall
+terminate immediately and You may no longer exercise any of the rights
+granted to You by this License upon your failure to honor the conditions
+in Section 1(c).
+
+10) Termination for Patent Action. This License shall terminate
+automatically and You may no longer exercise any of the rights granted
+to You by this License as of the date You commence an action, including
+a cross-claim or counterclaim, against Licensor or any licensee alleging
+that the Original Work infringes a patent. This termination provision
+shall not apply for an action alleging patent infringement by
+combinations of the Original Work with other software or hardware.
+
+11) Jurisdiction, Venue and Governing Law. Any action or suit relating
+to this License may be brought only in the courts of a jurisdiction
+wherein the Licensor resides or in which Licensor conducts its primary
+business, and under the laws of that jurisdiction excluding its
+conflict-of-law provisions. The application of the United Nations
+Convention on Contracts for the International Sale of Goods is expressly
+excluded. Any use of the Original Work outside the scope of this License
+or after its termination shall be subject to the requirements and
+penalties of copyright or patent law in the appropriate jurisdiction.
+This section shall survive the termination of this License.
+
+12) Attorneys' Fees. In any action to enforce the terms of this License
+or seeking damages relating thereto, the prevailing party shall be
+entitled to recover its costs and expenses, including, without
+limitation, reasonable attorneys' fees and costs incurred in connection
+with such action, including any appeal of such action. This section
+shall survive the termination of this License.
+
+13) Miscellaneous. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable.
+
+14) Definition of "You" in This License. "You" throughout this License,
+whether in upper or lower case, means an individual or a legal entity
+exercising rights under, and complying with all of the terms of, this
+License. For legal entities, "You" includes any entity that controls, is
+controlled by, or is under common control with you. For purposes of this
+definition, "control" means (i) the power, direct or indirect, to cause
+the direction or management of such entity, whether by contract or
+otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+15) Right to Use. You may use the Original Work in all ways not
+otherwise restricted or conditioned by this License or by law, and
+Licensor promises not to interfere with or be responsible for such uses
+by You.
+
+16) Modification of This License. This License is Copyright (c) 2005
+Lawrence Rosen. Permission is granted to copy, distribute, or
+communicate this License without modification. Nothing in this License
+permits You to modify this License as applied to the Original Work or to
+Derivative Works. However, You may modify the text of this License and
+copy, distribute or communicate your modified version (the "Modified
+License") and apply it to other original works of authorship subject to
+the following conditions: (i) You may not indicate in any way that your
+Modified License is the "Academic Free License" or "AFL" and you may not
+use those names in the name of your Modified License; (ii) You must
+replace the notice specified in the first paragraph above with the
+notice "Licensed under <insert your license name here>" or with a notice
+of your own that is not confusingly similar to the notice in this
+License; and (iii) You may not claim that your original works are open
+source software unless your Modified License has been approved by Open
+Source Initiative (OSI) and You comply with its license review and
+certification process.
diff --git a/Manifest b/Manifest
new file mode 100644
index 0000000..41d236a
--- /dev/null
+++ b/Manifest
@@ -0,0 +1,16 @@
+README.textile
+Rakefile
+bin/simplesem
+lib/simplesem/arithmetic.treetop
+lib/simplesem/arithmetic_node_classes.rb
+lib/simplesem/simple_sem.treetop
+lib/simplesem/simplesem_program.rb
+lib/simplesem.rb
+sample_programs/case-statement.txt
+sample_programs/gcd.txt
+sample_programs/test-ip.txt
+sample_programs/while-loop.txt
+simplesem.tmproj
+test/simplesem_test.rb
+test/test_helper.rb
+Manifest
diff --git a/README.textile b/README.textile
index 1731c0a..8c7646c 100644
--- a/README.textile
+++ b/README.textile
@@ -1,142 +1,142 @@
h1. SIMPLESEM Interpreter
h2. Description
Interpreter for the SIMPLESEM language.
Author: "Rob Olson":http://thinkingdigitally.com
SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
- $ simplesem source_file.txt
+ $ simplesem simplesem_file.txt
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SIMPLESEM Instructions
h4. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
<code>
set 0, 4 * 2
</code>
Assign the value stored at location 0 into location 2:
<code>
set 2, D[0]
</code>
h4. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
<code>
set write, D[0]
</code>
Get input from the user and store it at location 1:
<code>
set 0, read
</code>
h4. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
<code>
jump D[0]
</code>
h4. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
<code>
jumpt 7, D[1] = D[0]
</code>
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Slightly More Advanced Features of SIMPLESEM
h4. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
<code>
set 5, D[D[0]+1]
</code>
h4. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
<code>
set D[10], D[15]
</code>
h4. Complex Math Expressions
SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
<code>
set 1, 2+3*4
</code>
h4. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and than exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<code><pre>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</pre></code>
h3. Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<code><pre>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</pre></code>
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..f650dae
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,13 @@
+require 'rubygems'
+require 'rake'
+require 'echoe'
+
+Echoe.new('simplesem', '0.1.0') do |p|
+ p.description = "SIMPLESEM Interpreter"
+ p.url = "http://github.com/robolson/simplesem"
+ p.author = "Rob Olson"
+ p.email = "[email protected]"
+ p.development_dependencies = ['treetop']
+end
+
+Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
diff --git a/arithmetic.rb b/arithmetic.rb
deleted file mode 100644
index 8f74129..0000000
--- a/arithmetic.rb
+++ /dev/null
@@ -1,551 +0,0 @@
-module Arithmetic
- include Treetop::Runtime
-
- def root
- @root || :expression
- end
-
- def _nt_expression
- start_index = index
- cached = node_cache[:expression][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- r1 = _nt_comparative
- if r1.success?
- r0 = r1
- else
- r2 = _nt_additive
- if r2.success?
- r0 = r2
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:expression][start_index] = r0
-
- return r0
- end
-
- module Comparative0
- def operand_1
- elements[0]
- end
-
- def space
- elements[1]
- end
-
- def operator
- elements[2]
- end
-
- def space
- elements[3]
- end
-
- def operand_2
- elements[4]
- end
- end
-
- def _nt_comparative
- start_index = index
- cached = node_cache[:comparative][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0, s0 = index, []
- r1 = _nt_additive
- s0 << r1
- if r1.success?
- r2 = _nt_space
- s0 << r2
- if r2.success?
- r3 = _nt_equality_op
- s0 << r3
- if r3.success?
- r4 = _nt_space
- s0 << r4
- if r4.success?
- r5 = _nt_additive
- s0 << r5
- end
- end
- end
- end
- if s0.last.success?
- r0 = (BinaryOperation).new(input, i0...index, s0)
- r0.extend(Comparative0)
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
-
- node_cache[:comparative][start_index] = r0
-
- return r0
- end
-
- module EqualityOp0
- def apply(a, b)
- a == b
- end
- end
-
- def _nt_equality_op
- start_index = index
- cached = node_cache[:equality_op][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- r0 = parse_terminal('==', SyntaxNode, EqualityOp0)
-
- node_cache[:equality_op][start_index] = r0
-
- return r0
- end
-
- module Additive0
- def operand_1
- elements[0]
- end
-
- def space
- elements[1]
- end
-
- def operator
- elements[2]
- end
-
- def space
- elements[3]
- end
-
- def operand_2
- elements[4]
- end
- end
-
- def _nt_additive
- start_index = index
- cached = node_cache[:additive][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- i1, s1 = index, []
- r2 = _nt_multitive
- s1 << r2
- if r2.success?
- r3 = _nt_space
- s1 << r3
- if r3.success?
- r4 = _nt_additive_op
- s1 << r4
- if r4.success?
- r5 = _nt_space
- s1 << r5
- if r5.success?
- r6 = _nt_additive
- s1 << r6
- end
- end
- end
- end
- if s1.last.success?
- r1 = (BinaryOperation).new(input, i1...index, s1)
- r1.extend(Additive0)
- else
- self.index = i1
- r1 = ParseFailure.new(input, i1)
- end
- if r1.success?
- r0 = r1
- else
- r7 = _nt_multitive
- if r7.success?
- r0 = r7
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:additive][start_index] = r0
-
- return r0
- end
-
- module AdditiveOp0
- def apply(a, b)
- a + b
- end
- end
-
- module AdditiveOp1
- def apply(a, b)
- a - b
- end
- end
-
- def _nt_additive_op
- start_index = index
- cached = node_cache[:additive_op][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- r1 = parse_terminal('+', SyntaxNode, AdditiveOp0)
- if r1.success?
- r0 = r1
- else
- r2 = parse_terminal('-', SyntaxNode, AdditiveOp1)
- if r2.success?
- r0 = r2
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:additive_op][start_index] = r0
-
- return r0
- end
-
- module Multitive0
- def operand_1
- elements[0]
- end
-
- def space
- elements[1]
- end
-
- def operator
- elements[2]
- end
-
- def space
- elements[3]
- end
-
- def operand_2
- elements[4]
- end
- end
-
- def _nt_multitive
- start_index = index
- cached = node_cache[:multitive][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- i1, s1 = index, []
- r2 = _nt_primary
- s1 << r2
- if r2.success?
- r3 = _nt_space
- s1 << r3
- if r3.success?
- r4 = _nt_multitive_op
- s1 << r4
- if r4.success?
- r5 = _nt_space
- s1 << r5
- if r5.success?
- r6 = _nt_multitive
- s1 << r6
- end
- end
- end
- end
- if s1.last.success?
- r1 = (BinaryOperation).new(input, i1...index, s1)
- r1.extend(Multitive0)
- else
- self.index = i1
- r1 = ParseFailure.new(input, i1)
- end
- if r1.success?
- r0 = r1
- else
- r7 = _nt_primary
- if r7.success?
- r0 = r7
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:multitive][start_index] = r0
-
- return r0
- end
-
- module MultitiveOp0
- def apply(a, b)
- a * b
- end
- end
-
- module MultitiveOp1
- def apply(a, b)
- a / b
- end
- end
-
- def _nt_multitive_op
- start_index = index
- cached = node_cache[:multitive_op][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- r1 = parse_terminal('*', SyntaxNode, MultitiveOp0)
- if r1.success?
- r0 = r1
- else
- r2 = parse_terminal('/', SyntaxNode, MultitiveOp1)
- if r2.success?
- r0 = r2
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:multitive_op][start_index] = r0
-
- return r0
- end
-
- module Primary0
- def space
- elements[1]
- end
-
- def expression
- elements[2]
- end
-
- def space
- elements[3]
- end
-
- end
-
- module Primary1
- def eval(env={})
- expression.eval(env)
- end
- end
-
- def _nt_primary
- start_index = index
- cached = node_cache[:primary][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- r1 = _nt_variable
- if r1.success?
- r0 = r1
- else
- r2 = _nt_number
- if r2.success?
- r0 = r2
- else
- i3, s3 = index, []
- r4 = parse_terminal('(', SyntaxNode)
- s3 << r4
- if r4.success?
- r5 = _nt_space
- s3 << r5
- if r5.success?
- r6 = _nt_expression
- s3 << r6
- if r6.success?
- r7 = _nt_space
- s3 << r7
- if r7.success?
- r8 = parse_terminal(')', SyntaxNode)
- s3 << r8
- end
- end
- end
- end
- if s3.last.success?
- r3 = (SyntaxNode).new(input, i3...index, s3)
- r3.extend(Primary0)
- r3.extend(Primary1)
- else
- self.index = i3
- r3 = ParseFailure.new(input, i3)
- end
- if r3.success?
- r0 = r3
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
- end
-
- node_cache[:primary][start_index] = r0
-
- return r0
- end
-
- module Variable0
- def eval(env={})
- env[name]
- end
-
- def name
- text_value
- end
- end
-
- def _nt_variable
- start_index = index
- cached = node_cache[:variable][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- s0, i0 = [], index
- loop do
- r1 = parse_char_class(/[a-z]/, 'a-z', SyntaxNode)
- if r1.success?
- s0 << r1
- else
- break
- end
- end
- if s0.empty?
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- else
- r0 = SyntaxNode.new(input, i0...index, s0)
- r0.extend(Variable0)
- end
-
- node_cache[:variable][start_index] = r0
-
- return r0
- end
-
- module Number0
- end
-
- module Number1
- def eval(env={})
- text_value.to_i
- end
- end
-
- def _nt_number
- start_index = index
- cached = node_cache[:number][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- i0 = index
- i1, s1 = index, []
- r2 = parse_char_class(/[1-9]/, '1-9', SyntaxNode)
- s1 << r2
- if r2.success?
- s3, i3 = [], index
- loop do
- r4 = parse_char_class(/[0-9]/, '0-9', SyntaxNode)
- if r4.success?
- s3 << r4
- else
- break
- end
- end
- r3 = SyntaxNode.new(input, i3...index, s3)
- s1 << r3
- end
- if s1.last.success?
- r1 = (SyntaxNode).new(input, i1...index, s1)
- r1.extend(Number0)
- else
- self.index = i1
- r1 = ParseFailure.new(input, i1)
- end
- if r1.success?
- r0 = r1
- r0.extend(Number1)
- else
- r5 = parse_terminal('0', SyntaxNode)
- if r5.success?
- r0 = r5
- r0.extend(Number1)
- else
- self.index = i0
- r0 = ParseFailure.new(input, i0)
- end
- end
-
- node_cache[:number][start_index] = r0
-
- return r0
- end
-
- def _nt_space
- start_index = index
- cached = node_cache[:space][index]
- if cached
- @index = cached.interval.end
- return cached
- end
-
- s0, i0 = [], index
- loop do
- r1 = parse_terminal(' ', SyntaxNode)
- if r1.success?
- s0 << r1
- else
- break
- end
- end
- r0 = SyntaxNode.new(input, i0...index, s0)
-
- node_cache[:space][start_index] = r0
-
- return r0
- end
-
-end
-
-class ArithmeticParser < Treetop::Runtime::CompiledParser
- include Arithmetic
-end
diff --git a/bin/simplesem b/bin/simplesem
new file mode 100755
index 0000000..a76fc2a
--- /dev/null
+++ b/bin/simplesem
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+require 'rubygems'
+
+$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
+require 'simplesem'
+
+if ARGV.empty?
+ puts "Usage:\n\nsimplesem simplesem_file.txt\n\n"
+ exit
+end
+
+ssp = SimpleSemProgram.new(ARGV.shift)
+ssp.run
+
+puts "\nDATA: " + ssp.data.inspect
\ No newline at end of file
diff --git a/lib/simplesem.rb b/lib/simplesem.rb
new file mode 100644
index 0000000..b9958e9
--- /dev/null
+++ b/lib/simplesem.rb
@@ -0,0 +1,2 @@
+dir = File.dirname(__FILE__)
+require "#{dir}/simplesem/simplesem_program"
\ No newline at end of file
diff --git a/arithmetic.treetop b/lib/simplesem/arithmetic.treetop
similarity index 100%
rename from arithmetic.treetop
rename to lib/simplesem/arithmetic.treetop
diff --git a/arithmetic_node_classes.rb b/lib/simplesem/arithmetic_node_classes.rb
similarity index 100%
rename from arithmetic_node_classes.rb
rename to lib/simplesem/arithmetic_node_classes.rb
diff --git a/simple_sem.treetop b/lib/simplesem/simple_sem.treetop
similarity index 100%
rename from simple_sem.treetop
rename to lib/simplesem/simple_sem.treetop
diff --git a/simple_sem_program.rb b/lib/simplesem/simplesem_program.rb
similarity index 100%
rename from simple_sem_program.rb
rename to lib/simplesem/simplesem_program.rb
diff --git a/simplesem.rb b/simplesem.rb
deleted file mode 100755
index 7038ebf..0000000
--- a/simplesem.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/env ruby
-dir = File.dirname(__FILE__)
-require File.expand_path("#{dir}/simple_sem_program")
-
-ssp = SimpleSemProgram.new(ARGV[0])
-ssp.run
-
-puts "\nDATA: " + ssp.data.inspect
\ No newline at end of file
diff --git a/simple_sem_test.rb b/test/simplesem_test.rb
similarity index 92%
rename from simple_sem_test.rb
rename to test/simplesem_test.rb
index 56e339a..e6ac282 100644
--- a/simple_sem_test.rb
+++ b/test/simplesem_test.rb
@@ -1,122 +1,119 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
-require File.expand_path("#{dir}/simple_sem_program")
-require File.expand_path("#{dir}/arithmetic_node_classes")
-
-Treetop.load File.expand_path("#{dir}/arithmetic")
-Treetop.load File.expand_path("#{dir}/simple_sem")
+libdir = dir + "/../lib"
+require File.expand_path("#{libdir}/simplesem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, "hello world!"').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_complex_expr
@ssp.data[1] = 2
parse('set 2, D[0]+D[1]*2').execute(@ssp)
assert_equal 5, @ssp.data[2]
end
def test_parenthesis
@ssp.data[1] = 2
parse('set 2, (D[0]+D[1])*2').execute(@ssp)
assert_equal 6, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
def test_nested_data_lookup
@ssp.data[0] = 0
@ssp.data[1] = 1
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2]
end
def test_instruction_pointer
# run two dummy instructions, manually incrementing the program counter
@ssp.pc = 1
parse('set 0, 0').execute(@ssp)
@ssp.pc = 2
parse('set 0, ip').execute(@ssp)
assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
\ No newline at end of file
diff --git a/test_helper.rb b/test/test_helper.rb
similarity index 100%
rename from test_helper.rb
rename to test/test_helper.rb
|
robolson/simplesem
|
139ec723795b865e26a25103f0ccf72c09a1939f
|
Support for complex expressions and expressions with parenthesis
|
diff --git a/README.textile b/README.textile
index 0b0a2ee..1731c0a 100644
--- a/README.textile
+++ b/README.textile
@@ -1,132 +1,142 @@
h1. SIMPLESEM Interpreter
h2. Description
Interpreter for the SIMPLESEM language.
+Author: "Rob Olson":http://thinkingdigitally.com
+
SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
h2. Installation and Usage
Install the simplesem gem with:
$ sudo gem install robolson-simplesem
Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
$ simplesem source_file.txt
h2. Introduction to SIMPLESEM
SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
h3. SIMPLESEM Instructions
h4. SET
The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
Evaluate the expression (4 * 2) and places the result into location 0:
<code>
set 0, 4 * 2
</code>
Assign the value stored at location 0 into location 2:
<code>
set 2, D[0]
</code>
h4. Input/Output with SET
The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
Print the value stored at location 0:
<code>
set write, D[0]
</code>
Get input from the user and store it at location 1:
<code>
set 0, read
</code>
h4. JUMP
The @jump@ command performs and unconditional jump to the line number specified.
Jump program execution to the address at location 0:
<code>
jump D[0]
</code>
h4. JUMPT
The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
<code>
jumpt 7, D[1] = D[0]
</code>
SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
h3. Slightly More Advanced Features of SIMPLESEM
h4. Nested Data Lookups
SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
<code>
set 5, D[D[0]+1]
</code>
h4. Indirect Addressing
Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
<code>
set D[10], D[15]
</code>
+h4. Complex Math Expressions
+
+SIMPLESEM supports standard mathematical order of operations. The following statement sets location 1 to 14 as expected:
+
+<code>
+ set 1, 2+3*4
+</code>
+
h4. Using The Instruction Pointer Variable
At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
The following program will output the text "hello world!" five times and than exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
<code><pre>
set 0, 0
set write, "hello world!"
set 0, D[0]+1
jumpt ip-3, D[0] < 5
halt
</pre></code>
h3. Sample SIMPLESEM Program
The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
<code><pre>
set 0, read // first number 'n'
set 1, read // second number 'm'
set 2, ip + 1 // return pointer for call to GCD
jump 8
set write, D[0] // print the GCD
halt
jumpt D[2], D[0] = D[1] // while(m != n)
jumpt 12, D[1] < D[0] // if(m < n)
set 1, D[1]-D[0]
jump 13
set 0, D[0]-D[1]
jump 8
</pre></code>
diff --git a/arithmetic.treetop b/arithmetic.treetop
index 2a77be4..1d0b0b4 100644
--- a/arithmetic.treetop
+++ b/arithmetic.treetop
@@ -1,95 +1,99 @@
grammar Arithmetic
- rule arithmetic_expression
- comparative / additive / multitive
+ rule expression
+ comparative / additive
end
rule comparative
- operand_1:expression space operator:comparison_op space operand_2:expression <BinaryOperation>
+ operand_1:additive space operator:comparison_op space operand_2:additive <BinaryOperation>
end
rule comparison_op
'>=' {
def apply(a, b)
a >= b
end
}
/
'<=' {
def apply(a, b)
a <= b
end
}
/
'>' {
def apply(a, b)
a > b
end
}
/
'<' {
def apply(a, b)
a < b
end
}
/
'!=' {
def apply(a, b)
a != b
end
}
/
'=' {
def apply(a, b)
a == b
end
}
end
rule additive
- operand_1:expression space operator:additive_op space operand_2:expression <BinaryOperation>
+ operand_1:multitive space operator:additive_op space operand_2:additive <BinaryOperation>
+ /
+ multitive
end
rule additive_op
'+' {
def apply(a, b)
a + b
end
}
/
'-' {
def apply(a, b)
a - b
end
}
end
rule multitive
- operand_1:expression space operator:multitive_op space operand_2:expression <BinaryOperation>
+ operand_1:primary space operator:multitive_op space operand_2:multitive <BinaryOperation>
+ /
+ primary
end
rule multitive_op
'*' {
def apply(a, b)
a * b
end
}
/
'/' {
def apply(a, b)
a / b
end
}
end
rule number
('-'? [1-9] [0-9]* / '0') {
def eval(env={})
text_value.to_i
end
}
end
rule space
' '*
end
end
\ No newline at end of file
diff --git a/simple_sem.treetop b/simple_sem.treetop
index 3f1d51d..18ee634 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,103 +1,103 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
raise ProgramHalt
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
- 'set' space location:primary comma value:primary {
+ 'set' space loc:additive comma value:additive {
def execute(env)
- env.data[location.eval(env)] = value.eval(env)
+ env.data[loc.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
/
'set' space 'write' comma '"' string:(!'"' . )* '"' {
def execute(env)
puts string.text_value
end
}
end
rule set_stmt_read
- 'set' space expression comma 'read' {
+ 'set' space loc:additive comma 'read' {
def execute(env)
print "input: "
- env.data[expression.eval(env)] = $stdin.gets.strip.to_i
+ env.data[loc.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
- 'jump' space loc:expression {
+ 'jump' space loc:additive {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
- 'jumpt' space loc:expression comma comparative {
+ 'jumpt' space loc:additive comma expression {
def execute(env)
- if comparative.eval(env)
+ if expression.eval(env)
env.pc = loc.eval(env)
end
end
}
end
- rule expression
- ip / data_lookup / number
- end
-
rule primary
- arithmetic_expression
- /
ip
/
data_lookup
/
number
+ /
+ '(' space expression space ')' {
+ def eval(env={})
+ expression.eval(env)
+ end
+ }
end
rule data_lookup
- 'D[' primary ']' {
+ 'D[' expr:additive ']' {
def eval(env)
- env.data[primary.eval(env)]
+ env.data[expr.eval(env)]
end
}
end
rule ip
'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index 9d49b11..56e339a 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,116 +1,122 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, "hello world!"').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
- def test_set_w_advanced_expr
+ def test_complex_expr
@ssp.data[1] = 2
- parse('set 2, D[1]+D[0]').execute(@ssp)
- assert_equal 3, @ssp.data[2]
+ parse('set 2, D[0]+D[1]*2').execute(@ssp)
+ assert_equal 5, @ssp.data[2]
+ end
+
+ def test_parenthesis
+ @ssp.data[1] = 2
+ parse('set 2, (D[0]+D[1])*2').execute(@ssp)
+ assert_equal 6, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
def test_nested_data_lookup
@ssp.data[0] = 0
@ssp.data[1] = 1
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2]
end
def test_instruction_pointer
# run two dummy instructions, manually incrementing the program counter
@ssp.pc = 1
parse('set 0, 0').execute(@ssp)
@ssp.pc = 2
parse('set 0, ip').execute(@ssp)
assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
def test_halt
assert_raise ProgramHalt do
parse('halt').execute(@ssp)
end
end
end
\ No newline at end of file
|
robolson/simplesem
|
eaa378b12a87f3f43636583830abee36bd7d1116
|
Adding 4 sample SIMPLESEM programs to sample_programs/
|
diff --git a/programs/whileloop.c1.txt b/sample_programs/case-statement.txt
similarity index 100%
rename from programs/whileloop.c1.txt
rename to sample_programs/case-statement.txt
diff --git a/sample_programs/gcd.txt b/sample_programs/gcd.txt
new file mode 100644
index 0000000..aa96001
--- /dev/null
+++ b/sample_programs/gcd.txt
@@ -0,0 +1,12 @@
+set 0, read // first number 'n'
+set 1, read // second number 'm'
+set 2, ip + 1 // return pointer for call to GCD
+jump 6
+set write, D[0] // print the GCD
+halt
+jumpt D[2], D[0] = D[1] // while(m != n)
+jumpt 10, D[1] < D[0] // if(m < n)
+set 1, D[1]-D[0]
+jump 11
+set 0, D[0]-D[1]
+jump 6
\ No newline at end of file
diff --git a/sample_programs/test-ip.txt b/sample_programs/test-ip.txt
new file mode 100644
index 0000000..85aefa6
--- /dev/null
+++ b/sample_programs/test-ip.txt
@@ -0,0 +1,5 @@
+set 0, 0
+set write, "hello world!"
+set 0, D[0]+1
+jumpt ip-3, D[0] < 5
+halt
\ No newline at end of file
diff --git a/sample_programs/while-loop.txt b/sample_programs/while-loop.txt
new file mode 100644
index 0000000..35508f5
--- /dev/null
+++ b/sample_programs/while-loop.txt
@@ -0,0 +1,14 @@
+set 0, 4
+set 1, 1
+set 2, -1
+jumpt 10, D[0] <= D[2]
+jumpt 7, D[0] != 0
+set write, D[1]
+jump 8
+set 1, D[1]+D[0]
+set 0, D[0] - 1
+jump 3
+set write, D[0]
+set write, D[1]
+set write, D[2]
+halt
\ No newline at end of file
|
robolson/simplesem
|
70c63e8227a7d800163dfa6f55e7fd329ff7b508
|
* support for outputting strings (before it was just numbers) * no longer outputs "program halted" upon executing a halt command
|
diff --git a/simple_sem.treetop b/simple_sem.treetop
index 79b37b6..3f1d51d 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,97 +1,103 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
raise ProgramHalt
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
'set' space location:primary comma value:primary {
def execute(env)
env.data[location.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
+ /
+ 'set' space 'write' comma '"' string:(!'"' . )* '"' {
+ def execute(env)
+ puts string.text_value
+ end
+ }
end
rule set_stmt_read
'set' space expression comma 'read' {
def execute(env)
print "input: "
env.data[expression.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
'jump' space loc:expression {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:expression comma comparative {
def execute(env)
if comparative.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule expression
ip / data_lookup / number
end
rule primary
arithmetic_expression
/
ip
/
data_lookup
/
number
end
rule data_lookup
'D[' primary ']' {
def eval(env)
env.data[primary.eval(env)]
end
}
end
rule ip
'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
end
\ No newline at end of file
diff --git a/simple_sem_program.rb b/simple_sem_program.rb
index 9574f91..f377dfd 100644
--- a/simple_sem_program.rb
+++ b/simple_sem_program.rb
@@ -1,46 +1,45 @@
require 'rubygems'
require 'treetop'
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class ProgramHalt < Exception
end
class SimpleSemProgram
attr_reader :code
attr_accessor :data, :pc
# Create a SimpleSemProgram instance
# Params:
# (String)filepath: path to SimpleSem source file.
# Optional because it's useful to use in tests without needing to load a file
def initialize filepath=nil
@code = Array.new
if filepath
IO.foreach(filepath) do |line|
@code << line.split("//", 2)[0].strip # seperate the comment from the code
end
end
@data = Array.new
@pc = 0
end
def run
@parser = SimpleSemParser.new
@pc = 0
loop do
- @pc += 1
- instruction = @code[@pc-1]
+ instruction = @code[@pc] # fetch
+ @pc += 1 # increment
begin
- @parser.parse(instruction).execute(self)
+ @parser.parse(instruction).execute(self) # decode and execute
rescue ProgramHalt
- puts "program halted"
break
end
end
end
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index 69f0042..9d49b11 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,111 +1,116 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
- assert_nil parse('set write, 1').execute(@ssp)
+ assert_nil parse('set write, "hello world!"').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_set_w_advanced_expr
@ssp.data[1] = 2
parse('set 2, D[1]+D[0]').execute(@ssp)
assert_equal 3, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
def test_nested_data_lookup
@ssp.data[0] = 0
@ssp.data[1] = 1
parse('set 2, D[D[0]+1]').execute(@ssp)
assert_equal 1, @ssp.data[2]
end
def test_instruction_pointer
# run two dummy instructions, manually incrementing the program counter
@ssp.pc = 1
parse('set 0, 0').execute(@ssp)
@ssp.pc = 2
parse('set 0, ip').execute(@ssp)
assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_less_than_comparison
# test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_comparison
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_greater_than_or_eql_comparison
parse('jumpt 5, 1 >= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
+ def test_halt
+ assert_raise ProgramHalt do
+ parse('halt').execute(@ssp)
+ end
+ end
end
\ No newline at end of file
diff --git a/simplesem.rb b/simplesem.rb
index 894e7e1..7038ebf 100755
--- a/simplesem.rb
+++ b/simplesem.rb
@@ -1,8 +1,8 @@
#!/usr/bin/env ruby
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/simple_sem_program")
ssp = SimpleSemProgram.new(ARGV[0])
ssp.run
-puts "\n" + ssp.data.inspect
\ No newline at end of file
+puts "\nDATA: " + ssp.data.inspect
\ No newline at end of file
|
robolson/simplesem
|
0f489b2d1930441bf4bacd8067ed770cf003b58a
|
First cut at writing the README file
|
diff --git a/README.textile b/README.textile
new file mode 100644
index 0000000..0b0a2ee
--- /dev/null
+++ b/README.textile
@@ -0,0 +1,132 @@
+h1. SIMPLESEM Interpreter
+
+h2. Description
+
+Interpreter for the SIMPLESEM language.
+
+SIMPLESEM is used in the CS141 Programming Languages course taught by "Professor Shannon Tauro":http://www.ics.uci.edu/~stauro/ at UC Irvine. This Rubygem was created out of my desire to execute SIMPLESEM programs. To my knowledge, there are none publicly available.
+
+This interpreter utilizes Nathan Sobo's "Treetop":http://github.com/nathansobo/treetop gem to create a parsing expression grammar for parsing SIMPLESEM commands.
+
+h2. Installation and Usage
+
+Install the simplesem gem with:
+
+ $ sudo gem install robolson-simplesem
+
+Execute a SIMPLESEM program using the simplesem command. Pass the filename of the SIMLESEM source file as an argument.
+
+ $ simplesem source_file.txt
+
+h2. Introduction to SIMPLESEM
+
+SIMPLESEM is an abstract semantic processor that is based on the Von Neumann model of the fetch-execute cycle.
+
+h3. SIMPLESEM Instructions
+
+h4. SET
+
+The @set@ command is used to modify the value stored in a cell. It takes two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.
+
+Evaluate the expression (4 * 2) and places the result into location 0:
+
+<code>
+ set 0, 4 * 2
+</code>
+
+Assign the value stored at location 0 into location 2:
+
+<code>
+ set 2, D[0]
+</code>
+
+h4. Input/Output with SET
+
+The @set@ command is also used to print to the screen and to get input from the user, through the special registers @read@ and @write@.
+
+Print the value stored at location 0:
+
+<code>
+ set write, D[0]
+</code>
+
+Get input from the user and store it at location 1:
+
+<code>
+set 0, read
+</code>
+
+h4. JUMP
+
+The @jump@ command performs and unconditional jump to the line number specified.
+
+Jump program execution to the address at location 0:
+
+<code>
+ jump D[0]
+</code>
+
+h4. JUMPT
+
+The @jumpt@ command (pronounced jump-true), is a conditional jump. It only jumps if the expression given is true.
+
+Jump to line 7 if the value at <notextile>D[1]</notextile> is equal to the value at <notextile>D[0]</notextile>:
+
+<code>
+ jumpt 7, D[1] = D[0]
+</code>
+
+SIMPLESEM supports all the common comparison operators: >, <, >=, <=, !=, and =. Take note that the equality operator is a single '=' sign, not the usual '=='.
+
+h3. Slightly More Advanced Features of SIMPLESEM
+
+h4. Nested Data Lookups
+
+SIMPLESEM supports nesting expressions inside of the address location for accessing the data array. This statement looks up the value at location 0, adds 1 to it, then uses the result as the address of another data lookup. If <notextile>D[0]</notextile> contains the value 9--this statement will set location 5 with the value at location 10.
+
+<code>
+ set 5, D[D[0]+1]
+</code>
+
+h4. Indirect Addressing
+
+Assigns the value stored at location 15 into the cell whose address is the value stored at location 10:
+
+<code>
+ set D[10], D[15]
+</code>
+
+h4. Using The Instruction Pointer Variable
+
+At any point you can use the @ip@ placeholder in your code and it will evaluate to the current value of the instruction pointer, also known as the program counter. The ip is always 1 greater than the current line number because in the fetch-execute cycle the processor increments the ip after fetching the next instruction and executing it.
+
+The following program will output the text "hello world!" five times and than exit. It uses the @ip@ variable to jump execution back to the @set write@ statement.
+
+<code><pre>
+ set 0, 0
+ set write, "hello world!"
+ set 0, D[0]+1
+ jumpt ip-3, D[0] < 5
+ halt
+</pre></code>
+
+h3. Sample SIMPLESEM Program
+
+The following SIMPLESEM program calculates the "GCD":http://en.wikipedia.org/wiki/Greatest_common_divisor of two numbers. The program prompts the user to enter the two numbers when the program is executed. This program is also included in the @sample_programs@ folder.
+
+<code><pre>
+ set 0, read // first number 'n'
+ set 1, read // second number 'm'
+ set 2, ip + 1 // return pointer for call to GCD
+ jump 8
+ set write, D[0] // print the GCD
+ halt
+ jumpt D[2], D[0] = D[1] // while(m != n)
+ jumpt 12, D[1] < D[0] // if(m < n)
+ set 1, D[1]-D[0]
+ jump 13
+ set 0, D[0]-D[1]
+ jump 8
+</pre></code>
+
+
|
robolson/simplesem
|
4e0ca72914ab38b037b2848e43c1a11d2093608e
|
* Change halt command to throw custom exception * Unit test refinement
|
diff --git a/simple_sem.treetop b/simple_sem.treetop
index c04413d..79b37b6 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,97 +1,97 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
- throw "halt!"
+ raise ProgramHalt
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
'set' space location:primary comma value:primary {
def execute(env)
env.data[location.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
end
rule set_stmt_read
'set' space expression comma 'read' {
def execute(env)
print "input: "
env.data[expression.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
'jump' space loc:expression {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:expression comma comparative {
def execute(env)
if comparative.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule expression
ip / data_lookup / number
end
rule primary
arithmetic_expression
/
ip
/
data_lookup
/
number
end
rule data_lookup
'D[' primary ']' {
def eval(env)
env.data[primary.eval(env)]
end
}
end
rule ip
'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
end
\ No newline at end of file
diff --git a/simple_sem_program.rb b/simple_sem_program.rb
index 8d6e580..9574f91 100644
--- a/simple_sem_program.rb
+++ b/simple_sem_program.rb
@@ -1,44 +1,46 @@
require 'rubygems'
require 'treetop'
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
+class ProgramHalt < Exception
+end
+
class SimpleSemProgram
attr_reader :code
attr_accessor :data, :pc
# Create a SimpleSemProgram instance
# Params:
# (String)filepath: path to SimpleSem source file.
- # Optional because it's useful to use in tests without needing to load a file
+ # Optional because it's useful to use in tests without needing to load a file
def initialize filepath=nil
@code = Array.new
if filepath
IO.foreach(filepath) do |line|
@code << line.split("//", 2)[0].strip # seperate the comment from the code
end
end
@data = Array.new
@pc = 0
end
- # alias :ip :pc
def run
@parser = SimpleSemParser.new
@pc = 0
loop do
@pc += 1
instruction = @code[@pc-1]
begin
@parser.parse(instruction).execute(self)
- rescue
+ rescue ProgramHalt
puts "program halted"
break
end
end
end
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index 1f2931e..69f0042 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,98 +1,111 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, 1').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_set_w_advanced_expr
@ssp.data[1] = 2
parse('set 2, D[1]+D[0]').execute(@ssp)
assert_equal 3, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
+ def test_nested_data_lookup
+ @ssp.data[0] = 0
+ @ssp.data[1] = 1
+ parse('set 2, D[D[0]+1]').execute(@ssp)
+ assert_equal 1, @ssp.data[2]
+ end
+
def test_instruction_pointer
# run two dummy instructions, manually incrementing the program counter
@ssp.pc = 1
parse('set 0, 0').execute(@ssp)
@ssp.pc = 2
parse('set 0, ip').execute(@ssp)
assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
end
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
- def test_comparison_greater_than
- parse('jumpt 5, D[0] > 0').execute(@ssp)
- assert_equal 5, @ssp.pc
- end
-
- def test_comparison_greater_than
+ def test_less_than_comparison
+ # test a jumpt that returns false
parse('jumpt 5, D[0] < 0').execute(@ssp)
- assert_equal 0, @ssp.pc
+ assert_not_equal 5, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
- def test_comparison_greater_than_or_eql
+ def test_greater_than_comparison
+ parse('jumpt 5, D[0] > 0').execute(@ssp)
+ assert_equal 5, @ssp.pc
+ end
+
+ def test_greater_than_or_eql_comparison
+ parse('jumpt 5, 1 >= D[0]').execute(@ssp)
+ assert_equal 5, @ssp.pc
+ end
+
+ def test_less_than_or_eql_comparison
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
end
\ No newline at end of file
|
robolson/simplesem
|
a54cb189c6f2b6cad0a405255b98e6406602445d
|
Added support for using the ip (instruction pointer) variable in commands
|
diff --git a/simple_sem.treetop b/simple_sem.treetop
index fa578ea..c04413d 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,95 +1,97 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
throw "halt!"
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
'set' space location:primary comma value:primary {
def execute(env)
env.data[location.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
end
rule set_stmt_read
'set' space expression comma 'read' {
def execute(env)
print "input: "
env.data[expression.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
'jump' space loc:expression {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:expression comma comparative {
def execute(env)
if comparative.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule expression
- data_lookup / number
+ ip / data_lookup / number
end
rule primary
arithmetic_expression
/
+ ip
+ /
data_lookup
/
number
end
rule data_lookup
'D[' primary ']' {
def eval(env)
env.data[primary.eval(env)]
end
}
end
- rule pc
- 'pc' / 'ip' {
+ rule ip
+ 'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index 9f56774..1f2931e 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,89 +1,98 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, 1').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_set_to_data_loc
parse('set D[0], 2').execute(@ssp)
assert_equal 2, @ssp.data[1]
end
def test_set_w_advanced_expr
@ssp.data[1] = 2
parse('set 2, D[1]+D[0]').execute(@ssp)
assert_equal 3, @ssp.data[2]
end
def test_set_increment_instr
parse('set 0, D[0]+1').execute(@ssp)
assert_equal 2, @ssp.data[0]
end
+ def test_instruction_pointer
+ # run two dummy instructions, manually incrementing the program counter
+ @ssp.pc = 1
+ parse('set 0, 0').execute(@ssp)
+ @ssp.pc = 2
+ parse('set 0, ip').execute(@ssp)
+ assert_equal 2, @ssp.data[0] # check that the parser was able to read the ip correctly
+ end
+
def test_jump_to_data_loc
@ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
def test_comparison_greater_than
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_comparison_greater_than
parse('jumpt 5, D[0] < 0').execute(@ssp)
assert_equal 0, @ssp.pc
parse('jumpt 5, D[0] < 2').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_comparison_greater_than_or_eql
parse('jumpt 5, 0 <= D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_negative_number
parse('set 0, -1').execute(@ssp)
assert_equal -1, @ssp.data[0]
end
end
\ No newline at end of file
diff --git a/simplesem.rb b/simplesem.rb
old mode 100644
new mode 100755
index c767040..894e7e1
--- a/simplesem.rb
+++ b/simplesem.rb
@@ -1,7 +1,8 @@
+#!/usr/bin/env ruby
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/simple_sem_program")
ssp = SimpleSemProgram.new(ARGV[0])
ssp.run
puts "\n" + ssp.data.inspect
\ No newline at end of file
|
robolson/simplesem
|
13827d9c359f51ecb50ecc3ced62f7f96fa93359
|
* More test coverage for treetop grammar * Simplifying the grammar to narrow down possibilities for bugs.
|
diff --git a/arithmetic.treetop b/arithmetic.treetop
index fc6434f..2a77be4 100644
--- a/arithmetic.treetop
+++ b/arithmetic.treetop
@@ -1,121 +1,95 @@
grammar Arithmetic
rule arithmetic_expression
- comparative / additive
+ comparative / additive / multitive
end
rule comparative
- operand_1:additive space operator:comparison_op space operand_2:additive <BinaryOperation>
+ operand_1:expression space operator:comparison_op space operand_2:expression <BinaryOperation>
end
rule comparison_op
- equality_op
- /
- inequality_op
+ '>=' {
+ def apply(a, b)
+ a >= b
+ end
+ }
+ /
+ '<=' {
+ def apply(a, b)
+ a <= b
+ end
+ }
/
'>' {
def apply(a, b)
a > b
end
}
/
'<' {
def apply(a, b)
a < b
end
}
/
- '>=' {
+ '!=' {
def apply(a, b)
- a >= b
+ a != b
end
}
/
- '<=' {
- def apply(a, b)
- a <= b
- end
- }
- end
-
- rule equality_op
'=' {
def apply(a, b)
a == b
end
}
end
- rule inequality_op
- '!=' {
- def apply(a, b)
- a != b
- end
- }
- end
-
rule additive
- operand_1:multitive
- space operator:additive_op space
- operand_2:additive <BinaryOperation>
- /
- multitive
+ operand_1:expression space operator:additive_op space operand_2:expression <BinaryOperation>
end
rule additive_op
'+' {
def apply(a, b)
a + b
end
}
/
'-' {
def apply(a, b)
a - b
end
}
end
rule multitive
- operand_1:primary
- space operator:multitive_op space
- operand_2:multitive <BinaryOperation>
- /
- primary
+ operand_1:expression space operator:multitive_op space operand_2:expression <BinaryOperation>
end
rule multitive_op
'*' {
def apply(a, b)
a * b
end
}
/
'/' {
def apply(a, b)
a / b
end
}
end
-
- rule primary
- number
- /
- '(' space arithmetic_expression space ')' {
- def eval(env={})
- arithmetic_expression.eval(env)
- end
- }
- end
rule number
- ([1-9] [0-9]* / '0') {
+ ('-'? [1-9] [0-9]* / '0') {
def eval(env={})
text_value.to_i
end
}
end
rule space
' '*
end
end
\ No newline at end of file
diff --git a/simple_sem.treetop b/simple_sem.treetop
index 2c1a17c..fa578ea 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,111 +1,95 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
throw "halt!"
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
- 'set' space location:expression comma value:expression {
+ 'set' space location:primary comma value:primary {
def execute(env)
env.data[location.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
end
rule set_stmt_read
'set' space expression comma 'read' {
def execute(env)
print "input: "
env.data[expression.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
'jump' space loc:expression {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:expression comma comparative {
def execute(env)
if comparative.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule expression
data_lookup / number
end
rule primary
+ arithmetic_expression
+ /
data_lookup
/
number
- /
- '(' space arithmetic_expression space ')' {
- def eval(env={})
- arithmetic_expression.eval(env)
- end
- }
end
rule data_lookup
- 'D[' expression ']' {
+ 'D[' primary ']' {
def eval(env)
- env.data[expression.eval(env)]
- end
- }
- end
-
- rule number
- ([1-9] [0-9]* / '0') {
- def eval(env={})
- text_value.to_i
+ env.data[primary.eval(env)]
end
}
end
rule pc
'pc' / 'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
- rule space
- ' '*
- end
-
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index 5599a39..9f56774 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,54 +1,89 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
@ssp.data[0] = 1
end
def test_set_stmt_assign
parse('set 1, D[0]').execute(@ssp)
assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, 1').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
end
+ def test_set_to_data_loc
+ parse('set D[0], 2').execute(@ssp)
+ assert_equal 2, @ssp.data[1]
+ end
+
+ def test_set_w_advanced_expr
+ @ssp.data[1] = 2
+ parse('set 2, D[1]+D[0]').execute(@ssp)
+ assert_equal 3, @ssp.data[2]
+ end
+
+ def test_set_increment_instr
+ parse('set 0, D[0]+1').execute(@ssp)
+ assert_equal 2, @ssp.data[0]
+ end
+
def test_jump_to_data_loc
+ @ssp.data[0] = 2
parse('jump D[0]').execute(@ssp)
- assert_equal 1, @ssp.pc
+ assert_equal 2, @ssp.pc
end
def test_jumpt_stmt_true
@ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
end
def test_jumpt_stmt_false
@ssp.data[0] = 1
parse('jumpt 5, D[0]=2').execute(@ssp)
assert_equal 0, @ssp.pc # pc should not have changed
end
- def test_comparisons
+ def test_comparison_greater_than
parse('jumpt 5, D[0] > 0').execute(@ssp)
assert_equal 5, @ssp.pc
end
+ def test_comparison_greater_than
+ parse('jumpt 5, D[0] < 0').execute(@ssp)
+ assert_equal 0, @ssp.pc
+
+ parse('jumpt 5, D[0] < 2').execute(@ssp)
+ assert_equal 5, @ssp.pc
+ end
+
+ def test_comparison_greater_than_or_eql
+ parse('jumpt 5, 0 <= D[0]').execute(@ssp)
+ assert_equal 5, @ssp.pc
+ end
+
+ def test_negative_number
+ parse('set 0, -1').execute(@ssp)
+ assert_equal -1, @ssp.data[0]
+ end
+
end
\ No newline at end of file
|
robolson/simplesem
|
c151c0dc13aa5ce40428eeeab3202396dd93396c
|
* Added support for comparisons '<', '<=', etc * Take program name from command line while getting put from user with gets
|
diff --git a/arithmetic.treetop b/arithmetic.treetop
index a861fbc..fc6434f 100644
--- a/arithmetic.treetop
+++ b/arithmetic.treetop
@@ -1,95 +1,121 @@
grammar Arithmetic
rule arithmetic_expression
comparative / additive
end
rule comparative
operand_1:additive space operator:comparison_op space operand_2:additive <BinaryOperation>
end
rule comparison_op
- equality_op / inequality_op
+ equality_op
+ /
+ inequality_op
+ /
+ '>' {
+ def apply(a, b)
+ a > b
+ end
+ }
+ /
+ '<' {
+ def apply(a, b)
+ a < b
+ end
+ }
+ /
+ '>=' {
+ def apply(a, b)
+ a >= b
+ end
+ }
+ /
+ '<=' {
+ def apply(a, b)
+ a <= b
+ end
+ }
end
rule equality_op
'=' {
def apply(a, b)
a == b
end
}
end
rule inequality_op
'!=' {
def apply(a, b)
a != b
end
}
end
rule additive
operand_1:multitive
space operator:additive_op space
operand_2:additive <BinaryOperation>
/
multitive
end
rule additive_op
'+' {
def apply(a, b)
a + b
end
}
/
'-' {
def apply(a, b)
a - b
end
}
end
rule multitive
operand_1:primary
space operator:multitive_op space
operand_2:multitive <BinaryOperation>
/
primary
end
rule multitive_op
'*' {
def apply(a, b)
a * b
end
}
/
'/' {
def apply(a, b)
a / b
end
}
end
rule primary
number
/
'(' space arithmetic_expression space ')' {
def eval(env={})
arithmetic_expression.eval(env)
end
}
end
rule number
([1-9] [0-9]* / '0') {
def eval(env={})
text_value.to_i
end
}
end
rule space
' '*
end
end
\ No newline at end of file
diff --git a/whileloop.c1.txt b/programs/whileloop.c1.txt
similarity index 94%
rename from whileloop.c1.txt
rename to programs/whileloop.c1.txt
index 45e84d6..b5e401f 100644
--- a/whileloop.c1.txt
+++ b/programs/whileloop.c1.txt
@@ -1,11 +1,11 @@
set 0, read
jumpt 5, D[0] = 1
jumpt 7, D[0] = 2
jumpt 9, D[0] = 3
halt
set 1, 1
jump 4
set 1, 2
jump 4
set 1, 3
-jump 4
\ No newline at end of file
+jump 4
diff --git a/simple_sem.treetop b/simple_sem.treetop
index e601f42..2c1a17c 100644
--- a/simple_sem.treetop
+++ b/simple_sem.treetop
@@ -1,111 +1,111 @@
grammar SimpleSem
include Arithmetic
rule statement
set_stmt / jump_stmt / jumpt_stmt / halt
end
rule halt
'halt' {
def execute(env={})
throw "halt!"
end
}
end
rule set_stmt
set_stmt_assign / set_stmt_write / set_stmt_read
end
rule set_stmt_assign
'set' space location:expression comma value:expression {
def execute(env)
env.data[location.eval(env)] = value.eval(env)
end
}
end
rule set_stmt_write
'set' space 'write' comma expression {
def execute(env)
puts expression.eval(env)
end
}
end
rule set_stmt_read
'set' space expression comma 'read' {
def execute(env)
print "input: "
- env.data[expression.eval(env)] = gets.strip.to_i
+ env.data[expression.eval(env)] = $stdin.gets.strip.to_i
end
}
end
rule jump_stmt
'jump' space loc:expression {
def execute(env)
env.pc = loc.eval(env)
end
}
end
rule jumpt_stmt
'jumpt' space loc:expression comma comparative {
def execute(env)
if comparative.eval(env)
env.pc = loc.eval(env)
end
end
}
end
rule expression
data_lookup / number
end
rule primary
data_lookup
/
number
/
'(' space arithmetic_expression space ')' {
def eval(env={})
arithmetic_expression.eval(env)
end
}
end
rule data_lookup
'D[' expression ']' {
def eval(env)
env.data[expression.eval(env)]
end
}
end
rule number
([1-9] [0-9]* / '0') {
def eval(env={})
text_value.to_i
end
}
end
rule pc
'pc' / 'ip' {
def eval(env)
env.pc
end
}
end
rule comma
space ',' space
end
rule space
' '*
end
end
\ No newline at end of file
diff --git a/simple_sem_program.rb b/simple_sem_program.rb
index 1f4c3ea..8d6e580 100644
--- a/simple_sem_program.rb
+++ b/simple_sem_program.rb
@@ -1,48 +1,44 @@
require 'rubygems'
require 'treetop'
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemProgram
attr_reader :code
attr_accessor :data, :pc
+ # Create a SimpleSemProgram instance
+ # Params:
+ # (String)filepath: path to SimpleSem source file.
+ # Optional because it's useful to use in tests without needing to load a file
def initialize filepath=nil
@code = Array.new
if filepath
IO.foreach(filepath) do |line|
@code << line.split("//", 2)[0].strip # seperate the comment from the code
end
end
@data = Array.new
@pc = 0
end
# alias :ip :pc
def run
@parser = SimpleSemParser.new
@pc = 0
loop do
@pc += 1
instruction = @code[@pc-1]
- # puts "'#{instruction}'"
begin
@parser.parse(instruction).execute(self)
rescue
puts "program halted"
break
end
end
end
-
- def inspect_data
- puts "DATA:"
- @data.each_with_index do |item, index|
- puts "#{index}: #{item}"
- end
- end
end
\ No newline at end of file
diff --git a/simple_sem_test.rb b/simple_sem_test.rb
index de7cc34..5599a39 100644
--- a/simple_sem_test.rb
+++ b/simple_sem_test.rb
@@ -1,46 +1,54 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/test_helper")
require File.expand_path("#{dir}/simple_sem_program")
require File.expand_path("#{dir}/arithmetic_node_classes")
Treetop.load File.expand_path("#{dir}/arithmetic")
Treetop.load File.expand_path("#{dir}/simple_sem")
class SimpleSemParserTest < Test::Unit::TestCase
include ParserTestHelper
def setup
@parser = SimpleSemParser.new
@ssp = SimpleSemProgram.new
+ @ssp.data[0] = 1
end
def test_set_stmt_assign
- @ssp.data[0] = 2
parse('set 1, D[0]').execute(@ssp)
- assert_equal [2, 2], @ssp.data
+ assert_equal [1, 1], @ssp.data
end
def test_set_stmt_write
assert_nil parse('set write, 1').execute(@ssp)
end
def test_jump_stmt
parse('jump 5').execute(@ssp)
assert_equal 5, @ssp.pc
-
- @ssp.data[0] = 1
+ end
+
+ def test_jump_to_data_loc
parse('jump D[0]').execute(@ssp)
assert_equal 1, @ssp.pc
end
- def test_jumpt_stmt
- @ssp.data[0] = 2
+ def test_jumpt_stmt_true
+ @ssp.data[0] = 1
parse('jumpt 5, D[0]=D[0]').execute(@ssp)
assert_equal 5, @ssp.pc
+ end
- @ssp.data[1] = 3
- parse('jumpt 6, D[0]=D[1]').execute(@ssp)
- assert_equal 5, @ssp.pc # pc should have changed
+ def test_jumpt_stmt_false
+ @ssp.data[0] = 1
+ parse('jumpt 5, D[0]=2').execute(@ssp)
+ assert_equal 0, @ssp.pc # pc should not have changed
+ end
+
+ def test_comparisons
+ parse('jumpt 5, D[0] > 0').execute(@ssp)
+ assert_equal 5, @ssp.pc
end
end
\ No newline at end of file
diff --git a/simplesem.rb b/simplesem.rb
index 6cd7d4d..c767040 100644
--- a/simplesem.rb
+++ b/simplesem.rb
@@ -1,7 +1,7 @@
dir = File.dirname(__FILE__)
require File.expand_path("#{dir}/simple_sem_program")
-# SimpleSemProgram.new(ARGV[0])
-ssp = SimpleSemProgram.new("whileloop.c1.txt")
+ssp = SimpleSemProgram.new(ARGV[0])
ssp.run
-ssp.inspect_data
\ No newline at end of file
+
+puts "\n" + ssp.data.inspect
\ No newline at end of file
diff --git a/simplesem.tmproj b/simplesem.tmproj
deleted file mode 100644
index a897daa..0000000
--- a/simplesem.tmproj
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>currentDocument</key>
- <string>simplesem.rb</string>
- <key>documents</key>
- <array>
- <dict>
- <key>expanded</key>
- <true/>
- <key>name</key>
- <string>simplesem</string>
- <key>regexFolderFilter</key>
- <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string>
- <key>sourceDirectory</key>
- <string></string>
- </dict>
- </array>
- <key>fileHierarchyDrawerWidth</key>
- <integer>170</integer>
- <key>metaData</key>
- <dict>
- <key>simplesem.rb</key>
- <dict>
- <key>caret</key>
- <dict>
- <key>column</key>
- <integer>31</integer>
- <key>line</key>
- <integer>17</integer>
- </dict>
- <key>firstVisibleColumn</key>
- <integer>0</integer>
- <key>firstVisibleLine</key>
- <integer>0</integer>
- </dict>
- <key>sstest.c1.txt</key>
- <dict>
- <key>caret</key>
- <dict>
- <key>column</key>
- <integer>8</integer>
- <key>line</key>
- <integer>0</integer>
- </dict>
- <key>firstVisibleColumn</key>
- <integer>0</integer>
- <key>firstVisibleLine</key>
- <integer>0</integer>
- </dict>
- </dict>
- <key>openDocuments</key>
- <array>
- <string>simplesem.rb</string>
- <string>sstest.c1.txt</string>
- </array>
- <key>showFileHierarchyDrawer</key>
- <true/>
- <key>windowFrame</key>
- <string>{{46, 29}, {963, 742}}</string>
-</dict>
-</plist>
|
lsegal/Wiidi
|
36cbc99497570f2b655aa642cf79667608cd0c09
|
Add Readme
|
diff --git a/README.txt b/README.txt
new file mode 100644
index 0000000..499bb0e
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,8 @@
+Wiidi
+=====
+Wiimote MIDI interface application for OSX
+-------------------------------------------
+
+Written by Loren Segal in 2009.
+
+MIT License
|
lsegal/Wiidi
|
da89b0df19fdaa84628c85bef6b90658140ac16e
|
This marks the point in time before Wiimote will have true unit-vector values
|
diff --git a/AppController.h b/AppController.h
new file mode 100644
index 0000000..728bb4a
--- /dev/null
+++ b/AppController.h
@@ -0,0 +1,17 @@
+/* AppController */
+
+#import <Cocoa/Cocoa.h>
+#import "Wiimote.h"
+#import "Miidi.h"
+#import "WiiGestures.h"
+
+@interface AppController : NSObject <WiimoteDelegate>
+{
+ IBOutlet NSButton *nunchuckButton;
+ IBOutlet NSButton *wiimoteButton;
+
+ Wiimote *wiimote;
+ Miidi *miidi;
+ WiiGestures *gestures;
+}
+@end
diff --git a/AppController.m b/AppController.m
new file mode 100644
index 0000000..ca7c4f9
--- /dev/null
+++ b/AppController.m
@@ -0,0 +1,43 @@
+#import "AppController.h"
+
+@implementation AppController
+
+- (void)awakeFromNib
+{
+// miidi = [[Miidi alloc] init];
+// [miidi initializeMIDI];
+
+
+ gestures = [[WiiGestures alloc] init];
+
+ wiimote = [[Wiimote alloc] initWithDelegate:self];
+
+ // Start to search for the device and keep looking every 5 seconds
+ [wiimote connectDevice:nil];
+ [NSTimer scheduledTimerWithTimeInterval:5
+ target:wiimote
+ selector:@selector(connectDevice:)
+ userInfo:nil
+ repeats:YES];
+}
+
+- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
+{
+#ifdef DEBUG
+ NSLog(@"Application is terminating! Clean up");
+#endif
+ [wiimote stopDevice];
+ return NSTerminateNow;
+}
+
+- (void) wiimoteData:(WiimoteData *)data lastData:(WiimoteData *)lastData
+{
+ [gestures wiimoteData:data lastData:lastData];
+}
+
+- (void) nunchuckData:(NunchuckData *)data lastData:(NunchuckData *)lastData
+{
+ [gestures nunchuckData:data lastData:lastData];
+}
+
+@end
diff --git a/English.lproj/InfoPlist.strings b/English.lproj/InfoPlist.strings
new file mode 100644
index 0000000..b27f2bf
Binary files /dev/null and b/English.lproj/InfoPlist.strings differ
diff --git a/English.lproj/MainMenu.nib/classes.nib b/English.lproj/MainMenu.nib/classes.nib
new file mode 100644
index 0000000..eaff67f
--- /dev/null
+++ b/English.lproj/MainMenu.nib/classes.nib
@@ -0,0 +1,12 @@
+{
+ IBClasses = (
+ {
+ CLASS = AppController;
+ LANGUAGE = ObjC;
+ OUTLETS = {nunchuckButton = NSButton; wiimoteButton = NSButton; };
+ SUPERCLASS = NSObject;
+ },
+ {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
+ );
+ IBVersion = 1;
+}
\ No newline at end of file
diff --git a/English.lproj/MainMenu.nib/info.nib b/English.lproj/MainMenu.nib/info.nib
new file mode 100644
index 0000000..340dad7
--- /dev/null
+++ b/English.lproj/MainMenu.nib/info.nib
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IBDocumentLocation</key>
+ <string>497 155 356 240 0 0 1440 878 </string>
+ <key>IBEditorPositions</key>
+ <dict>
+ <key>29</key>
+ <string>507 343 338 44 0 0 1440 878 </string>
+ </dict>
+ <key>IBFramework Version</key>
+ <string>443.0</string>
+ <key>IBOpenObjects</key>
+ <array>
+ <integer>29</integer>
+ <integer>21</integer>
+ </array>
+ <key>IBSystem Version</key>
+ <string>8L2127</string>
+</dict>
+</plist>
diff --git a/English.lproj/MainMenu.nib/keyedobjects.nib b/English.lproj/MainMenu.nib/keyedobjects.nib
new file mode 100644
index 0000000..9be2d23
Binary files /dev/null and b/English.lproj/MainMenu.nib/keyedobjects.nib differ
diff --git a/English.lproj/MainMenu~.nib/classes.nib b/English.lproj/MainMenu~.nib/classes.nib
new file mode 100644
index 0000000..eaff67f
--- /dev/null
+++ b/English.lproj/MainMenu~.nib/classes.nib
@@ -0,0 +1,12 @@
+{
+ IBClasses = (
+ {
+ CLASS = AppController;
+ LANGUAGE = ObjC;
+ OUTLETS = {nunchuckButton = NSButton; wiimoteButton = NSButton; };
+ SUPERCLASS = NSObject;
+ },
+ {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
+ );
+ IBVersion = 1;
+}
\ No newline at end of file
diff --git a/English.lproj/MainMenu~.nib/info.nib b/English.lproj/MainMenu~.nib/info.nib
new file mode 100644
index 0000000..340dad7
--- /dev/null
+++ b/English.lproj/MainMenu~.nib/info.nib
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IBDocumentLocation</key>
+ <string>497 155 356 240 0 0 1440 878 </string>
+ <key>IBEditorPositions</key>
+ <dict>
+ <key>29</key>
+ <string>507 343 338 44 0 0 1440 878 </string>
+ </dict>
+ <key>IBFramework Version</key>
+ <string>443.0</string>
+ <key>IBOpenObjects</key>
+ <array>
+ <integer>29</integer>
+ <integer>21</integer>
+ </array>
+ <key>IBSystem Version</key>
+ <string>8L2127</string>
+</dict>
+</plist>
diff --git a/English.lproj/MainMenu~.nib/keyedobjects.nib b/English.lproj/MainMenu~.nib/keyedobjects.nib
new file mode 100644
index 0000000..05cc8a3
Binary files /dev/null and b/English.lproj/MainMenu~.nib/keyedobjects.nib differ
diff --git a/Info.plist b/Info.plist
new file mode 100644
index 0000000..7966dfc
--- /dev/null
+++ b/Info.plist
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>${EXECUTABLE_NAME}</string>
+ <key>CFBundleIconFile</key>
+ <string></string>
+ <key>CFBundleIdentifier</key>
+ <string>com.yourcompany.Wiidi</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>${PRODUCT_NAME}</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>1.0</string>
+ <key>NSMainNibFile</key>
+ <string>MainMenu</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+</dict>
+</plist>
diff --git a/Japanese.lproj/InfoPlist.strings b/Japanese.lproj/InfoPlist.strings
new file mode 100644
index 0000000..8a78ff4
Binary files /dev/null and b/Japanese.lproj/InfoPlist.strings differ
diff --git a/Japanese.lproj/MainMenu.nib/classes.nib b/Japanese.lproj/MainMenu.nib/classes.nib
new file mode 100644
index 0000000..b9b4b09
--- /dev/null
+++ b/Japanese.lproj/MainMenu.nib/classes.nib
@@ -0,0 +1,4 @@
+{
+ IBClasses = ({CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; });
+ IBVersion = 1;
+}
\ No newline at end of file
diff --git a/Japanese.lproj/MainMenu.nib/info.nib b/Japanese.lproj/MainMenu.nib/info.nib
new file mode 100644
index 0000000..4c74210
--- /dev/null
+++ b/Japanese.lproj/MainMenu.nib/info.nib
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IBDocumentLocation</key>
+ <string>94 103 356 240 0 0 1280 1002 </string>
+ <key>IBEditorPositions</key>
+ <dict>
+ <key>29</key>
+ <string>93 343 318 44 0 0 1280 1002 </string>
+ </dict>
+ <key>IBFramework Version</key>
+ <string>403.0</string>
+ <key>IBSystem Version</key>
+ <string>8A278</string>
+</dict>
+</plist>
diff --git a/Japanese.lproj/MainMenu.nib/keyedobjects.nib b/Japanese.lproj/MainMenu.nib/keyedobjects.nib
new file mode 100644
index 0000000..ee1187e
Binary files /dev/null and b/Japanese.lproj/MainMenu.nib/keyedobjects.nib differ
diff --git a/Miidi.h b/Miidi.h
new file mode 100644
index 0000000..b27469f
--- /dev/null
+++ b/Miidi.h
@@ -0,0 +1,40 @@
+//
+// Miidi.h
+// Wiidi
+//
+// Created by Jinx on 23/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import <Cocoa/Cocoa.h>
+#import <CoreMIDI/CoreMIDI.h>
+#import <CoreMIDIServer/CoreMIDIServer.h>
+#import "Wiimote.h"
+
+#define kMiidiInterfaceName CFSTR("Miidi Wii Remote Interface")
+#define kMiidiPortName CFSTR("Miidi_outPort")
+
+typedef enum {
+ kMIDIControlChangeEvent = 0xB0,
+ kMIDIProgramChangeEvent = 0xC0,
+ kMIDIBankMSBControlEvent = 0x00,
+ kMIDIBankLSBControlEvent = 0x20,
+ kMIDINoteOnEvent = 0x90
+} MIDIEvent;
+
+@interface Miidi : NSObject <WiimoteDelegate> {
+ MIDIClientRef client;
+ MIDIEndpointRef endpoint;
+ MIDIPortRef port;
+
+ Byte __listHolder[1024];
+ MIDIPacketList *list;
+ MIDIPacket *packet;
+}
+- (void) initializeMIDI;
+- (void) initializePacketList;
+- (UInt8) MIDINoteForWiimoteButton:(WiimoteButtonType)button;
+- (UInt8) MIDINoteForNunchuckButton:(NunchuckButtonType)button;
+- (void) MIDIEventAdd:(MIDIEvent)type note:(UInt8)note velocity:(UInt8)velocity;
+- (void) MIDIFlush;
+@end
diff --git a/Miidi.m b/Miidi.m
new file mode 100644
index 0000000..6673251
--- /dev/null
+++ b/Miidi.m
@@ -0,0 +1,151 @@
+//
+// Miidi.m
+// Wiidi
+//
+// Created by Jinx on 23/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import "Miidi.h"
+
+
+@implementation Miidi
+
+- (void) initializeMIDI
+{
+ MIDIClientCreate(kMiidiInterfaceName, nil, nil, &client);
+ MIDISourceCreate(client, kMiidiInterfaceName, &endpoint);
+ MIDIOutputPortCreate(client, kMiidiPortName, &port);
+
+ [self initializePacketList];
+}
+
+- (void) initializePacketList
+{
+ list = (MIDIPacketList *)__listHolder;
+ list->numPackets = 0;
+ packet = MIDIPacketListInit(list);
+}
+
+- (void) wiimoteData:(WiimoteData *)data lastData:(WiimoteData *)lastData
+{
+ int i;
+
+ // Button data (there are currently 11 buttons)
+ for (i = 0; i < 11; i++)
+ {
+ UInt8 button = WiimoteButtons[i];
+ UInt8 note = [self MIDINoteForWiimoteButton:button];
+ if (button & data->buttonData && !(button & lastData->buttonData))
+ {
+ [self MIDIEventAdd:(button == kWiimoteBButton ? kMIDIControlChangeEvent : kMIDINoteOnEvent) note:note velocity:127];
+ }
+ else if (button & lastData->buttonData && !(button & data->buttonData))
+ {
+ [self MIDIEventAdd:(button == kWiimoteBButton ? kMIDIControlChangeEvent : kMIDINoteOnEvent) note:note velocity:0];
+ }
+ }
+
+ // Wiimote X-Y axis MIDI controlling
+ // Only send it if A and B is pushed??
+ if (data->buttonData & kWiimoteBButton && data->buttonData & kWiimoteAButton)
+ {
+ for (i = 0; i < 2; i++)
+ {
+ double *f = data->force;
+ double Fc = f[Z] >= 0 ? f[X] : nearbyint(f[X]);
+ UInt8 velocity = (UInt8)(Fc * 63) + 64;
+ [self MIDIEventAdd:kMIDIControlChangeEvent note:i+1 velocity:velocity];
+ }
+ }
+
+ if (data->magnitude > 2.2 && data->magnitude < lastData->magnitude && lastData->force[Z] > 1 && lastData->force[Y] > -0.5)
+ {
+ NSLog(@"Snare HIT!");
+ [self MIDIEventAdd:kMIDINoteOnEvent note:62 velocity:(UInt8)((data->magnitude - 2.2) * 127 / 3)];
+ }
+
+ [self MIDIFlush];
+}
+
+- (void) nunchuckData:(NunchuckData *)data lastData:(NunchuckData *)lastData
+{
+ // Button data (there are currently 11 buttons)
+ int i;
+ for (i = 0; i < 2; i++)
+ {
+ UInt8 button = NunchuckButtons[i];
+ UInt8 note = [self MIDINoteForNunchuckButton:button];
+ if (button & data->buttonData && !(button & lastData->buttonData))
+ {
+ [self MIDIEventAdd:kMIDINoteOnEvent note:note velocity:127];
+ }
+ else if (button & lastData->buttonData && !(button & data->buttonData))
+ {
+ [self MIDIEventAdd:kMIDINoteOnEvent note:note velocity:0];
+ }
+ }
+
+ // Joypad
+ for (i = X; i < Z; i++)
+ {
+ if (data->joypad[i] != lastData->joypad[i])
+ {
+ UInt8 velocity = data->joypad[i] * 64 + 63;
+ [self MIDIEventAdd:kMIDIControlChangeEvent note:(i+100) velocity:velocity];
+ }
+ }
+
+ if (data->magnitude >= 1 && data->magnitude < lastData->magnitude && lastData->force[Z] > 0.9)
+ {
+ NSLog(@"NUNCHUCK Snare HIT!");
+ [self MIDIEventAdd:kMIDINoteOnEvent note:71 velocity:(UInt8)(abs(data->magnitude - 0.5) * 127)];
+ }
+ [self MIDIFlush];
+}
+
+- (void) MIDIEventAdd:(MIDIEvent)type note:(UInt8)note velocity:(UInt8)velocity
+{
+ UInt64 time = 0;
+ if (velocity > 127) velocity = 127;
+ Byte data[] = { type, note, velocity };
+ list->numPackets++;
+ packet = MIDIPacketListAdd(list, 1024, packet, time, 3, data);
+}
+
+- (void) MIDIFlush
+{
+ MIDIReceived(endpoint, list);
+ [self initializePacketList];
+}
+
+- (UInt8) MIDINoteForWiimoteButton:(WiimoteButtonType)button
+{
+ switch (button)
+ {
+ case kWiimoteAButton: return 74;
+ case kWiimoteBButton: return 73;
+ case kWiimoteLeftButton: return 76;
+ case kWiimoteRightButton: return 77;
+ case kWiimoteUpButton: return 78;
+ case kWiimoteDownButton: return 79;
+ case kWiimoteTwoButton: return 80;
+ case kWiimoteOneButton: return 81;
+ case kWiimoteMinusButton: return 82;
+ case kWiimoteHomeButton: return 83;
+ case kWiimotePlusButton: return 84;
+ }
+ return 0;
+}
+
+- (UInt8) MIDINoteForNunchuckButton:(NunchuckButtonType)button
+{
+ switch (button)
+ {
+ case kNunchuckZButton: return 72;
+ case kNunchuckCButton: return 60;
+ }
+ return 0;
+}
+
+@end
diff --git a/WiiGestures.h b/WiiGestures.h
new file mode 100644
index 0000000..46446de
--- /dev/null
+++ b/WiiGestures.h
@@ -0,0 +1,19 @@
+//
+// WiiGestures.h
+// Wiidi
+//
+// Created by Jinx on 25/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import <Cocoa/Cocoa.h>
+#import "Wiimote.h"
+
+#define SIMILAR(a,b) ((a/b) >= 0.8 || (a/b) <= 1.25)
+
+@interface WiiGestures : NSObject <WiimoteDelegate> {
+ NSMutableArray *record;
+ NSMutableArray *playback;
+}
+
+@end
diff --git a/WiiGestures.m b/WiiGestures.m
new file mode 100644
index 0000000..5687cfb
--- /dev/null
+++ b/WiiGestures.m
@@ -0,0 +1,144 @@
+//
+// WiiGestures.m
+// Wiidi
+//
+// Created by Jinx on 25/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import "WiiGestures.h"
+
+
+@implementation WiiGestures
+
+- (id) init
+{
+ if ([super init])
+ {
+ playback = nil;
+ record = nil;
+ }
+ return self;
+}
+
+- (bool) playbackMatchesRecording
+{
+ // First check that the sizes are close, define "close" as 80% similarity
+// double sizeCheck = (double)[playback count] / (double)[record count];
+// if ([playback count] < 10 || sizeCheck < 0.8 || sizeCheck > 1.2) return NO;
+
+ // Check that 80% or more of the component vectors match in direction
+ int rCount = [record count], pCount = [playback count], diff = rCount - pCount;
+ int numMatch = 0, i = 0, total = (diff < 0 ? rCount : pCount);
+ float p[3] = {0}, r[3] = {0};
+
+ if (total == 0) return NO;
+
+
+ for (i = 0; i < total; i++)
+ {
+ int pIndex = i, rIndex = i;
+ if (total == rCount) pIndex = (int)(((float)i/(float)total) * pCount);
+ else rIndex = (int)(((float)i/(float)total) * rCount);
+
+ NSArray *pArr = [playback objectAtIndex:pIndex];
+ NSArray *rArr = [record objectAtIndex:rIndex];
+ float p[] = { p[X] + [[pArr objectAtIndex:X] floatValue],
+ p[Y] + [[pArr objectAtIndex:Y] floatValue],
+ p[Z] + [[pArr objectAtIndex:Z] floatValue] };
+ float r[] = { r[X] + [[rArr objectAtIndex:X] floatValue],
+ r[Y] + [[rArr objectAtIndex:Y] floatValue],
+ r[Y] + [[rArr objectAtIndex:Z] floatValue] };
+ float vp[] = { lp[X] - p[X], lp[Y] - p[Y], lp[Z] - p[Z] };
+ float vr[] = { lr[X] - r[X], lr[Y] - r[Y], lr[Z] - r[Z] };
+
+ float pp[] = { lvp[X] - vp[X], lvp[Y] - vp[Y], lvp[Z] - vp[Z] };
+ float pr[] = { lvr[X] - vr[X], lvr[Y] - vr[Y], lvr[Z] - vr[Z] };
+
+ if (i > 1)
+ {
+
+ if (SIMILAR(pr[X], pp[X]) && SIMILAR(pr[Y], pp[Y]) && SIMILAR(pr[Z], pp[Z]))
+ {
+ NSLog(@"%2.2f <=> %2.2f \t %2.2f <=> %2.2f \t %2.2f <=> %2.2f (MATCH)", pp[X], pr[X], pp[Y], pr[Y], pp[Z], pr[Z]);
+ numMatch++;
+ //NSLog(@"Match number %d (%2.2f <=> %2.2f)", numMatch, pRatioXY, rRatioXY);
+ }
+ else
+ NSLog(@"%2.2f <=> %2.2f \t %2.2f <=> %2.2f \t %2.2f <=> %2.2f", pp[X], pr[X], pp[Y], pr[Y], pp[Z], pr[Z]);
+ }
+
+ // old values
+ memcpy(lp, p, sizeof(float) * 3);
+ memcpy(lr, r, sizeof(float) * 3);
+ memcpy(lvp, vp, sizeof(float) * 3);
+ memcpy(lvr, vr, sizeof(float) * 3);
+ }
+
+ if (numMatch / total >= 0.8) return YES;
+
+ return NO;
+}
+
+- (void) wiimoteData:(WiimoteData *)data lastData:(WiimoteData *)lastData
+{
+ bool aButton = data->buttonData & kWiimoteAButton, lastAButton = lastData->buttonData & kWiimoteAButton;
+ bool bButton = data->buttonData & kWiimoteBButton, lastBButton = lastData->buttonData & kWiimoteBButton;
+
+ if (aButton && bButton) // RECORD
+ {
+ if (!lastAButton || !lastBButton) // START RECORD
+ {
+ NSLog(@"Start record");
+ [record release];
+ record = [[NSMutableArray alloc] init];
+ }
+
+ NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:data->force[X]],
+ [NSNumber numberWithFloat:data->force[Y]],
+ [NSNumber numberWithFloat:data->force[Z]], nil];
+
+ [record addObject:arr];
+ return;
+ }
+ else if (lastAButton && lastBButton) // STOP RECORD
+ {
+ NSLog(@"Stop record");
+ return;
+ }
+
+ if (bButton) // PLAYBACK
+ {
+ if (!lastBButton) // START PLAYBACK
+ {
+ NSLog(@"Start playback");
+ [playback release];
+ playback = [[NSMutableArray alloc] init];
+ }
+ NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:data->force[X]],
+ [NSNumber numberWithFloat:data->force[Y]],
+ [NSNumber numberWithFloat:data->force[Z]], nil];
+
+ [playback addObject:arr];
+ return;
+ }
+ else if (lastBButton) // END PLAYBACK
+ {
+ NSLog(@"Stop playback");
+ if ([self playbackMatchesRecording])
+ {
+ NSLog(@"MATCH!");
+ }
+ else
+ {
+ NSLog(@"No match");
+ }
+ }
+}
+
+- (void) nunchuckData:(NunchuckData *)data lastData:(NunchuckData *)lastData
+{
+}
+
+
+@end
diff --git a/Wiidi.xcodeproj/jinx.mode1 b/Wiidi.xcodeproj/jinx.mode1
new file mode 100644
index 0000000..9891273
--- /dev/null
+++ b/Wiidi.xcodeproj/jinx.mode1
@@ -0,0 +1,1382 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>ActivePerspectiveName</key>
+ <string>Project</string>
+ <key>AllowedModules</key>
+ <array>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXSmartGroupTreeModule</string>
+ <key>Name</key>
+ <string>Groups and Files Outline View</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Name</key>
+ <string>Editor</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>XCTaskListModule</string>
+ <key>Name</key>
+ <string>Task List</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>XCDetailModule</string>
+ <key>Name</key>
+ <string>File and Smart Group Detail Viewer</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>1</string>
+ <key>Module</key>
+ <string>PBXBuildResultsModule</string>
+ <key>Name</key>
+ <string>Detailed Build Results Viewer</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>1</string>
+ <key>Module</key>
+ <string>PBXProjectFindModule</string>
+ <key>Name</key>
+ <string>Project Batch Find Tool</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXRunSessionModule</string>
+ <key>Name</key>
+ <string>Run Log</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXBookmarksModule</string>
+ <key>Name</key>
+ <string>Bookmarks Tool</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXClassBrowserModule</string>
+ <key>Name</key>
+ <string>Class Browser</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXCVSModule</string>
+ <key>Name</key>
+ <string>Source Code Control Tool</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXDebugBreakpointsModule</string>
+ <key>Name</key>
+ <string>Debug Breakpoints Tool</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>XCDockableInspector</string>
+ <key>Name</key>
+ <string>Inspector</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>n</string>
+ <key>Module</key>
+ <string>PBXOpenQuicklyModule</string>
+ <key>Name</key>
+ <string>Open Quickly Tool</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>1</string>
+ <key>Module</key>
+ <string>PBXDebugSessionModule</string>
+ <key>Name</key>
+ <string>Debugger</string>
+ </dict>
+ <dict>
+ <key>BundleLoadPath</key>
+ <string></string>
+ <key>MaxInstances</key>
+ <string>1</string>
+ <key>Module</key>
+ <string>PBXDebugCLIModule</string>
+ <key>Name</key>
+ <string>Debug Console</string>
+ </dict>
+ </array>
+ <key>Description</key>
+ <string>DefaultDescriptionKey</string>
+ <key>DockingSystemVisible</key>
+ <false/>
+ <key>Extension</key>
+ <string>mode1</string>
+ <key>FavBarConfig</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>B76A0A430B3C60C300C013AB</string>
+ <key>XCBarModuleItemNames</key>
+ <dict/>
+ <key>XCBarModuleItems</key>
+ <array/>
+ </dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>com.apple.perspectives.project.mode1</string>
+ <key>MajorVersion</key>
+ <integer>31</integer>
+ <key>MinorVersion</key>
+ <integer>1</integer>
+ <key>Name</key>
+ <string>Default</string>
+ <key>Notifications</key>
+ <array/>
+ <key>OpenEditors</key>
+ <array/>
+ <key>PerspectiveWidths</key>
+ <array>
+ <integer>-1</integer>
+ <integer>-1</integer>
+ </array>
+ <key>Perspectives</key>
+ <array>
+ <dict>
+ <key>ChosenToolbarItems</key>
+ <array>
+ <string>active-target-popup</string>
+ <string>action</string>
+ <string>NSToolbarFlexibleSpaceItem</string>
+ <string>buildOrClean</string>
+ <string>build-and-runOrDebug</string>
+ <string>com.apple.ide.PBXToolbarStopButton</string>
+ <string>get-info</string>
+ <string>toggle-editor</string>
+ <string>NSToolbarFlexibleSpaceItem</string>
+ <string>com.apple.pbx.toolbar.searchfield</string>
+ </array>
+ <key>ControllerClassBaseName</key>
+ <string></string>
+ <key>IconName</key>
+ <string>WindowOfProjectWithEditor</string>
+ <key>Identifier</key>
+ <string>perspective.project</string>
+ <key>IsVertical</key>
+ <false/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>BecomeActive</key>
+ <true/>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXBottomSmartGroupGIDs</key>
+ <array>
+ <string>1C37FBAC04509CD000000102</string>
+ <string>1C37FAAC04509CD000000102</string>
+ <string>1C08E77C0454961000C914BD</string>
+ <string>1C37FABC05509CD000000102</string>
+ <string>1C37FABC05539CD112110102</string>
+ <string>E2644B35053B69B200211256</string>
+ <string>1C37FABC04509CD000100104</string>
+ <string>1CC0EA4004350EF90044410B</string>
+ <string>1CC0EA4004350EF90041110B</string>
+ </array>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CE0B1FE06471DED0097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Files</string>
+ <key>PBXProjectStructureProvided</key>
+ <string>yes</string>
+ <key>PBXSmartGroupTreeModuleColumnData</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleColumnWidthsKey</key>
+ <array>
+ <real>225</real>
+ </array>
+ <key>PBXSmartGroupTreeModuleColumnsKey_v4</key>
+ <array>
+ <string>MainColumn</string>
+ </array>
+ </dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key>
+ <array>
+ <string>29B97314FDCFA39411CA2CEA</string>
+ <string>080E96DDFE201D6D7F000001</string>
+ <string>B72023F80B4178580036D182</string>
+ <string>B72023F90B4178600036D182</string>
+ <string>B72023F70B4178360036D182</string>
+ <string>29B97315FDCFA39411CA2CEA</string>
+ <string>29B97317FDCFA39411CA2CEA</string>
+ <string>19C28FACFE9D520D11CA2CBB</string>
+ <string>1C37FABC05509CD000000102</string>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key>
+ <array>
+ <array>
+ <integer>0</integer>
+ </array>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key>
+ <string>{{0, 0}, {225, 719}}</string>
+ </dict>
+ <key>PBXTopSmartGroupGIDs</key>
+ <array/>
+ <key>XCIncludePerspectivesSwitch</key>
+ <true/>
+ <key>XCSharingToken</key>
+ <string>com.apple.Xcode.GFSharingToken</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {242, 737}}</string>
+ <key>GroupTreeTableConfiguration</key>
+ <array>
+ <string>MainColumn</string>
+ <real>225</real>
+ </array>
+ <key>RubberWindowFrame</key>
+ <string>0 100 1440 778 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXSmartGroupTreeModule</string>
+ <key>Proportion</key>
+ <string>242pt</string>
+ </dict>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CE0B20306471E060097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>WiiGestures.m</string>
+ <key>PBXSplitModuleInNavigatorKey</key>
+ <dict>
+ <key>Split0</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CE0B20406471E060097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>WiiGestures.m</string>
+ <key>_historyCapacity</key>
+ <integer>0</integer>
+ <key>bookmark</key>
+ <string>B7F76CE30B41FC5D002CF8BE</string>
+ <key>history</key>
+ <array>
+ <string>B7436DF60B3C88EF00F36279</string>
+ <string>B7436DFA0B3C88EF00F36279</string>
+ <string>B7436DFC0B3C88EF00F36279</string>
+ <string>B7436DFE0B3C88EF00F36279</string>
+ <string>B7436E000B3C88EF00F36279</string>
+ <string>B7436E020B3C88EF00F36279</string>
+ <string>B7250A220B3D3FE200555F92</string>
+ <string>B7250C9D0B3DC76200555F92</string>
+ <string>B7250E040B3DEDAA00555F92</string>
+ <string>B7250F060B3E675100555F92</string>
+ <string>B753225C0B410850005F3DE8</string>
+ <string>B753225D0B410850005F3DE8</string>
+ <string>B72024C30B41DC730036D182</string>
+ <string>B72024D80B41DF540036D182</string>
+ <string>B72024E80B41DFD80036D182</string>
+ <string>B72024FA0B41E0780036D182</string>
+ <string>B72025010B41E12D0036D182</string>
+ <string>B773E3850B41FA1600F7B574</string>
+ </array>
+ <key>prevStack</key>
+ <array>
+ <string>B7436D9F0B3C7E9B00F36279</string>
+ <string>B7436DA00B3C7E9B00F36279</string>
+ <string>B7436E070B3C88EF00F36279</string>
+ <string>B7436E080B3C88EF00F36279</string>
+ <string>B7436E0A0B3C88EF00F36279</string>
+ <string>B7436E0C0B3C88EF00F36279</string>
+ <string>B7436E0E0B3C88EF00F36279</string>
+ <string>B7436E100B3C88EF00F36279</string>
+ <string>B7436E140B3C88EF00F36279</string>
+ <string>B7436E170B3C88EF00F36279</string>
+ <string>B7436E250B3C88EF00F36279</string>
+ <string>B7250A250B3D3FE200555F92</string>
+ <string>B7250AF20B3D592600555F92</string>
+ <string>B7250AF30B3D592600555F92</string>
+ <string>B7250C670B3DBF7600555F92</string>
+ <string>B7250DE00B3DEABA00555F92</string>
+ <string>B75322690B410850005F3DE8</string>
+ <string>B753226C0B410850005F3DE8</string>
+ </array>
+ </dict>
+ <key>SplitCount</key>
+ <string>1</string>
+ </dict>
+ <key>StatusBarVisibility</key>
+ <true/>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {1193, 512}}</string>
+ <key>RubberWindowFrame</key>
+ <string>0 100 1440 778 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Proportion</key>
+ <string>512pt</string>
+ </dict>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CE0B20506471E060097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Detail</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 517}, {1193, 220}}</string>
+ <key>RubberWindowFrame</key>
+ <string>0 100 1440 778 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>XCDetailModule</string>
+ <key>Proportion</key>
+ <string>220pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>1193pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Project</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>XCModuleDock</string>
+ <string>PBXSmartGroupTreeModule</string>
+ <string>XCModuleDock</string>
+ <string>PBXNavigatorGroup</string>
+ <string>XCDetailModule</string>
+ </array>
+ <key>TableOfContents</key>
+ <array>
+ <string>B7F76CE10B41FC5D002CF8BE</string>
+ <string>1CE0B1FE06471DED0097A5F4</string>
+ <string>B7F76CE20B41FC5D002CF8BE</string>
+ <string>1CE0B20306471E060097A5F4</string>
+ <string>1CE0B20506471E060097A5F4</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.default</string>
+ </dict>
+ <dict>
+ <key>ControllerClassBaseName</key>
+ <string></string>
+ <key>IconName</key>
+ <string>WindowOfProject</string>
+ <key>Identifier</key>
+ <string>perspective.morph</string>
+ <key>IsVertical</key>
+ <integer>0</integer>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>BecomeActive</key>
+ <integer>1</integer>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXBottomSmartGroupGIDs</key>
+ <array>
+ <string>1C37FBAC04509CD000000102</string>
+ <string>1C37FAAC04509CD000000102</string>
+ <string>1C08E77C0454961000C914BD</string>
+ <string>1C37FABC05509CD000000102</string>
+ <string>1C37FABC05539CD112110102</string>
+ <string>E2644B35053B69B200211256</string>
+ <string>1C37FABC04509CD000100104</string>
+ <string>1CC0EA4004350EF90044410B</string>
+ <string>1CC0EA4004350EF90041110B</string>
+ </array>
+ <key>PBXProjectModuleGUID</key>
+ <string>11E0B1FE06471DED0097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Files</string>
+ <key>PBXProjectStructureProvided</key>
+ <string>yes</string>
+ <key>PBXSmartGroupTreeModuleColumnData</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleColumnWidthsKey</key>
+ <array>
+ <real>186</real>
+ </array>
+ <key>PBXSmartGroupTreeModuleColumnsKey_v4</key>
+ <array>
+ <string>MainColumn</string>
+ </array>
+ </dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key>
+ <array>
+ <string>29B97314FDCFA39411CA2CEA</string>
+ <string>1C37FABC05509CD000000102</string>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key>
+ <array>
+ <array>
+ <integer>0</integer>
+ </array>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key>
+ <string>{{0, 0}, {186, 337}}</string>
+ </dict>
+ <key>PBXTopSmartGroupGIDs</key>
+ <array/>
+ <key>XCIncludePerspectivesSwitch</key>
+ <integer>1</integer>
+ <key>XCSharingToken</key>
+ <string>com.apple.Xcode.GFSharingToken</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {203, 355}}</string>
+ <key>GroupTreeTableConfiguration</key>
+ <array>
+ <string>MainColumn</string>
+ <real>186</real>
+ </array>
+ <key>RubberWindowFrame</key>
+ <string>373 269 690 397 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXSmartGroupTreeModule</string>
+ <key>Proportion</key>
+ <string>100%</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Morph</string>
+ <key>PreferredWidth</key>
+ <integer>300</integer>
+ <key>ServiceClasses</key>
+ <array>
+ <string>XCModuleDock</string>
+ <string>PBXSmartGroupTreeModule</string>
+ </array>
+ <key>TableOfContents</key>
+ <array>
+ <string>11E0B1FE06471DED0097A5F4</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.default.short</string>
+ </dict>
+ </array>
+ <key>PerspectivesBarVisible</key>
+ <false/>
+ <key>ShelfIsVisible</key>
+ <false/>
+ <key>SourceDescription</key>
+ <string>file at '/System/Library/PrivateFrameworks/DevToolsInterface.framework/Versions/A/Resources/XCPerspectivesSpecificationMode1.xcperspec'</string>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TimeStamp</key>
+ <real>0.0</real>
+ <key>ToolbarDisplayMode</key>
+ <integer>1</integer>
+ <key>ToolbarIsVisible</key>
+ <true/>
+ <key>ToolbarSizeMode</key>
+ <integer>1</integer>
+ <key>Type</key>
+ <string>Perspectives</string>
+ <key>UpdateMessage</key>
+ <string>The Default Workspace in this version of Xcode now includes support to hide and show the detail view (what has been referred to as the "Metro-Morph" feature). You must discard your current Default Workspace settings and update to the latest Default Workspace in order to gain this feature. Do you wish to update to the latest Workspace defaults for project '%@'?</string>
+ <key>WindowJustification</key>
+ <integer>5</integer>
+ <key>WindowOrderList</key>
+ <array>
+ <string>B7F76CDA0B41FBC2002CF8BE</string>
+ <string>1C0AD2B3069F1EA900FABCE6</string>
+ <string>/Users/jinx/Dev/Wiidi/Wiidi.xcodeproj</string>
+ </array>
+ <key>WindowString</key>
+ <string>0 100 1440 778 0 0 1440 878 </string>
+ <key>WindowTools</key>
+ <array>
+ <dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>windowTool.build</string>
+ <key>IsVertical</key>
+ <true/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CD0528F0623707200166675</string>
+ <key>PBXProjectModuleLabel</key>
+ <string></string>
+ <key>StatusBarVisibility</key>
+ <true/>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {1440, 495}}</string>
+ <key>RubberWindowFrame</key>
+ <string>0 101 1440 777 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Proportion</key>
+ <string>495pt</string>
+ </dict>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>XCMainBuildResultsModuleGUID</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Build</string>
+ <key>XCBuildResultsTrigger_Collapse</key>
+ <integer>1021</integer>
+ <key>XCBuildResultsTrigger_Open</key>
+ <integer>1011</integer>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 500}, {1440, 236}}</string>
+ <key>RubberWindowFrame</key>
+ <string>0 101 1440 777 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXBuildResultsModule</string>
+ <key>Proportion</key>
+ <string>236pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>736pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Build Results</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXBuildResultsModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TableOfContents</key>
+ <array>
+ <string>B7436DA20B3C7E9B00F36279</string>
+ <string>B773E3820B41EC0F00F7B574</string>
+ <string>1CD0528F0623707200166675</string>
+ <string>XCMainBuildResultsModuleGUID</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.build</string>
+ <key>WindowString</key>
+ <string>0 101 1440 777 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>B7436DA20B3C7E9B00F36279</string>
+ <key>WindowToolIsVisible</key>
+ <false/>
+ </dict>
+ <dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>windowTool.debugger</string>
+ <key>IsVertical</key>
+ <true/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>Debugger</key>
+ <dict>
+ <key>HorizontalSplitView</key>
+ <dict>
+ <key>_collapsingFrameDimension</key>
+ <real>0.0</real>
+ <key>_indexOfCollapsedView</key>
+ <integer>0</integer>
+ <key>_percentageOfCollapsedView</key>
+ <real>0.0</real>
+ <key>isCollapsed</key>
+ <string>yes</string>
+ <key>sizes</key>
+ <array>
+ <string>{{0, 0}, {576, 304}}</string>
+ <string>{{576, 0}, {864, 304}}</string>
+ </array>
+ </dict>
+ <key>VerticalSplitView</key>
+ <dict>
+ <key>_collapsingFrameDimension</key>
+ <real>0.0</real>
+ <key>_indexOfCollapsedView</key>
+ <integer>0</integer>
+ <key>_percentageOfCollapsedView</key>
+ <real>0.0</real>
+ <key>isCollapsed</key>
+ <string>yes</string>
+ <key>sizes</key>
+ <array>
+ <string>{{0, 0}, {1440, 304}}</string>
+ <string>{{0, 304}, {1440, 432}}</string>
+ </array>
+ </dict>
+ </dict>
+ <key>LauncherConfigVersion</key>
+ <string>8</string>
+ <key>PBXProjectModuleGUID</key>
+ <string>1C162984064C10D400B95A72</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Debug - GLUTExamples (Underwater)</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>DebugConsoleDrawerSize</key>
+ <string>{100, 120}</string>
+ <key>DebugConsoleVisible</key>
+ <string>None</string>
+ <key>DebugConsoleWindowFrame</key>
+ <string>{{200, 200}, {500, 300}}</string>
+ <key>DebugSTDIOWindowFrame</key>
+ <string>{{200, 200}, {500, 300}}</string>
+ <key>Frame</key>
+ <string>{{0, 0}, {1440, 736}}</string>
+ <key>RubberWindowFrame</key>
+ <string>0 101 1440 777 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXDebugSessionModule</string>
+ <key>Proportion</key>
+ <string>736pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>736pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Debugger</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXDebugSessionModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TableOfContents</key>
+ <array>
+ <string>1CD10A99069EF8BA00B06720</string>
+ <string>B72023DD0B4177FC0036D182</string>
+ <string>1C162984064C10D400B95A72</string>
+ <string>B72023DE0B4177FC0036D182</string>
+ <string>B72023DF0B4177FC0036D182</string>
+ <string>B72023E00B4177FC0036D182</string>
+ <string>B72023E10B4177FC0036D182</string>
+ <string>B72023E20B4177FC0036D182</string>
+ <string>B72023E30B4177FC0036D182</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.debug</string>
+ <key>WindowString</key>
+ <string>0 101 1440 777 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>1CD10A99069EF8BA00B06720</string>
+ <key>WindowToolIsVisible</key>
+ <false/>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>windowTool.find</string>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CDD528C0622207200134675</string>
+ <key>PBXProjectModuleLabel</key>
+ <string><No Editor></string>
+ <key>PBXSplitModuleInNavigatorKey</key>
+ <dict>
+ <key>Split0</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CD0528D0623707200166675</string>
+ </dict>
+ <key>SplitCount</key>
+ <string>1</string>
+ </dict>
+ <key>StatusBarVisibility</key>
+ <integer>1</integer>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {781, 167}}</string>
+ <key>RubberWindowFrame</key>
+ <string>62 385 781 470 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Proportion</key>
+ <string>781pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>50%</string>
+ </dict>
+ <dict>
+ <key>BecomeActive</key>
+ <integer>1</integer>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CD0528E0623707200166675</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Project Find</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{8, 0}, {773, 254}}</string>
+ <key>RubberWindowFrame</key>
+ <string>62 385 781 470 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXProjectFindModule</string>
+ <key>Proportion</key>
+ <string>50%</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>428pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Project Find</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXProjectFindModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <integer>1</integer>
+ <key>TableOfContents</key>
+ <array>
+ <string>1C530D57069F1CE1000CFCEE</string>
+ <string>1C530D58069F1CE1000CFCEE</string>
+ <string>1C530D59069F1CE1000CFCEE</string>
+ <string>1CDD528C0622207200134675</string>
+ <string>1C530D5A069F1CE1000CFCEE</string>
+ <string>1CE0B1FE06471DED0097A5F4</string>
+ <string>1CD0528E0623707200166675</string>
+ </array>
+ <key>WindowString</key>
+ <string>62 385 781 470 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>1C530D57069F1CE1000CFCEE</string>
+ <key>WindowToolIsVisible</key>
+ <integer>0</integer>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>MENUSEPARATOR</string>
+ </dict>
+ <dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>windowTool.debuggerConsole</string>
+ <key>IsVertical</key>
+ <true/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1C78EAAC065D492600B07095</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Debugger Console</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {440, 358}}</string>
+ <key>RubberWindowFrame</key>
+ <string>63 409 440 400 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXDebugCLIModule</string>
+ <key>Proportion</key>
+ <string>358pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>359pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Debugger Console</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXDebugCLIModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TableOfContents</key>
+ <array>
+ <string>B72507CF0B3CB40D00555F92</string>
+ <string>B72023E40B4177FC0036D182</string>
+ <string>1C78EAAC065D492600B07095</string>
+ </array>
+ <key>WindowString</key>
+ <string>63 409 440 400 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>B72507CF0B3CB40D00555F92</string>
+ <key>WindowToolIsVisible</key>
+ <false/>
+ </dict>
+ <dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>windowTool.run</string>
+ <key>IsVertical</key>
+ <true/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>LauncherConfigVersion</key>
+ <string>3</string>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CD0528B0623707200166675</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Run</string>
+ <key>Runner</key>
+ <dict>
+ <key>HorizontalSplitView</key>
+ <dict>
+ <key>_collapsingFrameDimension</key>
+ <real>0.0</real>
+ <key>_indexOfCollapsedView</key>
+ <integer>0</integer>
+ <key>_percentageOfCollapsedView</key>
+ <real>0.0</real>
+ <key>isCollapsed</key>
+ <string>yes</string>
+ <key>sizes</key>
+ <array>
+ <string>{{0, 0}, {367, 168}}</string>
+ <string>{{0, 173}, {367, 270}}</string>
+ </array>
+ </dict>
+ <key>VerticalSplitView</key>
+ <dict>
+ <key>_collapsingFrameDimension</key>
+ <real>0.0</real>
+ <key>_indexOfCollapsedView</key>
+ <integer>0</integer>
+ <key>_percentageOfCollapsedView</key>
+ <real>0.0</real>
+ <key>isCollapsed</key>
+ <string>yes</string>
+ <key>sizes</key>
+ <array>
+ <string>{{0, 0}, {406, 443}}</string>
+ <string>{{411, 0}, {517, 443}}</string>
+ </array>
+ </dict>
+ </dict>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {1121, 672}}</string>
+ <key>RubberWindowFrame</key>
+ <string>232 145 1121 713 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXRunSessionModule</string>
+ <key>Proportion</key>
+ <string>672pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>672pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Run Log</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXRunSessionModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TableOfContents</key>
+ <array>
+ <string>1C0AD2B3069F1EA900FABCE6</string>
+ <string>B7F76CD80B41FBC2002CF8BE</string>
+ <string>1CD0528B0623707200166675</string>
+ <string>B7F76CD90B41FBC2002CF8BE</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.run</string>
+ <key>WindowString</key>
+ <string>232 145 1121 713 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>1C0AD2B3069F1EA900FABCE6</string>
+ <key>WindowToolIsVisible</key>
+ <true/>
+ </dict>
+ <dict>
+ <key>FirstTimeWindowDisplayed</key>
+ <false/>
+ <key>Identifier</key>
+ <string>windowTool.scm</string>
+ <key>IsVertical</key>
+ <true/>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1C78EAB2065D492600B07095</string>
+ <key>PBXProjectModuleLabel</key>
+ <string></string>
+ <key>StatusBarVisibility</key>
+ <true/>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {452, 0}}</string>
+ <key>RubberWindowFrame</key>
+ <string>21 547 452 308 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Proportion</key>
+ <string>0pt</string>
+ </dict>
+ <dict>
+ <key>BecomeActive</key>
+ <true/>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CD052920623707200166675</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>SCM Results</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 5}, {452, 262}}</string>
+ <key>RubberWindowFrame</key>
+ <string>21 547 452 308 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXCVSModule</string>
+ <key>Proportion</key>
+ <string>262pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>267pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>SCM</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXCVSModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <true/>
+ <key>TableOfContents</key>
+ <array>
+ <string>B7F76CDA0B41FBC2002CF8BE</string>
+ <string>B7F76CDB0B41FBC2002CF8BE</string>
+ <string>1C78EAB2065D492600B07095</string>
+ <string>1CD052920623707200166675</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.scm</string>
+ <key>WindowString</key>
+ <string>21 547 452 308 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>B7F76CDA0B41FBC2002CF8BE</string>
+ <key>WindowToolIsVisible</key>
+ <false/>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>windowTool.breakpoints</string>
+ <key>IsVertical</key>
+ <integer>0</integer>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>BecomeActive</key>
+ <integer>1</integer>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXBottomSmartGroupGIDs</key>
+ <array>
+ <string>1C77FABC04509CD000000102</string>
+ </array>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CE0B1FE06471DED0097A5F4</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Files</string>
+ <key>PBXProjectStructureProvided</key>
+ <string>no</string>
+ <key>PBXSmartGroupTreeModuleColumnData</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleColumnWidthsKey</key>
+ <array>
+ <real>168</real>
+ </array>
+ <key>PBXSmartGroupTreeModuleColumnsKey_v4</key>
+ <array>
+ <string>MainColumn</string>
+ </array>
+ </dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateKey_v7</key>
+ <dict>
+ <key>PBXSmartGroupTreeModuleOutlineStateExpansionKey</key>
+ <array>
+ <string>1C77FABC04509CD000000102</string>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateSelectionKey</key>
+ <array>
+ <array>
+ <integer>0</integer>
+ </array>
+ </array>
+ <key>PBXSmartGroupTreeModuleOutlineStateVisibleRectKey</key>
+ <string>{{0, 0}, {168, 350}}</string>
+ </dict>
+ <key>PBXTopSmartGroupGIDs</key>
+ <array/>
+ <key>XCIncludePerspectivesSwitch</key>
+ <integer>0</integer>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{0, 0}, {185, 368}}</string>
+ <key>GroupTreeTableConfiguration</key>
+ <array>
+ <string>MainColumn</string>
+ <real>168</real>
+ </array>
+ <key>RubberWindowFrame</key>
+ <string>315 424 744 409 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXSmartGroupTreeModule</string>
+ <key>Proportion</key>
+ <string>185pt</string>
+ </dict>
+ <dict>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CA1AED706398EBD00589147</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Detail</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>Frame</key>
+ <string>{{190, 0}, {554, 368}}</string>
+ <key>RubberWindowFrame</key>
+ <string>315 424 744 409 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>XCDetailModule</string>
+ <key>Proportion</key>
+ <string>554pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>368pt</string>
+ </dict>
+ </array>
+ <key>MajorVersion</key>
+ <integer>2</integer>
+ <key>MinorVersion</key>
+ <integer>0</integer>
+ <key>Name</key>
+ <string>Breakpoints</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXSmartGroupTreeModule</string>
+ <string>XCDetailModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <integer>1</integer>
+ <key>TableOfContents</key>
+ <array>
+ <string>1CDDB66807F98D9800BB5817</string>
+ <string>1CDDB66907F98D9800BB5817</string>
+ <string>1CE0B1FE06471DED0097A5F4</string>
+ <string>1CA1AED706398EBD00589147</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.breakpoints</string>
+ <key>WindowString</key>
+ <string>315 424 744 409 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>1CDDB66807F98D9800BB5817</string>
+ <key>WindowToolIsVisible</key>
+ <integer>1</integer>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>windowTool.debugAnimator</string>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>Module</key>
+ <string>PBXNavigatorGroup</string>
+ <key>Proportion</key>
+ <string>100%</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>100%</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Debug Visualizer</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXNavigatorGroup</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <integer>1</integer>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.debugAnimator</string>
+ <key>WindowString</key>
+ <string>100 100 700 500 0 0 1280 1002 </string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>windowTool.bookmarks</string>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>Module</key>
+ <string>PBXBookmarksModule</string>
+ <key>Proportion</key>
+ <string>100%</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>100%</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Bookmarks</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXBookmarksModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <integer>0</integer>
+ <key>WindowString</key>
+ <string>538 42 401 187 0 0 1280 1002 </string>
+ </dict>
+ <dict>
+ <key>Identifier</key>
+ <string>windowTool.classBrowser</string>
+ <key>Layout</key>
+ <array>
+ <dict>
+ <key>Dock</key>
+ <array>
+ <dict>
+ <key>BecomeActive</key>
+ <integer>1</integer>
+ <key>ContentConfiguration</key>
+ <dict>
+ <key>OptionsSetName</key>
+ <string>Hierarchy, all classes</string>
+ <key>PBXProjectModuleGUID</key>
+ <string>1CA6456E063B45B4001379D8</string>
+ <key>PBXProjectModuleLabel</key>
+ <string>Class Browser - NSObject</string>
+ </dict>
+ <key>GeometryConfiguration</key>
+ <dict>
+ <key>ClassesFrame</key>
+ <string>{{0, 0}, {374, 96}}</string>
+ <key>ClassesTreeTableConfiguration</key>
+ <array>
+ <string>PBXClassNameColumnIdentifier</string>
+ <real>208</real>
+ <string>PBXClassBookColumnIdentifier</string>
+ <real>22</real>
+ </array>
+ <key>Frame</key>
+ <string>{{0, 0}, {630, 331}}</string>
+ <key>MembersFrame</key>
+ <string>{{0, 105}, {374, 395}}</string>
+ <key>MembersTreeTableConfiguration</key>
+ <array>
+ <string>PBXMemberTypeIconColumnIdentifier</string>
+ <real>22</real>
+ <string>PBXMemberNameColumnIdentifier</string>
+ <real>216</real>
+ <string>PBXMemberTypeColumnIdentifier</string>
+ <real>97</real>
+ <string>PBXMemberBookColumnIdentifier</string>
+ <real>22</real>
+ </array>
+ <key>PBXModuleWindowStatusBarHidden2</key>
+ <integer>1</integer>
+ <key>RubberWindowFrame</key>
+ <string>385 179 630 352 0 0 1440 878 </string>
+ </dict>
+ <key>Module</key>
+ <string>PBXClassBrowserModule</string>
+ <key>Proportion</key>
+ <string>332pt</string>
+ </dict>
+ </array>
+ <key>Proportion</key>
+ <string>332pt</string>
+ </dict>
+ </array>
+ <key>Name</key>
+ <string>Class Browser</string>
+ <key>ServiceClasses</key>
+ <array>
+ <string>PBXClassBrowserModule</string>
+ </array>
+ <key>StatusbarIsVisible</key>
+ <integer>0</integer>
+ <key>TableOfContents</key>
+ <array>
+ <string>1C0AD2AF069F1E9B00FABCE6</string>
+ <string>1C0AD2B0069F1E9B00FABCE6</string>
+ <string>1CA6456E063B45B4001379D8</string>
+ </array>
+ <key>ToolbarConfiguration</key>
+ <string>xcode.toolbar.config.classbrowser</string>
+ <key>WindowString</key>
+ <string>385 179 630 352 0 0 1440 878 </string>
+ <key>WindowToolGUID</key>
+ <string>1C0AD2AF069F1E9B00FABCE6</string>
+ <key>WindowToolIsVisible</key>
+ <integer>0</integer>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/Wiidi.xcodeproj/jinx.pbxuser b/Wiidi.xcodeproj/jinx.pbxuser
new file mode 100644
index 0000000..1ca4e3a
--- /dev/null
+++ b/Wiidi.xcodeproj/jinx.pbxuser
@@ -0,0 +1,762 @@
+// !$*UTF8*$!
+{
+ 29B97313FDCFA39411CA2CEA /* Project object */ = {
+ activeBuildConfigurationName = Debug;
+ activeBuildStyle = 4A9504CCFFE6A4B311CA0CBA /* Debug */;
+ activeExecutable = B76A099D0B3C38E500C013AB /* Wiidi */;
+ activeTarget = 8D1107260486CEB800E47090 /* Wiidi */;
+ addToTargets = (
+ 8D1107260486CEB800E47090 /* Wiidi */,
+ );
+ breakpoints = (
+ B720247E0B4189C40036D182 /* WiiGestures.m:101 */,
+ );
+ breakpointsGroup = B725086C0B3CC0AF00555F92 /* XCBreakpointsBucket */;
+ codeSenseManager = B76A09A90B3C390500C013AB /* Code sense */;
+ executables = (
+ B76A099D0B3C38E500C013AB /* Wiidi */,
+ );
+ perUserDictionary = {
+ PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 20,
+ 954,
+ 20,
+ 48,
+ 43,
+ 43,
+ 20,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXFileDataSource_FiletypeID,
+ PBXFileDataSource_Filename_ColumnID,
+ PBXFileDataSource_Built_ColumnID,
+ PBXFileDataSource_ObjectSize_ColumnID,
+ PBXFileDataSource_Errors_ColumnID,
+ PBXFileDataSource_Warnings_ColumnID,
+ PBXFileDataSource_Target_ColumnID,
+ );
+ };
+ PBXConfiguration.PBXFileTableDataSource3.PBXSymbolsDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXSymbolsDataSource_SymbolNameID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 16,
+ 200,
+ 50,
+ 200,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXSymbolsDataSource_SymbolTypeIconID,
+ PBXSymbolsDataSource_SymbolNameID,
+ PBXSymbolsDataSource_SymbolTypeID,
+ PBXSymbolsDataSource_ReferenceNameID,
+ );
+ };
+ PBXConfiguration.PBXFileTableDataSource3.XCSCMDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 20,
+ 20,
+ 930,
+ 20,
+ 48,
+ 43,
+ 43,
+ 20,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXFileDataSource_SCM_ColumnID,
+ PBXFileDataSource_FiletypeID,
+ PBXFileDataSource_Filename_ColumnID,
+ PBXFileDataSource_Built_ColumnID,
+ PBXFileDataSource_ObjectSize_ColumnID,
+ PBXFileDataSource_Errors_ColumnID,
+ PBXFileDataSource_Warnings_ColumnID,
+ PBXFileDataSource_Target_ColumnID,
+ );
+ };
+ PBXConfiguration.PBXTargetDataSource.PBXTargetDataSource = {
+ PBXFileTableDataSourceColumnSortingDirectionKey = "-1";
+ PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID;
+ PBXFileTableDataSourceColumnWidthsKey = (
+ 20,
+ 200,
+ 774,
+ 20,
+ 48.1626,
+ 43,
+ 43,
+ );
+ PBXFileTableDataSourceColumnsKey = (
+ PBXFileDataSource_FiletypeID,
+ PBXFileDataSource_Filename_ColumnID,
+ PBXTargetDataSource_PrimaryAttribute,
+ PBXFileDataSource_Built_ColumnID,
+ PBXFileDataSource_ObjectSize_ColumnID,
+ PBXFileDataSource_Errors_ColumnID,
+ PBXFileDataSource_Warnings_ColumnID,
+ );
+ };
+ PBXPerProjectTemplateStateSaveDate = 188873527;
+ PBXWorkspaceStateSaveDate = 188873527;
+ };
+ perUserProjectItems = {
+ B72024C30B41DC730036D182 /* PBXTextBookmark */ = B72024C30B41DC730036D182 /* PBXTextBookmark */;
+ B72024D80B41DF540036D182 /* PBXTextBookmark */ = B72024D80B41DF540036D182 /* PBXTextBookmark */;
+ B72024E80B41DFD80036D182 /* PBXTextBookmark */ = B72024E80B41DFD80036D182 /* PBXTextBookmark */;
+ B72024FA0B41E0780036D182 /* PBXTextBookmark */ = B72024FA0B41E0780036D182 /* PBXTextBookmark */;
+ B72025010B41E12D0036D182 /* PBXTextBookmark */ = B72025010B41E12D0036D182 /* PBXTextBookmark */;
+ B7250A220B3D3FE200555F92 /* PBXTextBookmark */ = B7250A220B3D3FE200555F92 /* PBXTextBookmark */;
+ B7250A250B3D3FE200555F92 /* PBXTextBookmark */ = B7250A250B3D3FE200555F92 /* PBXTextBookmark */;
+ B7250AF20B3D592600555F92 /* PBXTextBookmark */ = B7250AF20B3D592600555F92 /* PBXTextBookmark */;
+ B7250AF30B3D592600555F92 /* PBXTextBookmark */ = B7250AF30B3D592600555F92 /* PBXTextBookmark */;
+ B7250C670B3DBF7600555F92 /* PBXTextBookmark */ = B7250C670B3DBF7600555F92 /* PBXTextBookmark */;
+ B7250C9D0B3DC76200555F92 /* PBXTextBookmark */ = B7250C9D0B3DC76200555F92 /* PBXTextBookmark */;
+ B7250DE00B3DEABA00555F92 /* PBXTextBookmark */ = B7250DE00B3DEABA00555F92 /* PBXTextBookmark */;
+ B7250E040B3DEDAA00555F92 /* PBXTextBookmark */ = B7250E040B3DEDAA00555F92 /* PBXTextBookmark */;
+ B7250F060B3E675100555F92 /* PBXTextBookmark */ = B7250F060B3E675100555F92 /* PBXTextBookmark */;
+ B7436D9F0B3C7E9B00F36279 /* PBXTextBookmark */ = B7436D9F0B3C7E9B00F36279 /* PBXTextBookmark */;
+ B7436DA00B3C7E9B00F36279 /* PBXTextBookmark */ = B7436DA00B3C7E9B00F36279 /* PBXTextBookmark */;
+ B7436DF60B3C88EF00F36279 /* PBXTextBookmark */ = B7436DF60B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436DFA0B3C88EF00F36279 /* PBXTextBookmark */ = B7436DFA0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436DFC0B3C88EF00F36279 /* PBXTextBookmark */ = B7436DFC0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436DFE0B3C88EF00F36279 /* PBXTextBookmark */ = B7436DFE0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E000B3C88EF00F36279 /* PBXTextBookmark */ = B7436E000B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E020B3C88EF00F36279 /* PBXTextBookmark */ = B7436E020B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E070B3C88EF00F36279 /* PBXTextBookmark */ = B7436E070B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E080B3C88EF00F36279 /* PBXTextBookmark */ = B7436E080B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E0A0B3C88EF00F36279 /* PBXTextBookmark */ = B7436E0A0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E0C0B3C88EF00F36279 /* PBXTextBookmark */ = B7436E0C0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E0E0B3C88EF00F36279 /* PBXTextBookmark */ = B7436E0E0B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E100B3C88EF00F36279 /* PBXTextBookmark */ = B7436E100B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E140B3C88EF00F36279 /* PBXTextBookmark */ = B7436E140B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E170B3C88EF00F36279 /* PBXTextBookmark */ = B7436E170B3C88EF00F36279 /* PBXTextBookmark */;
+ B7436E250B3C88EF00F36279 /* PBXTextBookmark */ = B7436E250B3C88EF00F36279 /* PBXTextBookmark */;
+ B753225C0B410850005F3DE8 /* PBXTextBookmark */ = B753225C0B410850005F3DE8 /* PBXTextBookmark */;
+ B753225D0B410850005F3DE8 /* PBXTextBookmark */ = B753225D0B410850005F3DE8 /* PBXTextBookmark */;
+ B75322690B410850005F3DE8 /* PBXTextBookmark */ = B75322690B410850005F3DE8 /* PBXTextBookmark */;
+ B753226C0B410850005F3DE8 /* PBXTextBookmark */ = B753226C0B410850005F3DE8 /* PBXTextBookmark */;
+ B773E3850B41FA1600F7B574 /* PBXTextBookmark */ = B773E3850B41FA1600F7B574 /* PBXTextBookmark */;
+ B7F76CE30B41FC5D002CF8BE /* PBXTextBookmark */ = B7F76CE30B41FC5D002CF8BE /* PBXTextBookmark */;
+ };
+ sourceControlManager = B76A09A80B3C390500C013AB /* Source Control */;
+ userBuildSettings = {
+ };
+ };
+ 29B97316FDCFA39411CA2CEA /* main.m */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 700}}";
+ sepNavSelRange = "{0, 0}";
+ sepNavVisRect = "{{0, 0}, {1152, 700}}";
+ };
+ };
+ 8D1107260486CEB800E47090 /* Wiidi */ = {
+ activeExec = 0;
+ executables = (
+ B76A099D0B3C38E500C013AB /* Wiidi */,
+ );
+ };
+ B720247E0B4189C40036D182 /* WiiGestures.m:101 */ = {
+ isa = PBXFileBreakpoint;
+ actions = (
+ );
+ continueAfterActions = 0;
+ delayBeforeContinue = 0;
+ fileReference = B75322340B40982C005F3DE8 /* WiiGestures.m */;
+ functionName = "-wiimoteData:lastData:";
+ hitCount = 1;
+ lineNumber = 101;
+ modificationTime = 188865663.934678;
+ state = 1;
+ };
+ B72024C30B41DC730036D182 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B75322330B40982C005F3DE8 /* WiiGestures.h */;
+ name = "WiiGestures.h: SIMILAR";
+ rLen = 0;
+ rLoc = 194;
+ rType = 0;
+ vrLen = 343;
+ vrLoc = 0;
+ };
+ B72024D80B41DF540036D182 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436D980B3C6CDF00F36279 /* AppController.m */;
+ name = "AppController.m: 11";
+ rLen = 0;
+ rLoc = 144;
+ rType = 0;
+ vrLen = 968;
+ vrLoc = 0;
+ };
+ B72024E80B41DFD80036D182 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7250AC00B3D572600555F92 /* Miidi.m */;
+ name = "Miidi.m: 82";
+ rLen = 0;
+ rLoc = 2260;
+ rType = 0;
+ vrLen = 1412;
+ vrLoc = 429;
+ };
+ B72024FA0B41E0780036D182 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DA80B3C7FAA00F36279 /* Wiimote.h */;
+ name = "Wiimote.h: initialized";
+ rLen = 0;
+ rLoc = 2676;
+ rType = 0;
+ vrLen = 1067;
+ vrLoc = 2289;
+ };
+ B72025010B41E12D0036D182 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DA90B3C7FAA00F36279 /* Wiimote.m */;
+ name = "Wiimote.m: 309";
+ rLen = 0;
+ rLoc = 7754;
+ rType = 0;
+ vrLen = 1011;
+ vrLoc = 7473;
+ };
+ B725086C0B3CC0AF00555F92 /* XCBreakpointsBucket */ = {
+ isa = XCBreakpointsBucket;
+ name = "Project Breakpoints";
+ objects = (
+ B720247E0B4189C40036D182 /* WiiGestures.m:101 */,
+ );
+ };
+ B7250A220B3D3FE200555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = 29B97316FDCFA39411CA2CEA /* main.m */;
+ name = "main.m: 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 244;
+ vrLoc = 0;
+ };
+ B7250A250B3D3FE200555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = 29B97316FDCFA39411CA2CEA /* main.m */;
+ name = "main.m: 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 244;
+ vrLoc = 0;
+ };
+ B7250ABF0B3D572600555F92 /* Miidi.h */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 700}}";
+ sepNavSelRange = "{930, 0}";
+ sepNavVisRect = "{{0, 0}, {1152, 700}}";
+ };
+ };
+ B7250AC00B3D572600555F92 /* Miidi.m */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 2432}}";
+ sepNavSelRange = "{2260, 0}";
+ sepNavVisRect = "{{0, 372}, {1152, 700}}";
+ };
+ };
+ B7250AF20B3D592600555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7250ABF0B3D572600555F92 /* Miidi.h */;
+ name = "Miidi.h: 12";
+ rLen = 0;
+ rLoc = 593;
+ rType = 0;
+ vrLen = 226;
+ vrLoc = 0;
+ };
+ B7250AF30B3D592600555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7250AC00B3D572600555F92 /* Miidi.m */;
+ name = "Miidi.m: 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 172;
+ vrLoc = 0;
+ };
+ B7250C670B3DBF7600555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436F750B3CAC6400F36279 /* AppController.mm */;
+ name = "AppController.mm: 105";
+ rLen = 0;
+ rLoc = 2997;
+ rType = 0;
+ vrLen = 1457;
+ vrLoc = 2334;
+ };
+ B7250C9D0B3DC76200555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DF90B3C88EF00F36279 /* IOBluetoothL2CAPChannel.h */;
+ name = "IOBluetoothL2CAPChannel.h: 337";
+ rLen = 433;
+ rLoc = 16277;
+ rType = 0;
+ vrLen = 2155;
+ vrLoc = 14630;
+ };
+ B7250DE00B3DEABA00555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E630B3C8E7C00F36279 /* WiiRemote.m */;
+ name = kIOReturnSuccess;
+ rLen = 16;
+ rLoc = 3681;
+ rType = 0;
+ vrLen = 1243;
+ vrLoc = 4035;
+ };
+ B7250E040B3DEDAA00555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E630B3C8E7C00F36279 /* WiiRemote.m */;
+ name = "((short)dp[2] << 8) + dp[3]";
+ rLen = 27;
+ rLoc = 4116;
+ rType = 0;
+ vrLen = 1315;
+ vrLoc = 3792;
+ };
+ B7250F060B3E675100555F92 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436F750B3CAC6400F36279 /* AppController.mm */;
+ name = "z < lastPosition[Z] && z > 0 && abs(lastPosition[Z] - z) > 0.03";
+ rLen = 64;
+ rLoc = 4166;
+ rType = 0;
+ vrLen = 1503;
+ vrLoc = 1908;
+ };
+ B7436D970B3C6CDF00F36279 /* AppController.h */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 700}}";
+ sepNavSelRange = "{300, 0}";
+ sepNavVisRect = "{{0, 0}, {1152, 700}}";
+ };
+ };
+ B7436D980B3C6CDF00F36279 /* AppController.m */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 704}}";
+ sepNavSelRange = "{144, 0}";
+ sepNavVisRect = "{{0, 0}, {1152, 700}}";
+ sepNavWindowFrame = "{{15, 45}, {1055, 833}}";
+ };
+ };
+ B7436D9F0B3C7E9B00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436D980B3C6CDF00F36279 /* AppController.m */;
+ name = "AppController.m: 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 63;
+ vrLoc = 0;
+ };
+ B7436DA00B3C7E9B00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436D970B3C6CDF00F36279 /* AppController.h */;
+ name = "AppController.h: 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 168;
+ vrLoc = 0;
+ };
+ B7436DA80B3C7FAA00F36279 /* Wiimote.h */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 2768}}";
+ sepNavSelRange = "{2676, 0}";
+ sepNavVisRect = "{{0, 1856}, {1152, 700}}";
+ };
+ };
+ B7436DA90B3C7FAA00F36279 /* Wiimote.m */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 9024}}";
+ sepNavSelRange = "{7754, 0}";
+ sepNavVisRect = "{{0, 4691}, {1152, 700}}";
+ sepNavWindowFrame = "{{15, 45}, {1055, 833}}";
+ };
+ };
+ B7436DF60B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DF70B3C88EF00F36279 /* IOBluetoothSDPDataElement.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 1797;
+ vrLoc = 10557;
+ };
+ B7436DF70B3C88EF00F36279 /* IOBluetoothSDPDataElement.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothSDPDataElement.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothSDPDataElement.h;
+ sourceTree = "<absolute>";
+ };
+ B7436DF90B3C88EF00F36279 /* IOBluetoothL2CAPChannel.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothL2CAPChannel.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothL2CAPChannel.h;
+ sourceTree = "<absolute>";
+ };
+ B7436DFA0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DFB0B3C88EF00F36279 /* IOBluetoothObject.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 497;
+ vrLoc = 0;
+ };
+ B7436DFB0B3C88EF00F36279 /* IOBluetoothObject.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothObject.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothObject.h;
+ sourceTree = "<absolute>";
+ };
+ B7436DFC0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DFD0B3C88EF00F36279 /* IOBluetoothUserNotification.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 721;
+ vrLoc = 0;
+ };
+ B7436DFD0B3C88EF00F36279 /* IOBluetoothUserNotification.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothUserNotification.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothUserNotification.h;
+ sourceTree = "<absolute>";
+ };
+ B7436DFE0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DFF0B3C88EF00F36279 /* IOBluetoothDevice.h */;
+ name = inquiry;
+ rLen = 7;
+ rLoc = 23749;
+ rType = 0;
+ vrLen = 1826;
+ vrLoc = 22888;
+ };
+ B7436DFF0B3C88EF00F36279 /* IOBluetoothDevice.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothDevice.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothDevice.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E000B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E010B3C88EF00F36279 /* BluetoothAssignedNumbers.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 2249;
+ vrLoc = 17799;
+ };
+ B7436E010B3C88EF00F36279 /* BluetoothAssignedNumbers.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = BluetoothAssignedNumbers.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/BluetoothAssignedNumbers.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E020B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E030B3C88EF00F36279 /* IOBluetoothDeviceInquiry.h */;
+ name = "- (void)\tdeviceInquiryComplete:(IOBluetoothDeviceInquiry*)sender\terror:(IOReturn)error\taborted:(BOOL)aborted;";
+ rLen = 110;
+ rLoc = 13168;
+ rType = 0;
+ vrLen = 2500;
+ vrLoc = 10784;
+ };
+ B7436E030B3C88EF00F36279 /* IOBluetoothDeviceInquiry.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothDeviceInquiry.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothDeviceInquiry.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E070B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DA80B3C7FAA00F36279 /* Wiimote.h */;
+ name = "Wiimote.h: 36";
+ rLen = 0;
+ rLoc = 2545;
+ rType = 0;
+ vrLen = 651;
+ vrLoc = 0;
+ };
+ B7436E080B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E090B3C88EF00F36279 /* IOBluetoothSDPDataElement.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 1797;
+ vrLoc = 10557;
+ };
+ B7436E090B3C88EF00F36279 /* IOBluetoothSDPDataElement.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothSDPDataElement.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothSDPDataElement.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E0A0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E0B0B3C88EF00F36279 /* IOBluetoothL2CAPChannel.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 2470;
+ vrLoc = 8522;
+ };
+ B7436E0B0B3C88EF00F36279 /* IOBluetoothL2CAPChannel.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothL2CAPChannel.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothL2CAPChannel.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E0C0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E0D0B3C88EF00F36279 /* IOBluetoothObject.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 497;
+ vrLoc = 0;
+ };
+ B7436E0D0B3C88EF00F36279 /* IOBluetoothObject.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothObject.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothObject.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E0E0B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E0F0B3C88EF00F36279 /* IOBluetoothDevice.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 2846;
+ vrLoc = 16149;
+ };
+ B7436E0F0B3C88EF00F36279 /* IOBluetoothDevice.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothDevice.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothDevice.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E100B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E110B3C88EF00F36279 /* IOBluetoothUserNotification.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 721;
+ vrLoc = 0;
+ };
+ B7436E110B3C88EF00F36279 /* IOBluetoothUserNotification.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothUserNotification.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothUserNotification.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E140B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E150B3C88EF00F36279 /* IOBluetoothDeviceInquiry.h */;
+ name = IOBluetoothDeviceInquiryDelegate;
+ rLen = 32;
+ rLoc = 10262;
+ rType = 0;
+ vrLen = 2548;
+ vrLoc = 9825;
+ };
+ B7436E150B3C88EF00F36279 /* IOBluetoothDeviceInquiry.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = IOBluetoothDeviceInquiry.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/objc/IOBluetoothDeviceInquiry.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E170B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436E180B3C88EF00F36279 /* BluetoothAssignedNumbers.h */;
+ name = "(null): 1";
+ rLen = 0;
+ rLoc = 0;
+ rType = 0;
+ vrLen = 2249;
+ vrLoc = 17799;
+ };
+ B7436E180B3C88EF00F36279 /* BluetoothAssignedNumbers.h */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.h;
+ name = BluetoothAssignedNumbers.h;
+ path = /System/Library/Frameworks/IOBluetooth.framework/Headers/BluetoothAssignedNumbers.h;
+ sourceTree = "<absolute>";
+ };
+ B7436E250B3C88EF00F36279 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436DA90B3C7FAA00F36279 /* Wiimote.m */;
+ name = "Wiimote.m: 18";
+ rLen = 0;
+ rLoc = 722;
+ rType = 0;
+ vrLen = 506;
+ vrLoc = 0;
+ };
+ B7436E630B3C8E7C00F36279 /* WiiRemote.m */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.c.objc;
+ name = WiiRemote.m;
+ path = /Users/jinx/Download/DarwiinRemote/WiiRemote.m;
+ sourceTree = "<absolute>";
+ };
+ B7436F750B3CAC6400F36279 /* AppController.mm */ = {
+ isa = PBXFileReference;
+ lastKnownFileType = sourcecode.cpp.objcpp;
+ name = AppController.mm;
+ path = /Users/jinx/Download/DarwiinRemote/AppController.mm;
+ sourceTree = "<absolute>";
+ };
+ B75322330B40982C005F3DE8 /* WiiGestures.h */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 700}}";
+ sepNavSelRange = "{194, 0}";
+ sepNavVisRect = "{{0, 0}, {1152, 700}}";
+ };
+ };
+ B75322340B40982C005F3DE8 /* WiiGestures.m */ = {
+ uiCtxt = {
+ sepNavIntBoundsRect = "{{0, 0}, {1152, 2320}}";
+ sepNavSelRange = "{820, 0}";
+ sepNavVisRect = "{{0, 344}, {1152, 480}}";
+ };
+ };
+ B753225C0B410850005F3DE8 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7250ABF0B3D572600555F92 /* Miidi.h */;
+ name = "Miidi.h: MIDINoteForNunchuckButton:";
+ rLen = 0;
+ rLoc = 930;
+ rType = 0;
+ vrLen = 1039;
+ vrLoc = 0;
+ };
+ B753225D0B410850005F3DE8 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B7436D970B3C6CDF00F36279 /* AppController.h */;
+ name = "AppController.h: gestures";
+ rLen = 0;
+ rLoc = 300;
+ rType = 0;
+ vrLen = 308;
+ vrLoc = 0;
+ };
+ B75322690B410850005F3DE8 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B75322330B40982C005F3DE8 /* WiiGestures.h */;
+ name = "WiiGestures.h: 12";
+ rLen = 0;
+ rLoc = 281;
+ rType = 0;
+ vrLen = 238;
+ vrLoc = 0;
+ };
+ B753226C0B410850005F3DE8 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B75322340B40982C005F3DE8 /* WiiGestures.m */;
+ name = "WiiGestures.m: 12";
+ rLen = 0;
+ rLoc = 2397;
+ rType = 0;
+ vrLen = 190;
+ vrLoc = 0;
+ };
+ B76A099D0B3C38E500C013AB /* Wiidi */ = {
+ isa = PBXExecutable;
+ activeArgIndex = 2147483647;
+ activeArgIndices = (
+ );
+ argumentStrings = (
+ );
+ autoAttachOnCrash = 1;
+ configStateDict = {
+ };
+ customDataFormattersEnabled = 1;
+ debuggerPlugin = GDBDebugging;
+ disassemblyDisplayState = 0;
+ dylibVariantSuffix = "";
+ enableDebugStr = 1;
+ environmentEntries = (
+ );
+ executableSystemSymbolLevel = 0;
+ executableUserSymbolLevel = 0;
+ libgmallocEnabled = 0;
+ name = Wiidi;
+ savedGlobals = {
+ };
+ sourceDirectories = (
+ );
+ };
+ B76A09A80B3C390500C013AB /* Source Control */ = {
+ isa = PBXSourceControlManager;
+ fallbackIsa = XCSourceControlManager;
+ isSCMEnabled = 1;
+ scmConfiguration = {
+ SubversionToolPath = /usr/local/bin/svn;
+ };
+ scmType = scm.subversion;
+ };
+ B76A09A90B3C390500C013AB /* Code sense */ = {
+ isa = PBXCodeSenseManager;
+ indexTemplatePath = "";
+ };
+ B773E3850B41FA1600F7B574 /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B75322340B40982C005F3DE8 /* WiiGestures.m */;
+ name = "WiiGestures.m: 51";
+ rLen = 0;
+ rLoc = 1414;
+ rType = 0;
+ vrLen = 1889;
+ vrLoc = 275;
+ };
+ B7F76CE30B41FC5D002CF8BE /* PBXTextBookmark */ = {
+ isa = PBXTextBookmark;
+ fRef = B75322340B40982C005F3DE8 /* WiiGestures.m */;
+ name = "WiiGestures.m: 37";
+ rLen = 0;
+ rLoc = 820;
+ rType = 0;
+ vrLen = 1242;
+ vrLoc = 272;
+ };
+}
diff --git a/Wiidi.xcodeproj/project.pbxproj b/Wiidi.xcodeproj/project.pbxproj
new file mode 100644
index 0000000..6441d11
--- /dev/null
+++ b/Wiidi.xcodeproj/project.pbxproj
@@ -0,0 +1,354 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 42;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 8D11072A0486CEB800E47090 /* MainMenu.nib in Resources */ = {isa = PBXBuildFile; fileRef = 29B97318FDCFA39411CA2CEA /* MainMenu.nib */; };
+ 8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */; };
+ 8D11072D0486CEB800E47090 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; settings = {ATTRIBUTES = (); }; };
+ 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */; };
+ B7250AC10B3D572600555F92 /* Miidi.m in Sources */ = {isa = PBXBuildFile; fileRef = B7250AC00B3D572600555F92 /* Miidi.m */; };
+ B7250B0C0B3D596000555F92 /* CoreMIDI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B7250B0B0B3D596000555F92 /* CoreMIDI.framework */; };
+ B7250B100B3D596900555F92 /* CoreMIDIServer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B7250B0F0B3D596900555F92 /* CoreMIDIServer.framework */; };
+ B7436D990B3C6CDF00F36279 /* AppController.m in Sources */ = {isa = PBXBuildFile; fileRef = B7436D980B3C6CDF00F36279 /* AppController.m */; };
+ B7436DAA0B3C7FAA00F36279 /* Wiimote.m in Sources */ = {isa = PBXBuildFile; fileRef = B7436DA90B3C7FAA00F36279 /* Wiimote.m */; };
+ B7436DAF0B3C84C600F36279 /* IOBluetooth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B7436DAE0B3C84C600F36279 /* IOBluetooth.framework */; };
+ B75322350B40982C005F3DE8 /* WiiGestures.m in Sources */ = {isa = PBXBuildFile; fileRef = B75322340B40982C005F3DE8 /* WiiGestures.m */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXBuildStyle section */
+ 4A9504CCFFE6A4B311CA0CBA /* Debug */ = {
+ isa = PBXBuildStyle;
+ buildSettings = {
+ };
+ name = Debug;
+ };
+ 4A9504CDFFE6A4B311CA0CBA /* Release */ = {
+ isa = PBXBuildStyle;
+ buildSettings = {
+ };
+ name = Release;
+ };
+/* End PBXBuildStyle section */
+
+/* Begin PBXFileReference section */
+ 089C165DFE840E0CC02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+ 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = "<absolute>"; };
+ 13E42FB307B3F0F600E4EEF1 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = /System/Library/Frameworks/CoreData.framework; sourceTree = "<absolute>"; };
+ 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
+ 29B97319FDCFA39411CA2CEA /* English */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = English; path = English.lproj/MainMenu.nib; sourceTree = "<group>"; };
+ 29B97324FDCFA39411CA2CEA /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = "<absolute>"; };
+ 29B97325FDCFA39411CA2CEA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = "<absolute>"; };
+ 32CA4F630368D1EE00C91783 /* Wiidi_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Wiidi_Prefix.pch; sourceTree = "<group>"; };
+ 8D1107310486CEB800E47090 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 8D1107320486CEB800E47090 /* Wiidi.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Wiidi.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ B7250ABF0B3D572600555F92 /* Miidi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Miidi.h; sourceTree = "<group>"; };
+ B7250AC00B3D572600555F92 /* Miidi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Miidi.m; sourceTree = "<group>"; };
+ B7250B0B0B3D596000555F92 /* CoreMIDI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMIDI.framework; path = /System/Library/Frameworks/CoreMIDI.framework; sourceTree = "<absolute>"; };
+ B7250B0F0B3D596900555F92 /* CoreMIDIServer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMIDIServer.framework; path = /System/Library/Frameworks/CoreMIDIServer.framework; sourceTree = "<absolute>"; };
+ B7436D970B3C6CDF00F36279 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = "<group>"; };
+ B7436D980B3C6CDF00F36279 /* AppController.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = AppController.m; sourceTree = "<group>"; };
+ B7436DA80B3C7FAA00F36279 /* Wiimote.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Wiimote.h; sourceTree = "<group>"; };
+ B7436DA90B3C7FAA00F36279 /* Wiimote.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Wiimote.m; sourceTree = "<group>"; };
+ B7436DAE0B3C84C600F36279 /* IOBluetooth.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOBluetooth.framework; path = /System/Library/Frameworks/IOBluetooth.framework; sourceTree = "<absolute>"; };
+ B75322330B40982C005F3DE8 /* WiiGestures.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WiiGestures.h; sourceTree = "<group>"; };
+ B75322340B40982C005F3DE8 /* WiiGestures.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WiiGestures.m; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 8D11072E0486CEB800E47090 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */,
+ B7436DAF0B3C84C600F36279 /* IOBluetooth.framework in Frameworks */,
+ B7250B0C0B3D596000555F92 /* CoreMIDI.framework in Frameworks */,
+ B7250B100B3D596900555F92 /* CoreMIDIServer.framework in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 080E96DDFE201D6D7F000001 /* Classes */ = {
+ isa = PBXGroup;
+ children = (
+ B72023F80B4178580036D182 /* Controllers */,
+ B72023F90B4178600036D182 /* Models */,
+ );
+ name = Classes;
+ sourceTree = "<group>";
+ };
+ 1058C7A0FEA54F0111CA2CBB /* Linked Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ B7250B0F0B3D596900555F92 /* CoreMIDIServer.framework */,
+ B7250B0B0B3D596000555F92 /* CoreMIDI.framework */,
+ B7436DAE0B3C84C600F36279 /* IOBluetooth.framework */,
+ 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */,
+ );
+ name = "Linked Frameworks";
+ sourceTree = "<group>";
+ };
+ 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 29B97324FDCFA39411CA2CEA /* AppKit.framework */,
+ 13E42FB307B3F0F600E4EEF1 /* CoreData.framework */,
+ 29B97325FDCFA39411CA2CEA /* Foundation.framework */,
+ );
+ name = "Other Frameworks";
+ sourceTree = "<group>";
+ };
+ 19C28FACFE9D520D11CA2CBB /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 8D1107320486CEB800E47090 /* Wiidi.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 29B97314FDCFA39411CA2CEA /* Wiidi */ = {
+ isa = PBXGroup;
+ children = (
+ 080E96DDFE201D6D7F000001 /* Classes */,
+ B72023F70B4178360036D182 /* Headers */,
+ 29B97315FDCFA39411CA2CEA /* Other Sources */,
+ 29B97317FDCFA39411CA2CEA /* Resources */,
+ 29B97323FDCFA39411CA2CEA /* Frameworks */,
+ 19C28FACFE9D520D11CA2CBB /* Products */,
+ );
+ name = Wiidi;
+ sourceTree = "<group>";
+ };
+ 29B97315FDCFA39411CA2CEA /* Other Sources */ = {
+ isa = PBXGroup;
+ children = (
+ 32CA4F630368D1EE00C91783 /* Wiidi_Prefix.pch */,
+ 29B97316FDCFA39411CA2CEA /* main.m */,
+ );
+ name = "Other Sources";
+ sourceTree = "<group>";
+ };
+ 29B97317FDCFA39411CA2CEA /* Resources */ = {
+ isa = PBXGroup;
+ children = (
+ 8D1107310486CEB800E47090 /* Info.plist */,
+ 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */,
+ 29B97318FDCFA39411CA2CEA /* MainMenu.nib */,
+ );
+ name = Resources;
+ sourceTree = "<group>";
+ };
+ 29B97323FDCFA39411CA2CEA /* Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 1058C7A0FEA54F0111CA2CBB /* Linked Frameworks */,
+ 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */,
+ );
+ name = Frameworks;
+ sourceTree = "<group>";
+ };
+ B72023F70B4178360036D182 /* Headers */ = {
+ isa = PBXGroup;
+ children = (
+ B7436D970B3C6CDF00F36279 /* AppController.h */,
+ B7250ABF0B3D572600555F92 /* Miidi.h */,
+ B7436DA80B3C7FAA00F36279 /* Wiimote.h */,
+ B75322330B40982C005F3DE8 /* WiiGestures.h */,
+ );
+ name = Headers;
+ sourceTree = "<group>";
+ };
+ B72023F80B4178580036D182 /* Controllers */ = {
+ isa = PBXGroup;
+ children = (
+ B7436D980B3C6CDF00F36279 /* AppController.m */,
+ );
+ name = Controllers;
+ sourceTree = "<group>";
+ };
+ B72023F90B4178600036D182 /* Models */ = {
+ isa = PBXGroup;
+ children = (
+ B7250AC00B3D572600555F92 /* Miidi.m */,
+ B7436DA90B3C7FAA00F36279 /* Wiimote.m */,
+ B75322340B40982C005F3DE8 /* WiiGestures.m */,
+ );
+ name = Models;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 8D1107260486CEB800E47090 /* Wiidi */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = C01FCF4A08A954540054247B /* Build configuration list for PBXNativeTarget "Wiidi" */;
+ buildPhases = (
+ 8D1107290486CEB800E47090 /* Resources */,
+ 8D11072C0486CEB800E47090 /* Sources */,
+ 8D11072E0486CEB800E47090 /* Frameworks */,
+ );
+ buildRules = (
+ );
+ buildSettings = {
+ };
+ dependencies = (
+ );
+ name = Wiidi;
+ productInstallPath = "$(HOME)/Applications";
+ productName = Wiidi;
+ productReference = 8D1107320486CEB800E47090 /* Wiidi.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 29B97313FDCFA39411CA2CEA /* Project object */ = {
+ isa = PBXProject;
+ buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Wiidi" */;
+ buildSettings = {
+ };
+ buildStyles = (
+ 4A9504CCFFE6A4B311CA0CBA /* Debug */,
+ 4A9504CDFFE6A4B311CA0CBA /* Release */,
+ );
+ hasScannedForEncodings = 1;
+ mainGroup = 29B97314FDCFA39411CA2CEA /* Wiidi */;
+ projectDirPath = "";
+ targets = (
+ 8D1107260486CEB800E47090 /* Wiidi */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ 8D1107290486CEB800E47090 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 8D11072A0486CEB800E47090 /* MainMenu.nib in Resources */,
+ 8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 8D11072C0486CEB800E47090 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 8D11072D0486CEB800E47090 /* main.m in Sources */,
+ B7436D990B3C6CDF00F36279 /* AppController.m in Sources */,
+ B7436DAA0B3C7FAA00F36279 /* Wiimote.m in Sources */,
+ B7250AC10B3D572600555F92 /* Miidi.m in Sources */,
+ B75322350B40982C005F3DE8 /* WiiGestures.m in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXVariantGroup section */
+ 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 089C165DFE840E0CC02AAC07 /* English */,
+ );
+ name = InfoPlist.strings;
+ sourceTree = "<group>";
+ };
+ 29B97318FDCFA39411CA2CEA /* MainMenu.nib */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 29B97319FDCFA39411CA2CEA /* English */,
+ );
+ name = MainMenu.nib;
+ sourceTree = "<group>";
+ };
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+ C01FCF4B08A954540054247B /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ COPY_PHASE_STRIP = NO;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_ENABLE_FIX_AND_CONTINUE = YES;
+ GCC_MODEL_TUNING = G5;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ INFOPLIST_FILE = Info.plist;
+ INSTALL_PATH = "$(HOME)/Applications";
+ PRODUCT_NAME = Wiidi;
+ WRAPPER_EXTENSION = app;
+ ZERO_LINK = YES;
+ };
+ name = Debug;
+ };
+ C01FCF4C08A954540054247B /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ARCHS = (
+ ppc,
+ i386,
+ );
+ GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
+ GCC_MODEL_TUNING = G5;
+ INFOPLIST_FILE = Info.plist;
+ INSTALL_PATH = "$(HOME)/Applications";
+ PRODUCT_NAME = Wiidi;
+ WRAPPER_EXTENSION = app;
+ };
+ name = Release;
+ };
+ C01FCF4F08A954540054247B /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ GCC_PREPROCESSOR_DEFINITIONS = DEBUG;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ PREBINDING = NO;
+ SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
+ };
+ name = Debug;
+ };
+ C01FCF5008A954540054247B /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ GCC_PREPROCESSOR_DEFINITIONS = DEBUG;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ PREBINDING = NO;
+ SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ C01FCF4A08A954540054247B /* Build configuration list for PBXNativeTarget "Wiidi" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ C01FCF4B08A954540054247B /* Debug */,
+ C01FCF4C08A954540054247B /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ C01FCF4E08A954540054247B /* Build configuration list for PBXProject "Wiidi" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ C01FCF4F08A954540054247B /* Debug */,
+ C01FCF5008A954540054247B /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = 29B97313FDCFA39411CA2CEA /* Project object */;
+}
diff --git a/Wiidi_Prefix.pch b/Wiidi_Prefix.pch
new file mode 100644
index 0000000..ef65b23
--- /dev/null
+++ b/Wiidi_Prefix.pch
@@ -0,0 +1,7 @@
+//
+// Prefix header for all source files of the 'Wiidi' target in the 'Wiidi' project
+//
+
+#ifdef __OBJC__
+ #import <Cocoa/Cocoa.h>
+#endif
diff --git a/Wiimote.h b/Wiimote.h
new file mode 100644
index 0000000..b271619
--- /dev/null
+++ b/Wiimote.h
@@ -0,0 +1,173 @@
+//
+// Wiimote.h
+// Wiidi
+//
+// Created by Jinx on 22/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import <Cocoa/Cocoa.h>
+#import <IOBluetooth/objc/IOBluetoothDeviceInquiry.h>
+#import <IOBluetooth/objc/IOBluetoothL2CAPChannel.h>
+#pragma pack(0)
+
+@protocol WiimoteDelegate;
+
+enum { X, Y, Z, Gx, Gy, Gz, Gnx, Gny, Gnz } Directions;
+
+typedef enum {
+ kLEDAndFeedback = 0x11,
+ kReportType = 0x12,
+ kIRSensorEnable = 0x13,
+ kSpeakerEnable = 0x14,
+ kControllerStatus = 0x15,
+ kWriteData = 0x16,
+ kReadData = 0x17,
+ kSpeakerData = 0x18,
+ kMuteSpeaker = 0x19,
+ kIRSensorEnable2 = 0x1A
+} WiimoteCommand;
+
+typedef enum {
+ kInitializeReport = 0x00,
+ kExpansionPortReport = 0x20,
+ kReadDataReport = 0x21,
+ kWriteDataReport = 0x22,
+ kButtonOnlyReport = 0x30,
+ kFullReport = 0x37
+} WiimoteReport;
+
+typedef enum {
+ kNunchuckReading = 0x1,
+ kWiimoteCalibrationReading = 0x2,
+} WiimoteReadings;
+
+enum {
+ kZeroPointX = 0x00,
+ kZeroPointY = 0x01,
+ kZeroPointZ = 0x02,
+ kGravPointX = 0x04,
+ kGravPointY = 0x05,
+ kGravPointZ = 0x06
+} WiimoteCalibrationData;
+
+typedef enum {
+ kWiimoteTwoButton = 0x0001,
+ kWiimoteOneButton = 0x0002,
+ kWiimoteBButton = 0x0004,
+ kWiimoteAButton = 0x0008,
+ kWiimoteMinusButton = 0x0010,
+ kWiimoteHomeButton = 0x0080,
+ kWiimoteLeftButton = 0x0100,
+ kWiimoteRightButton = 0x0200,
+ kWiimoteDownButton = 0x0400,
+ kWiimoteUpButton = 0x0800,
+ kWiimotePlusButton = 0x1000,
+} WiimoteButtonType;
+
+const UInt16 WiimoteButtons[] = {
+ kWiimoteTwoButton,
+ kWiimoteOneButton,
+ kWiimoteBButton,
+ kWiimoteAButton,
+ kWiimoteMinusButton,
+ kWiimoteHomeButton,
+ kWiimoteLeftButton,
+ kWiimoteRightButton,
+ kWiimoteDownButton,
+ kWiimoteUpButton,
+ kWiimotePlusButton
+};
+
+typedef enum {
+ kNunchuckCButton = 0x01,
+ kNunchuckZButton = 0x02
+} NunchuckButtonType;
+
+const UInt8 NunchuckButtons[] = {
+ kNunchuckCButton,
+ kNunchuckZButton
+};
+
+typedef struct {
+ UInt32 address;
+ UInt16 length;
+} WiimoteReadAddress;
+
+typedef struct {
+ UInt8 buttonData;
+ UInt8 rawJoypad[2];
+ UInt8 rawForce[3];
+ UInt8 calibration[9];
+ UInt8 joypadCalibration[6];
+
+ double force[3];
+ double joypad[2];
+ double magnitude;
+} NunchuckData;
+
+typedef struct {
+ UInt16 buttonData;
+ UInt8 rawForce[3];
+ UInt8 calibration[9];
+
+ double force[3];
+ double magnitude;
+} WiimoteData;
+
+#define kWiimoteDeviceName @"Nintendo RVL-CNT-01"
+#define kBluetoothWrite 0x52
+#define kNunchukDecryptionValue 0x17
+
+@interface Wiimote : NSObject {
+ IOBluetoothDevice *device;
+ IOBluetoothDeviceInquiry *inquiry;
+ IOBluetoothL2CAPChannel *inChannel;
+ IOBluetoothL2CAPChannel *outChannel;
+
+ id delegate;
+ bool nunchuckAvailable;
+ UInt8 ledValues;
+ UInt8 readerIdentifier;
+ BOOL initialized;
+
+ NunchuckData nunchuckData;
+ NunchuckData lastNunchuckData;
+ WiimoteData wiimoteData;
+ WiimoteData lastWiimoteData;
+}
+- (id) initWithDelegate:(id)del;
+- (id) delegate;
+- (void) setDelegate:(id)newDelegate;
+- (void) informDelegate;
+
+- (void) connectDevice:(NSTimer *)timer;
+- (bool) isConnected;
+- (bool) nunchuckAvailable;
+
+- (void) setLED:(UInt8)number enabled:(BOOL)onOrOff;
+- (void) toggleLED:(UInt8)number;
+- (bool) isLEDenabled:(UInt8)number;
+- (void) disableAllLEDs;
+- (void) enableAllLEDs;
+
+- (void) enableNunchuck;
+
+- (bool) initializeDevice:(IOBluetoothDevice *)newDevice;
+- (void) stopDevice;
+
+- (void) setLED:(UInt8)newLEDValues;
+- (void) sendLEDValues;
+
+- (void) registerForReport:(WiimoteReport)type;
+- (void) sendCommand:(WiimoteCommand)command withData:(void *)data length:(UInt16)length;
+- (void) readDataFromAddress:(UInt32)address length:(UInt16)length identifier:(UInt8)identifier;
+
+- (void) calibrateDevices;
+- (void) transformRawDevicePositions;
+@end
+
+@protocol WiimoteDelegate
+- (void) nunchuckData:(NunchuckData *)data lastData:(NunchuckData *)lastData;
+- (void) wiimoteData: (WiimoteData *)data lastData: (WiimoteData *)lastData;
+@end
\ No newline at end of file
diff --git a/Wiimote.m b/Wiimote.m
new file mode 100644
index 0000000..dd005fb
--- /dev/null
+++ b/Wiimote.m
@@ -0,0 +1,563 @@
+//
+// Wiimote.m
+// Wiidi
+//
+// Created by Jinx on 22/12/06.
+// Copyright 2006 __MyCompanyName__. All rights reserved.
+//
+
+#import "Wiimote.h"
+
+
+@implementation Wiimote
+
+- (id) initWithDelegate:(id)del
+{
+ if ([self init])
+ {
+ [self setDelegate:del];
+ }
+ return self;
+}
+
+- (id) init
+{
+ if ([super init])
+ {
+ device = nil;
+ delegate = nil;
+ inquiry = nil;
+ inChannel = nil;
+ outChannel = nil;
+ initialized = NO;
+ nunchuckAvailable = NO;
+ ledValues = 0;
+ memset(&nunchuckData, 0, sizeof(NunchuckData));
+ memset(&wiimoteData, 0, sizeof(WiimoteData));
+ memset(&lastNunchuckData, 0, sizeof(NunchuckData));
+ memset(&lastWiimoteData, 0, sizeof(WiimoteData));
+ readerIdentifier = 0;
+
+ [self calibrateDevices];
+ }
+ return self;
+}
+
+- (void) dealloc
+{
+ if ([self isConnected]) [self stopDevice];
+ if (inquiry) [inquiry stop];
+ [delegate release];
+ [super dealloc];
+}
+
+- (void) calibrateDevices
+{
+ // Manually calibrate the remote for now (REFACTOR THIS)
+
+ // Wiimote
+ // Default values are:
+ // => 0 force: 82 82 82
+ // => gravity: 9C 9C 9E
+ // - wiili.org
+ wiimoteData.calibration[X] = 135;
+ wiimoteData.calibration[Y] = 136;
+ wiimoteData.calibration[Z] = 132;
+ wiimoteData.calibration[Gx] = 164;
+ wiimoteData.calibration[Gy] = 164;
+ wiimoteData.calibration[Gz] = 160;
+ wiimoteData.calibration[Gnx] = 108;
+ wiimoteData.calibration[Gny] = 108;
+ wiimoteData.calibration[Gnz] = 105;
+
+ // Nunchuck
+ // Default values are:
+ // => 0 force: 7D 7A 7E
+ // => gravity: B0 AF B1
+ // - wiili.org
+ nunchuckData.calibration[X] = 95;
+ nunchuckData.calibration[Y] = 87;
+ nunchuckData.calibration[Z] = 92;
+ nunchuckData.calibration[Gx] = 175;
+ nunchuckData.calibration[Gy] = 191;
+ nunchuckData.calibration[Gz] = 191;
+ nunchuckData.calibration[Gnx] = 8;
+ nunchuckData.calibration[Gny] = 0;
+ nunchuckData.calibration[Gnz] = 0;
+
+ // Calibrate the joypad for nunchuck
+ nunchuckData.joypadCalibration[X] = 103;
+ nunchuckData.joypadCalibration[Y] = 108;
+ nunchuckData.joypadCalibration[Z] = 202;
+ nunchuckData.joypadCalibration[Gx] = 205;
+ nunchuckData.joypadCalibration[Gy] = 5;
+ nunchuckData.joypadCalibration[Gz] = 10;
+}
+
+- (void) transformRawDevicePositions
+{
+ int i;
+ WiimoteData *w = &wiimoteData;
+ NunchuckData *n = &nunchuckData;
+
+ // Fix some of the values
+ // Wiimote X and Y axes is too sensitive at 0-1, treat 1 as 0
+ if (w->rawForce[X] == wiimoteData.calibration[X] + 1) w->rawForce[X] -= 1;
+ if (w->rawForce[Y] == wiimoteData.calibration[Y] + 1) w->rawForce[Y] -= 1;
+
+ for (i = X; i < Z+1; i++)
+ {
+ double comp = (double)(w->rawForce[i] - w->calibration[i]);
+ double grav = (double)(comp >= 0 ? w->calibration[i+3] - w->calibration[i]
+ : w->calibration[i] - w->calibration[i+6]);
+ w->force[i] = comp / grav;
+
+ if (nunchuckAvailable) { // do the nunchuck
+ comp = (double)(n->rawForce[i] - n->calibration[i]);
+ grav = (double)(comp >= 0 ? n->calibration[i+3] - n->calibration[i]
+ : n->calibration[i] - n->calibration[i+6]);
+ n->force[i] = comp / grav;
+
+ // Also do the joypad, but not for Z
+ if (i < Z) {
+ comp = (double)(n->rawJoypad[i] - n->joypadCalibration[i]);
+ grav = (double)(comp >= 0 ? n->joypadCalibration[i+2] - n->joypadCalibration[i]
+ : n->joypadCalibration[i] - n->joypadCalibration[i+4]);
+
+ n->joypad[i] = comp / grav;
+ }
+ }
+ }
+
+ // Magnitudes
+ w->magnitude = sqrt(w->force[X] * w->force[X] + w->force[Y] *
+ w->force[Y] + w->force[Z] * w->force[Z]);
+
+ if (nunchuckAvailable)
+ {
+ n->magnitude = sqrt(n->force[X] * n->force[X] + n->force[Y] *
+ n->force[Y] + n->force[Z] * n->force[Z]);
+ }
+}
+
+- (void) decryptNunchuckData:(Byte *)data
+{
+ int i;
+ for (i = 0; i < 6; i ++)
+ {
+ if (i == 3) // Y-axis has special encoding (why?)
+ {
+ data[i] = (data[i] & 201) + 6 - (data[i] & 6) + 48 - (data[i] & 48) - 100;
+ }
+ else
+ {
+ data[i] = (data[i] & 232) + 7 - (data[i] & 7) + 16 - (data[i] & 16);
+ }
+ }
+
+ // Button data is inverted except for bit 1
+ data[5] = data[5] ^ 0x01;
+}
+
+- (bool) isConnected
+{
+ // Device exists, device is connected and both L2CAP channels are active (in/out)
+ return (device && [device isConnected] && initialized);
+}
+
+- (bool)nunchuckAvailable
+{
+ return nunchuckAvailable;
+}
+
+- (void) connectDevice:(NSTimer *)timer
+{
+ if ([self isConnected] || inquiry) return;
+ inquiry = [[IOBluetoothDeviceInquiry alloc] initWithDelegate:self];
+ [inquiry start];
+
+#ifdef DEBUG
+ NSLog(@"Searching for device...");
+#endif
+}
+
+- (void) deviceInquiryDeviceFound:(IOBluetoothDeviceInquiry*)sender device:(IOBluetoothDevice*)foundDevice
+{
+ if ([[foundDevice getName] isEqualToString:kWiimoteDeviceName])
+ {
+#ifdef DEBUG
+ NSLog(@"Found Wii device, initializing...");
+#endif
+
+ // Found device, retain it in memory and end the search
+ [self initializeDevice:foundDevice];
+ [sender stop];
+ }
+}
+
+- (void) deviceInquiryComplete:(IOBluetoothDeviceInquiry*)sender error:(IOReturn)error aborted:(BOOL)aborted
+{
+#ifdef DEBUG
+ NSLog(@"Device inquiry completed.");
+#endif
+
+ [inquiry release];
+ inquiry = nil;
+}
+
+- (void) l2capChannelData:(IOBluetoothL2CAPChannel*)l2capChannel data:(void *)packet length:(size_t)packetLength
+{
+ Byte *packetData = (Byte *)packet;
+ Byte reportType = packetData[1];
+ Byte *data = (Byte *)(packet + 2);
+ int length = packetLength - 2;
+ int i; // use this counter later
+
+ switch (reportType)
+ {
+ case kExpansionPortReport:
+ {
+ if (data[2] & 2) // 0x02 bit is set when nunchuck connects
+ [self enableNunchuck];
+ else
+ nunchuckAvailable = NO;
+
+ [self registerForReport:kFullReport]; // Register for full report
+
+ break;
+ }
+ case kReadDataReport:
+ {
+ if (readerIdentifier == kNunchuckReading)
+ {
+#ifdef DEBUG
+ NSLog(@"Received nunchuck reading");
+#endif
+ if (data[2] == 0xF0) // Nunchuck is available
+ [self enableNunchuck];
+ else
+ nunchuckAvailable = NO;
+ }
+ if (readerIdentifier == kWiimoteCalibrationReading) // NOT USED!
+ {
+ // Get calibration data
+ // Data is segmented on the controller as:
+ // X Y Z | Gx Gy Gz, "|" being an empty byte
+ for (i = 0; i < 3; i++) wiimoteData.calibration[i] = data[i];
+ for (i = 4; i < 7; i++) wiimoteData.calibration[i-1] = data[i];
+
+#ifdef DEBUG
+ NSLog(@"Got calibration data: 0x=%d 0y=%d 0z=%d / Gx=%d Gy=%d Gz=%d",
+ wiimoteData.calibration[X], wiimoteData.calibration[Y], wiimoteData.calibration[Z],
+ wiimoteData.calibration[Gx], wiimoteData.calibration[Gy], wiimoteData.calibration[Gz]);
+#endif
+ }
+ break;
+ }
+ case kFullReport:
+ {
+ if (nunchuckAvailable) // Grab nunchuck info
+ {
+ // Decrypt nunchuck data
+ [self decryptNunchuckData:(data+15)];
+
+ // Set values
+ for (i = 15; i < 17; i++) nunchuckData.rawJoypad[i-15] = data[i];
+ for (i = 17; i < 20; i++) nunchuckData.rawForce[i-17] = data[i];
+ nunchuckData.buttonData = data[20];
+ }
+
+ // Do wiimote stuff
+ wiimoteData.buttonData = ((UInt16)data[0] << 8) + data[1];
+ for (i = 2; i < 5; i++) wiimoteData.rawForce[i-2] = data[i];
+
+ [self transformRawDevicePositions];
+ [self informDelegate];
+
+ // Save last values
+ memcpy(&lastNunchuckData, &nunchuckData, sizeof(NunchuckData));
+ memcpy(&lastWiimoteData, &wiimoteData, sizeof(WiimoteData));
+
+ break;
+ }
+ }
+
+#ifdef DEBUG
+ if (reportType != kFullReport)
+ {
+ int i;
+ printf("READ DATA: (Report type = 0x%02X) ", reportType);
+ for (i = 0; i < length; i++) {
+ printf("0x%02X ", data[i]);
+ }
+ printf("\n");
+ }
+#endif
+
+}
+
+- (void)l2capChannelOpenComplete:(IOBluetoothL2CAPChannel*)l2capChannel status:(IOReturn)error
+{
+#ifdef DEBUG
+ NSLog(@"Wiimote delegate triggered: l2capChannelOpenComplete");
+#endif
+ if (!initialized)
+ {
+#ifdef DEBUG
+ NSLog(@"Initializing the Wiimote...");
+#endif
+ initialized = YES;
+
+ // Calibrate the remote
+ //[self readDataFromAddress:0x16 length:9 identifier:kWiimoteCalibrationReading];
+
+ // Get the nunchuck read value
+ [self readDataFromAddress:0x04A40000 length:0x10 identifier:kNunchuckReading];
+
+ [self registerForReport:kFullReport]; // Register for the full report
+ [self setLED:1]; // Turn on only led 1
+ }
+}
+
+- (void)l2capChannelClosed:(IOBluetoothL2CAPChannel*)l2capChannel
+{
+#ifdef DEBUG
+ NSLog(@"Wiimote delegate triggered: l2capChannelClosed");
+#endif
+ [self stopDevice];
+ [self connectDevice:nil];
+}
+
+- (void)l2capChannelReconfigured:(IOBluetoothL2CAPChannel*)l2capChannel
+{
+#ifdef DEBUG
+ NSLog(@"Wiimote delegate triggered: l2capChannelReconfigured");
+#endif
+}
+
+- (void)l2capChannelWriteComplete:(IOBluetoothL2CAPChannel*)l2capChannel refcon:(void*)refcon status:(IOReturn)error
+{
+#ifdef DEBUG
+ NSLog(@"Wiimote delegate triggered: l2capChannelWriteComplete");
+#endif
+}
+
+- (void)l2capChannelQueueSpaceAvailable:(IOBluetoothL2CAPChannel*)l2capChannel
+{
+#ifdef DEBUG
+ NSLog(@"Wiimote delegate triggered: l2capChannelQueueSpaceAvailable");
+#endif
+}
+
+- (void) sendLEDValues
+{
+ Byte msg[] = { ledValues << 4 };
+ [self sendCommand:kLEDAndFeedback withData:msg length:sizeof(msg)];
+}
+
+- (void) setLED:(UInt8)number enabled:(BOOL)onOrOff
+{
+ UInt8 value = (UInt8)(1 << number);
+ [self setLED:(ledValues + (onOrOff ? value : -value))];
+}
+
+- (void) setLED:(UInt8)newLEDValues
+{
+ ledValues = newLEDValues;
+ [self sendLEDValues];
+}
+
+- (void) toggleLED:(UInt8)number
+{
+ [self setLED:(ledValues ^ (UInt8)pow(2, number))];
+}
+
+- (void) disableAllLEDs
+{
+ [self setLED:0x00];
+}
+
+- (void) enableAllLEDs
+{
+ [self setLED:0xF0];
+}
+
+- (bool) isLEDenabled:(UInt8)number
+{
+ return (ledValues & (UInt8)pow(2, number));
+}
+
+- (void) sendCommand:(WiimoteCommand)command withData:(void *)data length:(UInt16)length
+{
+ if (outChannel == nil) return;
+ IOReturn retValue;
+
+ // Build the message
+ Byte *msg = (Byte *)malloc(length + 2);
+ memset(msg, 0, length + 2);
+ msg[0] = kBluetoothWrite;
+ msg[1] = command;
+ memcpy(msg + 2, data, length);
+
+ // Send the message
+ retValue = [outChannel writeSync:msg length:(length + 2)];
+
+#ifdef DEBUG
+ if (retValue != kIOReturnSuccess) NSLog(@"Message failed to send!");
+ int i;
+ printf("WROTE DATA: ");
+ for (i = 0; i < length+2; i++) {
+ printf("%02X ", msg[i]);
+ }
+ printf("\n");
+#endif
+
+ if (retValue != kIOReturnSuccess)
+ {
+ // Something is wrong with the connection, re-establish it
+ [self stopDevice];
+ [self connectDevice:nil];
+ }
+
+ free(msg); // free the data
+}
+
+/**
+ * Not thread safe!
+ */
+- (void) readDataFromAddress:(UInt32)address length:(UInt16)length identifier:(UInt8)identifier
+{
+ readerIdentifier = identifier;
+ WiimoteReadAddress addr;
+ addr.address = htonl(address);
+ addr.length = htons(length);
+ [self sendCommand:kReadData withData:(void *)&addr length:6];
+}
+
+- (void) enableNunchuck
+{
+#ifdef DEBUG
+ NSLog(@"Enabling nunchuck...");
+#endif
+
+ Byte msg[] = {0x04, 0xA4, 0x00, 0x40, 0x09, 0x01, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ [self sendCommand:kWriteData withData:msg length:21];
+ nunchuckAvailable = YES;
+}
+
+- (void) registerForReport:(WiimoteReport)type
+{
+#ifdef DEBUG
+ NSLog(@"Registering for full motion report...");
+#endif
+
+ Byte msg[] = {0x00, type};
+ [self sendCommand:kReportType withData:msg length:2];
+}
+
+- (bool) initializeDevice:(IOBluetoothDevice*)foundDevice
+{
+ [self stopDevice];
+
+ if ([foundDevice openConnection] != kIOReturnSuccess)
+ {
+ NSLog(@"could not open the connection...");
+ return NO;
+ }
+
+ if ([foundDevice performSDPQuery:nil] != kIOReturnSuccess)
+ {
+ NSLog(@"could not perform SDP Query...");
+ return NO;
+ }
+
+ if ([foundDevice openL2CAPChannelSync:&outChannel withPSM:17 delegate:self] != kIOReturnSuccess)
+ {
+ NSLog(@"could not open L2CAP channel cchan");
+ outChannel = nil;
+ [foundDevice closeConnection];
+ return NO;
+ }
+
+ if ([foundDevice openL2CAPChannelSync:&inChannel withPSM:19 delegate:self] != kIOReturnSuccess){
+ NSLog(@"could not open L2CAP channel ichan");
+ inChannel = nil;
+ [outChannel closeChannel];
+ [foundDevice closeConnection];
+ return NO;
+ }
+
+ // Retain the device in memory
+ device = [foundDevice retain];
+ [outChannel retain];
+ [inChannel retain];
+
+ return YES;
+}
+
+- (void) stopDevice
+{
+ if (outChannel)
+ {
+ [outChannel closeChannel];
+ [outChannel release];
+ outChannel = nil;
+ }
+
+ if (inChannel)
+ {
+ [inChannel closeChannel];
+ [inChannel release];
+ inChannel = nil;
+ }
+
+ if (device)
+ {
+ [device closeConnection];;
+ [device release];
+ device = nil;
+ }
+
+ initialized = NO;
+ nunchuckAvailable = NO;
+}
+
+- (void) informDelegate
+{
+ if (delegate == nil) return;
+
+ [delegate wiimoteData:&wiimoteData lastData:&lastWiimoteData];
+
+ if (nunchuckAvailable)
+ {
+ [delegate nunchuckData:&nunchuckData lastData:&lastNunchuckData];
+ }
+
+// UInt8 *p = nunchuckData.rawForce;
+// NSLog(@"RAW NUNCHUCK x = %d \t y = %d \t z = %d", p[X], p[Y], p[Z]);
+if (nunchuckData.magnitude >= 1) {
+ //double *p = nunchuckData.force;
+ //NSLog(@"NUNCHUCK x = %2.2f \t y = %2.2f \t z = %2.2f \t mag = %2.2f", p[X], p[Y], p[Z], nunchuckData.magnitude);
+ }
+}
+
+- (id) delegate
+{
+ return delegate;
+}
+
+- (void) setDelegate:(id)newDelegate
+{
+ if ([newDelegate conformsToProtocol:@protocol(WiimoteDelegate)])
+ {
+ [delegate release];
+ delegate = [newDelegate retain];
+ }
+ else
+ [NSException raise:@"InvalidWiimoteDelegateException"
+ format:@"The delegate object does not conform to the WiimoteDelegate protocol"];
+}
+
+@end
diff --git a/main.m b/main.m
new file mode 100644
index 0000000..c19a69f
--- /dev/null
+++ b/main.m
@@ -0,0 +1,14 @@
+//
+// main.m
+// Wiidi
+//
+// Created by Jinx on 22/12/06.
+// Copyright __MyCompanyName__ 2006. All rights reserved.
+//
+
+#import <Cocoa/Cocoa.h>
+
+int main(int argc, char *argv[])
+{
+ return NSApplicationMain(argc, (const char **) argv);
+}
|
dalloliogm/snps-hdf5
|
942ddae6438bc5dd0b101b2ead665f0f34028a7b
|
removed doctest, which didn't belong to Descriptor object
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 30a46b0..8554529 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,121 +1,113 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = Enum('0 1 2 9'.split())
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
-# >>> import random; random.seed(0)
-
-# >>> snp = h5testfile.root.HGDP.snps
-# >>> for i in range(10):
-# >>> snp['id'] = i
-# >>> snp['position'] = random.choice(range(1000))
-# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = StringCol(8)
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
# genotype = EnumCol(genotypes, '9', base='uint8')
genotype = UInt8Col()
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
continent = StringCol(20)
iHS = Float64Col()
class Individual(IsDescription):
"""
"""
id = StringCol(20)
population = StringCol(50) # Here it will be good to have relationships
class haplotypes(IsDescription): # Redundancy!!
snp = StringCol(20)
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
import random
def filldata(h5file):
"""
Fill test data in SNP
"""
table = h5file.root.tests.hgdp.snps
snp = table.row
random.seed(0)
individuals = ('hgdp001', 'hgdp002', 'hgdp003')
for i in range(10):
snp['id'] = "rs000%d" % i
snp['position'] = random.choice(xrange(1000))
snp['chromosome'] = random.choice(xrange(22))
for ind in individuals:
snp['genotypes/individual'] = ind
snp['genotypes/genotype'] = random.choice('0 1 2 9'.split())
- table.flush()
snp.append()
table.flush()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
fcb5d7028ee0306b5a31f64fe628bc93b18de407
|
changed some column types
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 412918a..30a46b0 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,119 +1,121 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = Enum('0 1 2 9'.split())
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
# >>> snp['id'] = i
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
-
"""
-
+
id = StringCol(20)
position = UInt16Col()
- chromosome = UInt8Col()
+ chromosome = StringCol(8)
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
- genotype = EnumCol(genotypes, '9', base='uint8')
+# genotype = EnumCol(genotypes, '9', base='uint8')
+ genotype = UInt8Col()
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
continent = StringCol(20)
iHS = Float64Col()
class Individual(IsDescription):
"""
"""
id = StringCol(20)
population = StringCol(50) # Here it will be good to have relationships
class haplotypes(IsDescription): # Redundancy!!
snp = StringCol(20)
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
import random
def filldata(h5file):
"""
Fill test data in SNP
"""
table = h5file.root.tests.hgdp.snps
snp = table.row
random.seed(0)
individuals = ('hgdp001', 'hgdp002', 'hgdp003')
for i in range(10):
snp['id'] = "rs000%d" % i
snp['position'] = random.choice(xrange(1000))
snp['chromosome'] = random.choice(xrange(22))
for ind in individuals:
snp['genotypes/individual'] = ind
-# snp['genotypes/genotype'] = random.choice((genotypes.0, genotypes.1, genotypes.2, genotypes.9))
- snp['genotypes/genotype'] = random.choice((0, 1, 2, 3))
+ snp['genotypes/genotype'] = random.choice('0 1 2 9'.split())
+ table.flush()
+
+ snp.append()
table.flush()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
2588f20c1d78d5b5a613b598dbc5c6aa5c2c1e22
|
added a makefile
|
diff --git a/src/Makefile b/src/Makefile
new file mode 100644
index 0000000..b79bcf4
--- /dev/null
+++ b/src/Makefile
@@ -0,0 +1,7 @@
+filldata:
+ ipython -i -c 'from schema.schema import *; (h5file, group, genotypes_table) = create_testfile(); filldata(h5file)'
+
+connect:
+ ipython -i -c 'from schema.schema import *; (h5file, group, genotypes_table) = create_testfile()'
+
+
|
dalloliogm/snps-hdf5
|
2807114dbb71a4accbfd8123dacd918329dc0455
|
fixed nested table access and error from Enum
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 250e5a0..412918a 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,116 +1,119 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
+genotypes = Enum('0 1 2 9'.split())
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
# >>> snp['id'] = i
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
- genotype = EnumCol(('1', '2', '0', '9'), '9', base='uint8')
+ genotype = EnumCol(genotypes, '9', base='uint8')
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
continent = StringCol(20)
iHS = Float64Col()
class Individual(IsDescription):
"""
"""
id = StringCol(20)
population = StringCol(50) # Here it will be good to have relationships
class haplotypes(IsDescription): # Redundancy!!
snp = StringCol(20)
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
import random
def filldata(h5file):
"""
Fill test data in SNP
"""
- snp = h5file.root.tests.hgdp.snps.row
+ table = h5file.root.tests.hgdp.snps
+ snp = table.row
random.seed(0)
individuals = ('hgdp001', 'hgdp002', 'hgdp003')
for i in range(10):
snp['id'] = "rs000%d" % i
snp['position'] = random.choice(xrange(1000))
snp['chromosome'] = random.choice(xrange(22))
for ind in individuals:
- snp['genotypes']['individual'] = ind
- snp['genotypes']['genotype'] = random.choice(('0', '1', '2', '9'))
+ snp['genotypes/individual'] = ind
+# snp['genotypes/genotype'] = random.choice((genotypes.0, genotypes.1, genotypes.2, genotypes.9))
+ snp['genotypes/genotype'] = random.choice((0, 1, 2, 3))
table.flush()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
9a2b4452f36798d907ee10ac458265cae5b9c286
|
stub for filldata func
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 8b46de2..250e5a0 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,92 +1,116 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
-# >>> snp['id'] = id
+# >>> snp['id'] = i
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
genotype = EnumCol(('1', '2', '0', '9'), '9', base='uint8')
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
continent = StringCol(20)
iHS = Float64Col()
class Individual(IsDescription):
"""
"""
id = StringCol(20)
population = StringCol(50) # Here it will be good to have relationships
class haplotypes(IsDescription): # Redundancy!!
snp = StringCol(20)
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
+import random
+def filldata(h5file):
+ """
+ Fill test data in SNP
+ """
+ snp = h5file.root.tests.hgdp.snps.row
+
+ random.seed(0)
+
+ individuals = ('hgdp001', 'hgdp002', 'hgdp003')
+
+ for i in range(10):
+ snp['id'] = "rs000%d" % i
+ snp['position'] = random.choice(xrange(1000))
+ snp['chromosome'] = random.choice(xrange(22))
+
+ for ind in individuals:
+ snp['genotypes']['individual'] = ind
+ snp['genotypes']['genotype'] = random.choice(('0', '1', '2', '9'))
+
+ table.flush()
+
+
+
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
b14f547583e1862a6864318a578ef1acffeef247
|
proposal: an Individual table?
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 5325a7e..8b46de2 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,84 +1,92 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
-genotypes = tables.Enum(['0', '1', '2', '9'])
-
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
# >>> snp['id'] = id
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
- genotype = EnumCol(genotypes, '9', base='uint8')
+ genotype = EnumCol(('1', '2', '0', '9'), '9', base='uint8')
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
continent = StringCol(20)
iHS = Float64Col()
+class Individual(IsDescription):
+ """
+ """
+
+ id = StringCol(20)
+ population = StringCol(50) # Here it will be good to have relationships
+
+ class haplotypes(IsDescription): # Redundancy!!
+ snp = StringCol(20)
+ haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
+ haplotype1 = EnumCol(('A', 'C', 'G', 'T', '-'), '-', base='uint8')
-
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
77cc90fd63451f93f86dc217e4052970ae271d49
|
indent fix
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index e0d1ff1..5325a7e 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,84 +1,84 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = tables.Enum(['0', '1', '2', '9'])
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
# >>> snp['id'] = id
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
genotype = EnumCol(genotypes, '9', base='uint8')
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
"""
A nested table containing iHS by continent for the current snp.
"""
- continent = StringCol(20)
+ continent = StringCol(20)
iHS = Float64Col()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
be809a514aec60fb74b97db0aea14de25dc41bac
|
other enhancements to docstrings.. maybe too much descriptive
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index a5a39f4..e0d1ff1 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,81 +1,84 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = tables.Enum(['0', '1', '2', '9'])
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
- >>> import random; random.seed(0)
+# >>> import random; random.seed(0)
# >>> snp = h5testfile.root.HGDP.snps
# >>> for i in range(10):
# >>> snp['id'] = id
# >>> snp['position'] = random.choice(range(1000))
# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
genotype = EnumCol(genotypes, '9', base='uint8')
class stats(IsDescription):
"""
A nested table containing some statistics related to the current snp.
"""
class iHS_by_population(IsDescription):
"""
- iHS by population for the current snp.
+ A nested table containing iHS by population for the current snp.
"""
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
- continent = StringCol(20)
+ """
+ A nested table containing iHS by continent for the current snp.
+ """
+ continent = StringCol(20)
iHS = Float64Col()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
3eb9cc8bd24671ba11d5aabb1c00c312b07bca50
|
improved docstrings in SNP table
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 5015280..a5a39f4 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,77 +1,81 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = tables.Enum(['0', '1', '2', '9'])
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
- import random; random.seed(0)
+ >>> import random; random.seed(0)
- snp = h5testfile.root.HGDP.snps
- for i in range(10):
- snp['id'] = id
- snp['position'] = random.choice(range(1000))
- snp['chromosome'] = random.choice(22)
+# >>> snp = h5testfile.root.HGDP.snps
+# >>> for i in range(10):
+# >>> snp['id'] = id
+# >>> snp['position'] = random.choice(range(1000))
+# >>> snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
- A genotype identified by a snp ID and a individual ID
-
-
+ A nested table containing the genotypes of the current snp.
"""
individual = StringCol(16)
genotype = EnumCol(genotypes, '9', base='uint8')
class stats(IsDescription):
+ """
+ A nested table containing some statistics related to the current snp.
+ """
class iHS_by_population(IsDescription):
+ """
+ iHS by population for the current snp.
+ """
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
continent = StringCol(20)
iHS = Float64Col()
def create_testfile():
"""
Create test file and tables
"""
h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
h5file.createGroup('/', 'tests', 'Tests')
group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
genotypes_table = h5file.createTable(group, 'snps',
SNP, 'Genotypes table')
return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
27ca6eef59f92b9e79fb628e0e8c03936f6a7249
|
fixes to h5file setup
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 06b5aab..5015280 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,76 +1,77 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import *
from numpy import *
import tables
import logging
genotypes = tables.Enum(['0', '1', '2', '9'])
class SNP(IsDescription):
"""
A SNP table, containing many nested tables (genotypes, stats)
import random; random.seed(0)
snp = h5testfile.root.HGDP.snps
for i in range(10):
snp['id'] = id
snp['position'] = random.choice(range(1000))
snp['chromosome'] = random.choice(22)
"""
id = StringCol(20)
position = UInt16Col()
chromosome = UInt8Col()
class genotypes(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
"""
individual = StringCol(16)
genotype = EnumCol(genotypes, '9', base='uint8')
class stats(IsDescription):
class iHS_by_population(IsDescription):
population = StringCol(20)
iHS = Float64Col()
class iHS_by_continent(IsDescription):
continent = StringCol(20)
iHS = Float64Col()
def create_testfile():
"""
Create test file and tables
"""
- h5dfile = tables.openFile('../data/test.h5', mode = 'w',
+ h5file = tables.openFile('../data/test.h5', mode = 'w',
title = 'Testfile')
- group = h5dfile.createGroup('/', 'tests', 'Test table')
+ h5file.createGroup('/', 'tests', 'Tests')
+ group = h5file.createGroup('/tests/', 'hgdp', 'hgdp tests')
- genotypes_table = h5dfile.createTable(group, 'genotypes',
- GenotypeDescriptor, 'Genotypes table')
- return h5dfile, group, genotypes_table
+ genotypes_table = h5file.createTable(group, 'snps',
+ SNP, 'Genotypes table')
+ return h5file, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_testfile()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
|
dalloliogm/snps-hdf5
|
540ddafd5576a1c542b197bb72546876896cd16f
|
always use hdf5, not h5df
|
diff --git a/src/schema/config.py b/src/schema/config.py
index 2cd29aa..c0694d1 100644
--- a/src/schema/config.py
+++ b/src/schema/config.py
@@ -1,21 +1,27 @@
#!/Usr/bin/env python
"""
"""
import tables
from schema import Genotype
-h5df_file_path = '../../test.h5'
+hdf5_file_path = '../../test.h5'
-def create_h5df_file(path = '../../data/test.h5'):
+def create_hdf5_file(path = '../../data/test.h5'):
"""
Create test file and tables
"""
- h5dfile = tables.openFile(path, mode = 'w',
+ hdf5file = tables.openFile(path, mode = 'w',
title = 'Testfile')
- group = h5dfile.createGroup('/', 'tests', 'Test table')
+ group = hdf5file.createGroup('/', 'tests', 'Test table')
- genotypes_table = h5dfile.createTable(group, 'genotypes',
+ genotypes_table = hdf5file.createTable(group, 'genotypes',
Genotype, 'Genotypes table')
- return h5dfile, group, genotypes_table
\ No newline at end of file
+ return hdf5file, group, genotypes_table
+
+def test_file():
+ create_hdf5_file(path = '../../data/test.h5')
+
+def hdf5_file():
+ create_hdf5_file()
\ No newline at end of file
diff --git a/src/scripts/upload_snps_to_h5df.py b/src/scripts/upload_snps_to_h5df.py
index f8c28e7..90ee10b 100644
--- a/src/scripts/upload_snps_to_h5df.py
+++ b/src/scripts/upload_snps_to_h5df.py
@@ -1,80 +1,67 @@
#! /usr/bin/env python
"""
Read the SNP file and upload the data to the h5df file
"""
from schema.config import *
import re
def genotypes_parser(handle, ):
"""
Parse a genotypes file handler.
It returns a Marker object for every line of the file
>>> from schema.debug_database import *
>>> print metadata
MetaData(Engine(sqlite:///:memory:))
>>> from StringIO import StringIO
>>> genotypes_file = StringIO(
... ''' HGDP00001 HGDP00002 HGDP00003 HGDP00004 HGDP00005 HGDP00006 HGDP00007 HGDP00008 HGDP00009 HGDP000010
... rs1112390 AA GG AG AA AA AA AA AA AA AA
... rs1112391 TT TC CC CC CC CC CC CC CC CC
... MitoA11252G AA AA AA AA AA AA AA AA AA AA
... rs11124185 TC TT TT TT TT TT TT TT TT TT
... MitoA13265G AA AA AA AA AA AA AA AA AA AA
... MitoA13264G GG AA AA AA GG AG AA AA AA AA
... MitoA13781G AA AA AA AA AA AA -- AA AA AA
... MitoA14234G AA AA AA AA AA AA AA AA AA AA
... MitoA14583G AA AA AA AA AA AA AA AA AA AA
... MitoA14906G GG GG GG GG GG GG GG GG GG GG
... MitoA15219G AA AA AA GG AA AA AA AA AA AA''')
- >>> snps = genotypes_parser(genotypes_file)
-
- >>> for snp in snps:
- ... print snp.id, snp.genotypes1, snp.genotypes2
- rs1112390 AGAAAAAAAA AGGAAAAAAA
- rs1112391 TTCCCCCCCC TCCCCCCCCC
- MitoA11252G AAAAAAAAAA AAAAAAAAAA
- rs11124185 TTTTTTTTTT CTTTTTTTTT
- MitoA13265G AAAAAAAAAA AAAAAAAAAA
- MitoA13264G GAAAGAAAAA GAAAGGAAAA
- MitoA13781G AAAAAA-AAA AAAAAA-AAA
- MitoA14234G AAAAAAAAAA AAAAAAAAAA
- MitoA14583G AAAAAAAAAA AAAAAAAAAA
- MitoA14906G GGGGGGGGGG GGGGGGGGGG
- MitoA15219G AAAGAAAAAA AAAGAAAAAA
+ >>> for snp in genotypes_parser(genotypes_file):
+ ... print snp
"""
# initialize output var
snps = []
# read the header, containing the Individuals names
# handle.readline() # first line is empty??
header = handle.readline()
if header is None:
raise ValueError('Empty file!!')
# individuals = [Individual(ind_id) for ind_id in header.split()]
# Read snp file line by line.
for line in handle.readlines():
fields = line.split() # TODO: add more rigorous conditions
if fields is None:
break
# Initialize a SNP object
- snp = SNP(id = fields[0])
+ snp = Genotype(id = fields[0])
snps.append(snp)
# read
for n in range(1, len(fields)):
# current_individual = individuals[n-1]
current_genotype = fields[n]
snp.genotypes1 += current_genotype[0]
snp.genotypes2 += current_genotype[1]
return snps
|
dalloliogm/snps-hdf5
|
e9aad86dd2f0571f7e1f95c752d5ed2f7a9bd9dd
|
imported parse_genotype function from old HGDPIO
|
diff --git a/src/schema/config.py b/src/schema/config.py
index edea5d8..2cd29aa 100644
--- a/src/schema/config.py
+++ b/src/schema/config.py
@@ -1,20 +1,21 @@
#!/Usr/bin/env python
"""
"""
import tables
+from schema import Genotype
h5df_file_path = '../../test.h5'
def create_h5df_file(path = '../../data/test.h5'):
"""
Create test file and tables
"""
h5dfile = tables.openFile(path, mode = 'w',
title = 'Testfile')
group = h5dfile.createGroup('/', 'tests', 'Test table')
genotypes_table = h5dfile.createTable(group, 'genotypes',
Genotype, 'Genotypes table')
return h5dfile, group, genotypes_table
\ No newline at end of file
diff --git a/src/scripts/upload_snps_to_h5df.py b/src/scripts/upload_snps_to_h5df.py
index 3e3239d..f8c28e7 100644
--- a/src/scripts/upload_snps_to_h5df.py
+++ b/src/scripts/upload_snps_to_h5df.py
@@ -1,7 +1,80 @@
#! /usr/bin/env python
"""
Read the SNP file and upload the data to the h5df file
"""
-from schema.schema import *
+from schema.config import *
+import re
+
+
+def genotypes_parser(handle, ):
+ """
+ Parse a genotypes file handler.
+
+ It returns a Marker object for every line of the file
+
+ >>> from schema.debug_database import *
+ >>> print metadata
+ MetaData(Engine(sqlite:///:memory:))
+ >>> from StringIO import StringIO
+ >>> genotypes_file = StringIO(
+ ... ''' HGDP00001 HGDP00002 HGDP00003 HGDP00004 HGDP00005 HGDP00006 HGDP00007 HGDP00008 HGDP00009 HGDP000010
+ ... rs1112390 AA GG AG AA AA AA AA AA AA AA
+ ... rs1112391 TT TC CC CC CC CC CC CC CC CC
+ ... MitoA11252G AA AA AA AA AA AA AA AA AA AA
+ ... rs11124185 TC TT TT TT TT TT TT TT TT TT
+ ... MitoA13265G AA AA AA AA AA AA AA AA AA AA
+ ... MitoA13264G GG AA AA AA GG AG AA AA AA AA
+ ... MitoA13781G AA AA AA AA AA AA -- AA AA AA
+ ... MitoA14234G AA AA AA AA AA AA AA AA AA AA
+ ... MitoA14583G AA AA AA AA AA AA AA AA AA AA
+ ... MitoA14906G GG GG GG GG GG GG GG GG GG GG
+ ... MitoA15219G AA AA AA GG AA AA AA AA AA AA''')
+
+ >>> snps = genotypes_parser(genotypes_file)
+
+ >>> for snp in snps:
+ ... print snp.id, snp.genotypes1, snp.genotypes2
+ rs1112390 AGAAAAAAAA AGGAAAAAAA
+ rs1112391 TTCCCCCCCC TCCCCCCCCC
+ MitoA11252G AAAAAAAAAA AAAAAAAAAA
+ rs11124185 TTTTTTTTTT CTTTTTTTTT
+ MitoA13265G AAAAAAAAAA AAAAAAAAAA
+ MitoA13264G GAAAGAAAAA GAAAGGAAAA
+ MitoA13781G AAAAAA-AAA AAAAAA-AAA
+ MitoA14234G AAAAAAAAAA AAAAAAAAAA
+ MitoA14583G AAAAAAAAAA AAAAAAAAAA
+ MitoA14906G GGGGGGGGGG GGGGGGGGGG
+ MitoA15219G AAAGAAAAAA AAAGAAAAAA
+ """
+ # initialize output var
+ snps = []
+
+ # read the header, containing the Individuals names
+# handle.readline() # first line is empty??
+ header = handle.readline()
+ if header is None:
+ raise ValueError('Empty file!!')
+# individuals = [Individual(ind_id) for ind_id in header.split()]
+
+ # Read snp file line by line.
+ for line in handle.readlines():
+ fields = line.split() # TODO: add more rigorous conditions
+ if fields is None:
+ break
+
+ # Initialize a SNP object
+ snp = SNP(id = fields[0])
+ snps.append(snp)
+
+ # read
+ for n in range(1, len(fields)):
+# current_individual = individuals[n-1]
+ current_genotype = fields[n]
+
+ snp.genotypes1 += current_genotype[0]
+ snp.genotypes2 += current_genotype[1]
+
+ return snps
+
|
dalloliogm/snps-hdf5
|
b937547e0875d414bedaaa29cafbf4254d2e635a
|
added a config file
|
diff --git a/src/schema/config.py b/src/schema/config.py
new file mode 100644
index 0000000..edea5d8
--- /dev/null
+++ b/src/schema/config.py
@@ -0,0 +1,20 @@
+#!/Usr/bin/env python
+"""
+
+"""
+
+import tables
+
+h5df_file_path = '../../test.h5'
+
+def create_h5df_file(path = '../../data/test.h5'):
+ """
+ Create test file and tables
+ """
+ h5dfile = tables.openFile(path, mode = 'w',
+ title = 'Testfile')
+ group = h5dfile.createGroup('/', 'tests', 'Test table')
+
+ genotypes_table = h5dfile.createTable(group, 'genotypes',
+ Genotype, 'Genotypes table')
+ return h5dfile, group, genotypes_table
\ No newline at end of file
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 530fa90..8df6bc7 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,66 +1,66 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import IsDescription
from tables import Int32Col, StringCol
import tables
import logging
class Genotype(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
>>> geno1 = Genotype('hr1333', 'HGDP0001', '01')
"""
snp = StringCol(10)
individual_id = StringCol(16)
genotype = StringCol(2)
population = StringCol(30)
def __init__(self, snp, individual, genotype):
row = self.row
row['snp'] = str(snp)
row['individual'] = individual
genotype = _check_valid_genotype
row['genotype'] = genotype
row.append()
def _check_valid_genotype(genotype):
"""
check if genotype is a valid genotype
(a string of 2 characters)
"""
if not isinstance(genotype, str):
genotype = str(genotype)
if len(genotype) != 2:
raise TypeException('genotype should be two chars long')
return genotype
def create_debug_file():
"""
Create test file and tables
"""
h5dfile = tables.openFile('../../data/test.h5', mode = 'w',
title = 'Testfile')
group = h5dfile.createGroup('/', 'tests', 'Test table')
genotypes_table = h5dfile.createTable(group, 'genotypes',
Genotype, 'Genotypes table')
- return genotypes_table
+ return h5dfile, group, genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_debug_file()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
\ No newline at end of file
diff --git a/src/scripts/__init__.py b/src/scripts/__init__.py
new file mode 100644
index 0000000..5a4829a
--- /dev/null
+++ b/src/scripts/__init__.py
@@ -0,0 +1,2 @@
+"""
+"""
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
363f28b3a4762c8cd71506ae7e528847903bf549
|
added a script to upload the snps to the h5df file
|
diff --git a/src/schema/__init__.py b/src/schema/__init__.py
index e69de29..ff3fa9a 100644
--- a/src/schema/__init__.py
+++ b/src/schema/__init__.py
@@ -0,0 +1,3 @@
+"""
+"""
+__all__ = ['schema', ]
\ No newline at end of file
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 4f6abc1..530fa90 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,65 +1,66 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import IsDescription
from tables import Int32Col, StringCol
import tables
import logging
class Genotype(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
>>> geno1 = Genotype('hr1333', 'HGDP0001', '01')
"""
snp = StringCol(10)
individual_id = StringCol(16)
genotype = StringCol(2)
+ population = StringCol(30)
def __init__(self, snp, individual, genotype):
row = self.row
row['snp'] = str(snp)
row['individual'] = individual
genotype = _check_valid_genotype
row['genotype'] = genotype
row.append()
def _check_valid_genotype(genotype):
"""
check if genotype is a valid genotype
(a string of 2 characters)
"""
if not isinstance(genotype, str):
genotype = str(genotype)
if len(genotype) != 2:
raise TypeException('genotype should be two chars long')
return genotype
def create_debug_file():
"""
Create test file and tables
"""
h5dfile = tables.openFile('../../data/test.h5', mode = 'w',
title = 'Testfile')
group = h5dfile.createGroup('/', 'tests', 'Test table')
genotypes_table = h5dfile.createTable(group, 'genotypes',
Genotype, 'Genotypes table')
return genotypes_table
def test_all():
"""
test the current module
"""
logging.basicConfig(level=logging.DEBUG)
create_debug_file()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
\ No newline at end of file
diff --git a/src/scripts/upload_snps_to_h5df.py b/src/scripts/upload_snps_to_h5df.py
new file mode 100644
index 0000000..3e3239d
--- /dev/null
+++ b/src/scripts/upload_snps_to_h5df.py
@@ -0,0 +1,7 @@
+#! /usr/bin/env python
+"""
+Read the SNP file and upload the data to the h5df file
+"""
+
+from schema.schema import *
+
|
dalloliogm/snps-hdf5
|
d9babf58ab029887187312966ff69bb329b2a39e
|
added a _check_valid_genotype method
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 18660b8..4f6abc1 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,51 +1,65 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import IsDescription
from tables import Int32Col, StringCol
import tables
import logging
class Genotype(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
>>> geno1 = Genotype('hr1333', 'HGDP0001', '01')
"""
snp = StringCol(10)
individual_id = StringCol(16)
genotype = StringCol(2)
def __init__(self, snp, individual, genotype):
row = self.row
row['snp'] = str(snp)
row['individual'] = individual
+ genotype = _check_valid_genotype
row['genotype'] = genotype
row.append()
-
+
+def _check_valid_genotype(genotype):
+ """
+ check if genotype is a valid genotype
+ (a string of 2 characters)
+ """
+ if not isinstance(genotype, str):
+ genotype = str(genotype)
+ if len(genotype) != 2:
+ raise TypeException('genotype should be two chars long')
+ return genotype
def create_debug_file():
"""
Create test file and tables
"""
- h5dfile = tables.openFile('../../data/test.h5', mode = 'w', title = 'Test file')
+ h5dfile = tables.openFile('../../data/test.h5', mode = 'w',
+ title = 'Testfile')
group = h5dfile.createGroup('/', 'tests', 'Test table')
- genotypes_table = h5dfile.createTable(group, 'genotypes', Genotype, 'Genotypes table')
-
+ genotypes_table = h5dfile.createTable(group, 'genotypes',
+ Genotype, 'Genotypes table')
+ return genotypes_table
def test_all():
"""
test the current module
"""
+ logging.basicConfig(level=logging.DEBUG)
create_debug_file()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
1b630c699b61a8dc8d4fa4c2af788e52a7dbdf49
|
played with tests a bit
|
diff --git a/src/schema/test/__init__.py b/src/schema/test/__init__.py
index 0529b93..44ef4ba 100644
--- a/src/schema/test/__init__.py
+++ b/src/schema/test/__init__.py
@@ -1,9 +1,10 @@
#!/usr/bin/env python
"""
Test the HGDP H5DF database
use nosetests for running it
"""
+__all__ = ['test1',]
def setup_package():
a = 2
global a
\ No newline at end of file
diff --git a/src/schema/test/test1.py b/src/schema/test/test1.py
new file mode 100644
index 0000000..4ed61b9
--- /dev/null
+++ b/src/schema/test/test1.py
@@ -0,0 +1,4 @@
+#!/usr/bin/env python
+
+def test_a():
+ assert a == 1
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
377f50f9253089a3eada8cc1152f0106a273599e
|
added a genotype column
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 7c6db4d..18660b8 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,47 +1,51 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import IsDescription
-from tables import Int32Col
-from tables import *
+from tables import Int32Col, StringCol
import tables
import logging
class Genotype(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
+
+ >>> geno1 = Genotype('hr1333', 'HGDP0001', '01')
+
"""
- snp = StringCol(16)
+ snp = StringCol(10)
individual_id = StringCol(16)
+ genotype = StringCol(2)
- def __init__(self, snp, individual):
+ def __init__(self, snp, individual, genotype):
row = self.row
row['snp'] = str(snp)
row['individual'] = individual
+ row['genotype'] = genotype
+ row.append()
-
-def create_test_file():
+def create_debug_file():
"""
Create test file and tables
"""
h5dfile = tables.openFile('../../data/test.h5', mode = 'w', title = 'Test file')
group = h5dfile.createGroup('/', 'tests', 'Test table')
genotypes_table = h5dfile.createTable(group, 'genotypes', Genotype, 'Genotypes table')
def test_all():
"""
test the current module
"""
- create_test_file()
+ create_debug_file()
import doctest
doctest.testmod()
if __name__ == '__main__':
test_all()
\ No newline at end of file
diff --git a/src/schema/test/__init__.py b/src/schema/test/__init__.py
index 00e5f1d..0529b93 100644
--- a/src/schema/test/__init__.py
+++ b/src/schema/test/__init__.py
@@ -1,10 +1,9 @@
#!/usr/bin/env python
"""
Test the HGDP H5DF database
use nosetests for running it
"""
-
def setup_package():
a = 2
global a
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
89eb27e501cbb18de7da64aba231c31e7fe37295
|
added a setup.py script
|
diff --git a/src/schema/setup.py b/src/schema/setup.py
new file mode 100644
index 0000000..3ea4cf2
--- /dev/null
+++ b/src/schema/setup.py
@@ -0,0 +1,8 @@
+from setuptools import setup, find_packages
+
+setup(
+ name = 'hgdp h5df schema',
+ version = '0.1',
+ packages = find_packages,
+
+ )
\ No newline at end of file
diff --git a/src/schema/test/__init__.py b/src/schema/test/__init__.py
new file mode 100644
index 0000000..00e5f1d
--- /dev/null
+++ b/src/schema/test/__init__.py
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+"""
+Test the HGDP H5DF database
+use nosetests for running it
+"""
+
+
+def setup_package():
+ a = 2
+ global a
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
24b288a6ec1c3fd6c4ef25838bfff0a7af02224c
|
added a 'create test table' function and added an init to SNP
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
index 4bace2d..7c6db4d 100644
--- a/src/schema/schema.py
+++ b/src/schema/schema.py
@@ -1,23 +1,47 @@
#!/usr/bin/env python
"""
HDF5 schema for the HGDP snp data
"""
from tables import IsDescription
from tables import Int32Col
from tables import *
+import tables
+import logging
class Genotype(IsDescription):
"""
A genotype identified by a snp ID and a individual ID
"""
snp = StringCol(16)
+ individual_id = StringCol(16)
+ def __init__(self, snp, individual):
+ row = self.row
+ row['snp'] = str(snp)
+ row['individual'] = individual
+
+
+
+def create_test_file():
+ """
+ Create test file and tables
+ """
+ h5dfile = tables.openFile('../../data/test.h5', mode = 'w', title = 'Test file')
+ group = h5dfile.createGroup('/', 'tests', 'Test table')
+
+ genotypes_table = h5dfile.createTable(group, 'genotypes', Genotype, 'Genotypes table')
+
+
def test_all():
+ """
+ test the current module
+ """
+ create_test_file()
import doctest
doctest.testmod()
if __name__ == '__main__':
- pass
\ No newline at end of file
+ test_all()
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
6a70cdf2cbeed4cab7e3d2dce9eddceb5354085b
|
added a short install doc
|
diff --git a/doc/install.txt b/doc/install.txt
new file mode 100644
index 0000000..f7a510f
--- /dev/null
+++ b/doc/install.txt
@@ -0,0 +1,11 @@
+How to install
+
+You need to have the HDF5 modules installed.
+On an Ubuntu machine, install the packages:
+- h5utils
+- hdf5-tools
+- libhdf5-serial-1.6.5-0
+- libhdf5-serial-dev
+
+Then, to install the pytables python library, do:
+sudo easy_install tables
\ No newline at end of file
|
dalloliogm/snps-hdf5
|
9d5dacbbe151ec685e6ccbb0b517e351a478768a
|
stub for a new schema with hdf5
|
diff --git a/src/schema/schema.py b/src/schema/schema.py
new file mode 100644
index 0000000..4bace2d
--- /dev/null
+++ b/src/schema/schema.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+"""
+HDF5 schema for the HGDP snp data
+
+"""
+
+from tables import IsDescription
+from tables import Int32Col
+from tables import *
+
+class Genotype(IsDescription):
+ """
+ A genotype identified by a snp ID and a individual ID
+ """
+ snp = StringCol(16)
+
+
+def test_all():
+ import doctest
+ doctest.testmod()
+
+if __name__ == '__main__':
+ pass
\ No newline at end of file
|
dotjay/hashgrid
|
4350c65118b73d12afaeac579d812370e97236d4
|
Minor edit
|
diff --git a/index.html b/index.html
index 73affa5..29958ac 100644
--- a/index.html
+++ b/index.html
@@ -1,317 +1,317 @@
<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title>
<!-- Demo styles-->
<style type="text/css">
/* Putting inline rules here so the document can be downloaded with style */
body{
font-size: 1em;
line-height: 1.25;
font-family: Arial, sans-serif;
background: White;
color: DimGray;
margin: 0;
padding: 0 20px;
}
#content{
font-size: 16px;
line-height: 20px;
position: relative;
}
#content{
width: 620px;
margin: 0 auto;
}
#footer{
border-top: 1px dotted DarkGray;
padding-top: 19px;
}
h1, h2{
color: Black;
font-weight: normal;
}
h1{
font-size: 36px;
line-height: 40px;
margin: 40px 0 20px;
padding-bottom: 19px;
border-bottom: 1px dotted DarkGray;
}
h1 em{
font-style: normal;
color: DarkGray;
font-size: 16px;
line-height: 20px;
margin: 0 0 20px;
}
h2, h3{
font-size: 16px;
font-weight: 700;
line-height: 20px;
margin: 0 0 20px;
}
h3{
font-weight: 300;
}
a:link,
a:visited{
color: Black;
text-decoration: none;
padding: 0 2px;
background-color: WhiteSmoke;
border-bottom: 1px solid Gold;
}
a:focus{
outline: none;
}
a:focus,
a:hover,
a:active{
background-color: Khaki;
border-bottom: 1px solid GoldenRod;
}
p, ul{
padding: 0;
margin: 0 0 20px;
}
dl, ol{
padding: 0;
margin: 0;
}
ul{
list-style: circle;
}
ol li{
margin-bottom: 20px;
}
dd{
margin: 0 0 20px 0;
}
del{
text-decoration: line-through;
opacity: 0.75;
}
ins{
text-decoration: none;
}
code{
font-size: 14px;
line-height: 1;
}
textarea{
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 20px;
display: block;
width: 600px;
margin: 0 0 20px;
padding: 20px 0 0 15px;
border: 0;
color: Black;
background: Gainsboro;
border-left: 5px solid DarkGray;
}
#javascript-code{
height: 300px;
}
#css-code{
height: 1560px;
}
.summary em{
font-style: normal;
position: absolute;
color: DarkGray;
right: 0;
top: 18px;
width: 140px;
}
.summary em span{
position: absolute;
left: -9999px;
}
#download{
line-height: 60px;
padding: 0 40px 0 15px;
border-left: 5px solid DarkGray;
background: Gainsboro;
color: DimGray;
}
span.key{
color: Black;
text-transform: uppercase;
}
</style>
<!-- Hashgrid styles-->
<style type="text/css">
/**
* Hashgrid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating Hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</style>
-</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the hashgrid script -->
+</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the Hashgrid script -->
<script type="text/javascript" src="hashgrid.js"></script>
-<!-- Kick hashgrid into action -->
+<!-- Kick Hashgrid into action -->
<script type="text/javascript">
var grid = new Hashgrid({ numberOfGrids: 2 });
</script>
<!-- Note: Use window onload if your css is not inlined -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
var grid = new Hashgrid({ numberOfGrids: 2 });
});
</script></textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/**
* Grid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the Hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick Hashgrid into action--><script>var hg = new Hashgrid({
numberOfGrids: 2
});</script></body></html>
\ No newline at end of file
|
dotjay/hashgrid
|
b86b751dd64ac16df991a99b1e71199eea0669ac
|
Correct id
|
diff --git a/index.html b/index.html
index e75463c..73affa5 100644
--- a/index.html
+++ b/index.html
@@ -1,317 +1,317 @@
<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title>
<!-- Demo styles-->
<style type="text/css">
/* Putting inline rules here so the document can be downloaded with style */
body{
font-size: 1em;
line-height: 1.25;
font-family: Arial, sans-serif;
background: White;
color: DimGray;
margin: 0;
padding: 0 20px;
}
#content{
font-size: 16px;
line-height: 20px;
position: relative;
}
#content{
width: 620px;
margin: 0 auto;
}
#footer{
border-top: 1px dotted DarkGray;
padding-top: 19px;
}
h1, h2{
color: Black;
font-weight: normal;
}
h1{
font-size: 36px;
line-height: 40px;
margin: 40px 0 20px;
padding-bottom: 19px;
border-bottom: 1px dotted DarkGray;
}
h1 em{
font-style: normal;
color: DarkGray;
font-size: 16px;
line-height: 20px;
margin: 0 0 20px;
}
h2, h3{
font-size: 16px;
font-weight: 700;
line-height: 20px;
margin: 0 0 20px;
}
h3{
font-weight: 300;
}
a:link,
a:visited{
color: Black;
text-decoration: none;
padding: 0 2px;
background-color: WhiteSmoke;
border-bottom: 1px solid Gold;
}
a:focus{
outline: none;
}
a:focus,
a:hover,
a:active{
background-color: Khaki;
border-bottom: 1px solid GoldenRod;
}
p, ul{
padding: 0;
margin: 0 0 20px;
}
dl, ol{
padding: 0;
margin: 0;
}
ul{
list-style: circle;
}
ol li{
margin-bottom: 20px;
}
dd{
margin: 0 0 20px 0;
}
del{
text-decoration: line-through;
opacity: 0.75;
}
ins{
text-decoration: none;
}
code{
font-size: 14px;
line-height: 1;
}
textarea{
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 20px;
display: block;
width: 600px;
margin: 0 0 20px;
padding: 20px 0 0 15px;
border: 0;
color: Black;
background: Gainsboro;
border-left: 5px solid DarkGray;
}
#javascript-code{
height: 300px;
}
#css-code{
height: 1560px;
}
.summary em{
font-style: normal;
position: absolute;
color: DarkGray;
right: 0;
top: 18px;
width: 140px;
}
.summary em span{
position: absolute;
left: -9999px;
}
#download{
line-height: 60px;
padding: 0 40px 0 15px;
border-left: 5px solid DarkGray;
background: Gainsboro;
color: DimGray;
}
span.key{
color: Black;
text-transform: uppercase;
}
</style>
<!-- Hashgrid styles-->
<style type="text/css">
/**
* Hashgrid
*/
-#grid{
+#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating Hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</style>
</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the hashgrid script -->
<script type="text/javascript" src="hashgrid.js"></script>
<!-- Kick hashgrid into action -->
<script type="text/javascript">
var grid = new Hashgrid({ numberOfGrids: 2 });
</script>
<!-- Note: Use window onload if your css is not inlined -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
var grid = new Hashgrid({ numberOfGrids: 2 });
});
</script></textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/**
* Grid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the Hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick Hashgrid into action--><script>var hg = new Hashgrid({
numberOfGrids: 2
});</script></body></html>
\ No newline at end of file
|
dotjay/hashgrid
|
d456247b71dfcffd9a9437b096005621119147a4
|
Cleaner license
|
diff --git a/index.html b/index.html
index 743aecb..e75463c 100644
--- a/index.html
+++ b/index.html
@@ -1,317 +1,317 @@
<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title>
<!-- Demo styles-->
<style type="text/css">
/* Putting inline rules here so the document can be downloaded with style */
body{
font-size: 1em;
line-height: 1.25;
font-family: Arial, sans-serif;
background: White;
color: DimGray;
margin: 0;
padding: 0 20px;
}
#content{
font-size: 16px;
line-height: 20px;
position: relative;
}
#content{
width: 620px;
margin: 0 auto;
}
#footer{
border-top: 1px dotted DarkGray;
padding-top: 19px;
}
h1, h2{
color: Black;
font-weight: normal;
}
h1{
font-size: 36px;
line-height: 40px;
margin: 40px 0 20px;
padding-bottom: 19px;
border-bottom: 1px dotted DarkGray;
}
h1 em{
font-style: normal;
color: DarkGray;
font-size: 16px;
line-height: 20px;
margin: 0 0 20px;
}
h2, h3{
font-size: 16px;
font-weight: 700;
line-height: 20px;
margin: 0 0 20px;
}
h3{
font-weight: 300;
}
a:link,
a:visited{
color: Black;
text-decoration: none;
padding: 0 2px;
background-color: WhiteSmoke;
border-bottom: 1px solid Gold;
}
a:focus{
outline: none;
}
a:focus,
a:hover,
a:active{
background-color: Khaki;
border-bottom: 1px solid GoldenRod;
}
p, ul{
padding: 0;
margin: 0 0 20px;
}
dl, ol{
padding: 0;
margin: 0;
}
ul{
list-style: circle;
}
ol li{
margin-bottom: 20px;
}
dd{
margin: 0 0 20px 0;
}
del{
text-decoration: line-through;
opacity: 0.75;
}
ins{
text-decoration: none;
}
code{
font-size: 14px;
line-height: 1;
}
textarea{
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 20px;
display: block;
width: 600px;
margin: 0 0 20px;
padding: 20px 0 0 15px;
border: 0;
color: Black;
background: Gainsboro;
border-left: 5px solid DarkGray;
}
#javascript-code{
height: 300px;
}
#css-code{
height: 1560px;
}
.summary em{
font-style: normal;
position: absolute;
color: DarkGray;
right: 0;
top: 18px;
width: 140px;
}
.summary em span{
position: absolute;
left: -9999px;
}
#download{
line-height: 60px;
padding: 0 40px 0 15px;
border-left: 5px solid DarkGray;
background: Gainsboro;
color: DimGray;
}
span.key{
color: Black;
text-transform: uppercase;
}
</style>
<!-- Hashgrid styles-->
<style type="text/css">
/**
* Hashgrid
*/
#grid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating Hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</style>
</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the hashgrid script -->
<script type="text/javascript" src="hashgrid.js"></script>
<!-- Kick hashgrid into action -->
<script type="text/javascript">
var grid = new Hashgrid({ numberOfGrids: 2 });
</script>
<!-- Note: Use window onload if your css is not inlined -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
var grid = new Hashgrid({ numberOfGrids: 2 });
});
</script></textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/**
* Grid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
-</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({
+</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the Hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick Hashgrid into action--><script>var hg = new Hashgrid({
numberOfGrids: 2
});</script></body></html>
\ No newline at end of file
diff --git a/src/index.jade b/src/index.jade
index 5fd7cc6..3cee7dd 100644
--- a/src/index.jade
+++ b/src/index.jade
@@ -1,157 +1,157 @@
doctype html
html(lang="en-GB")
head
meta(http-equiv="Content-Type", content="text/html; charset=utf-8")
link(rel="shortcut icon", type="image/x-icon", href="favicon.ico")
title #grid
// Demo styles
style(type="text/css")
include ./partial/demo.css
// Hashgrid styles
style(type="text/css")
include ./partial/hashgrid.css
body
main#content
h1
| #grid
em v10
p.summary
em 30 Nov 2015
span :
| #grid (or âHashgridâ) is a little tool that inserts a 
a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid
| in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit
span(class="key") g
| on your keyboard.
h2 Download
p#download
a(href="https://github.com/dotjay/hashgrid/tags") Download #grid
| from
a(href="https://github.com/dotjay/hashgrid") GitHub
h2#features Features
ul
li Adaptable for all layout widths and alignments
li Adaptable for any vertical rhythm value
li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids
li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters
p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.
h2#installation Installation
ol
li
h3 Copy the
a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js
| script to your project
li
h3 Add this script to your page(s) just before the closing <code></body></code> tag
include ./partial/js_code.jade
li
h3 Add the CSS to your page(s)
include ./partial/css_code.jade
li
h3 Modify #grid to suit your needs
p The CSS and JavaScript is annotated to help you.
h2#usage Usage
p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.
dl
dt <span class="key">g</span>
dd Show the grid until you release.
dt <span class="key">g</span> + <span class="key">h</span>
dd Show and hold the grid (<span class="key">g</span> will remove it again).
dt <span class="key">g</span> + <span class="key">f</span>
dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.
dt <span class="key">g</span> + <span class="key">j</span>
dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.
p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em>
h2#release-notes Release Notes
dl
dt v10 — 30 Nov 2015
dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.
dt v9 — 30 May 2013
dd Minor release: Improved example usage to avoid conflicts.
dt v8 — 6 Oct 2012
dd
ul
li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.
li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.
li Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.
li Optimisations.
dt v7 — 11 Jun 2011
dd Minor release: Updated license references.
dt v6 — 10 Jun 2011
dd Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.
dt v5 — 3 Nov 2010
dd
ul
li Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.
li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="https://github.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.
li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.
dt v4 — 29 Mar 2010
dd Fixes for multiple grid support under WebKit (Safari and Chrome).
dt v3 — 22 Feb 2010
dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.
dt v2 — 2 Feb 2010
dd
ul
li Keys are now more easily configured (see top of hashgrid.js).
li Fixed crash when using with disabled CSS.
li Renamed the GridOverlay object to hashgrid.
dt v1 — 21 Dec 2009
dd First release.
h2#known-issues Known Issues
ul
li No known issues.
h2#license License
- p Copyright 2013-2022 Jon Gibbins
+ p Copyright Jon Gibbins
p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/>
a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0
p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
p This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.
div#footer(role="contentinfo")
p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.
// Include the Hashgrid script
script(type="text/javascript" src="dist/javascripts/hashgrid.js")
// Kick Hashgrid into action
script.
var hg = new Hashgrid({
numberOfGrids: 2
});
|
dotjay/hashgrid
|
e996f2970c8b2aaead3715c9ed08f74de333c1d4
|
Correct link to James Aitken
|
diff --git a/index.html b/index.html
index fe3d02e..743aecb 100644
--- a/index.html
+++ b/index.html
@@ -1,317 +1,317 @@
<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title>
<!-- Demo styles-->
<style type="text/css">
/* Putting inline rules here so the document can be downloaded with style */
body{
font-size: 1em;
line-height: 1.25;
font-family: Arial, sans-serif;
background: White;
color: DimGray;
margin: 0;
padding: 0 20px;
}
#content{
font-size: 16px;
line-height: 20px;
position: relative;
}
#content{
width: 620px;
margin: 0 auto;
}
#footer{
border-top: 1px dotted DarkGray;
padding-top: 19px;
}
h1, h2{
color: Black;
font-weight: normal;
}
h1{
font-size: 36px;
line-height: 40px;
margin: 40px 0 20px;
padding-bottom: 19px;
border-bottom: 1px dotted DarkGray;
}
h1 em{
font-style: normal;
color: DarkGray;
font-size: 16px;
line-height: 20px;
margin: 0 0 20px;
}
h2, h3{
font-size: 16px;
font-weight: 700;
line-height: 20px;
margin: 0 0 20px;
}
h3{
font-weight: 300;
}
a:link,
a:visited{
color: Black;
text-decoration: none;
padding: 0 2px;
background-color: WhiteSmoke;
border-bottom: 1px solid Gold;
}
a:focus{
outline: none;
}
a:focus,
a:hover,
a:active{
background-color: Khaki;
border-bottom: 1px solid GoldenRod;
}
p, ul{
padding: 0;
margin: 0 0 20px;
}
dl, ol{
padding: 0;
margin: 0;
}
ul{
list-style: circle;
}
ol li{
margin-bottom: 20px;
}
dd{
margin: 0 0 20px 0;
}
del{
text-decoration: line-through;
opacity: 0.75;
}
ins{
text-decoration: none;
}
code{
font-size: 14px;
line-height: 1;
}
textarea{
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 20px;
display: block;
width: 600px;
margin: 0 0 20px;
padding: 20px 0 0 15px;
border: 0;
color: Black;
background: Gainsboro;
border-left: 5px solid DarkGray;
}
#javascript-code{
height: 300px;
}
#css-code{
height: 1560px;
}
.summary em{
font-style: normal;
position: absolute;
color: DarkGray;
right: 0;
top: 18px;
width: 140px;
}
.summary em span{
position: absolute;
left: -9999px;
}
#download{
line-height: 60px;
padding: 0 40px 0 15px;
border-left: 5px solid DarkGray;
background: Gainsboro;
color: DimGray;
}
span.key{
color: Black;
text-transform: uppercase;
}
</style>
<!-- Hashgrid styles-->
<style type="text/css">
/**
* Hashgrid
*/
#grid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating Hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</style>
</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the hashgrid script -->
<script type="text/javascript" src="hashgrid.js"></script>
<!-- Kick hashgrid into action -->
<script type="text/javascript">
var grid = new Hashgrid({ numberOfGrids: 2 });
</script>
<!-- Note: Use window onload if your css is not inlined -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
var grid = new Hashgrid({ numberOfGrids: 2 });
});
</script></textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/**
* Grid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
-</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({
+</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({
numberOfGrids: 2
});</script></body></html>
\ No newline at end of file
diff --git a/src/index.jade b/src/index.jade
index 395538a..5fd7cc6 100644
--- a/src/index.jade
+++ b/src/index.jade
@@ -1,157 +1,157 @@
doctype html
html(lang="en-GB")
head
meta(http-equiv="Content-Type", content="text/html; charset=utf-8")
link(rel="shortcut icon", type="image/x-icon", href="favicon.ico")
title #grid
// Demo styles
style(type="text/css")
include ./partial/demo.css
// Hashgrid styles
style(type="text/css")
include ./partial/hashgrid.css
body
main#content
h1
| #grid
em v10
p.summary
em 30 Nov 2015
span :
| #grid (or âHashgridâ) is a little tool that inserts a 
a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid
| in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit
span(class="key") g
| on your keyboard.
h2 Download
p#download
a(href="https://github.com/dotjay/hashgrid/tags") Download #grid
| from
a(href="https://github.com/dotjay/hashgrid") GitHub
h2#features Features
ul
li Adaptable for all layout widths and alignments
li Adaptable for any vertical rhythm value
li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids
li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters
p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.
h2#installation Installation
ol
li
h3 Copy the
a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js
| script to your project
li
h3 Add this script to your page(s) just before the closing <code></body></code> tag
include ./partial/js_code.jade
li
h3 Add the CSS to your page(s)
include ./partial/css_code.jade
li
h3 Modify #grid to suit your needs
p The CSS and JavaScript is annotated to help you.
h2#usage Usage
p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.
dl
dt <span class="key">g</span>
dd Show the grid until you release.
dt <span class="key">g</span> + <span class="key">h</span>
dd Show and hold the grid (<span class="key">g</span> will remove it again).
dt <span class="key">g</span> + <span class="key">f</span>
dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.
dt <span class="key">g</span> + <span class="key">j</span>
dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.
p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em>
h2#release-notes Release Notes
dl
dt v10 — 30 Nov 2015
dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.
dt v9 — 30 May 2013
dd Minor release: Improved example usage to avoid conflicts.
dt v8 — 6 Oct 2012
dd
ul
li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.
li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.
- li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.
+ li Fixes to cookie handling. Thanks to <a href="https://github.com/LoonyPandora">James Aitken</a>.
li Optimisations.
dt v7 — 11 Jun 2011
dd Minor release: Updated license references.
dt v6 — 10 Jun 2011
dd Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.
dt v5 — 3 Nov 2010
dd
ul
li Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.
li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="https://github.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.
li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.
dt v4 — 29 Mar 2010
dd Fixes for multiple grid support under WebKit (Safari and Chrome).
dt v3 — 22 Feb 2010
dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.
dt v2 — 2 Feb 2010
dd
ul
li Keys are now more easily configured (see top of hashgrid.js).
li Fixed crash when using with disabled CSS.
li Renamed the GridOverlay object to hashgrid.
dt v1 — 21 Dec 2009
dd First release.
h2#known-issues Known Issues
ul
li No known issues.
h2#license License
p Copyright 2013-2022 Jon Gibbins
p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/>
a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0
p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
p This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.
div#footer(role="contentinfo")
p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.
// Include the Hashgrid script
script(type="text/javascript" src="dist/javascripts/hashgrid.js")
// Kick Hashgrid into action
script.
var hg = new Hashgrid({
numberOfGrids: 2
});
|
dotjay/hashgrid
|
478dbd6aea1d798326d3f701c3b9998a78b1dd4c
|
Correct link to Tom Arnold
|
diff --git a/index.html b/index.html
index fc4583c..fe3d02e 100644
--- a/index.html
+++ b/index.html
@@ -1,317 +1,317 @@
<!DOCTYPE html><html lang="en-GB"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico"><title>#grid</title>
<!-- Demo styles-->
<style type="text/css">
/* Putting inline rules here so the document can be downloaded with style */
body{
font-size: 1em;
line-height: 1.25;
font-family: Arial, sans-serif;
background: White;
color: DimGray;
margin: 0;
padding: 0 20px;
}
#content{
font-size: 16px;
line-height: 20px;
position: relative;
}
#content{
width: 620px;
margin: 0 auto;
}
#footer{
border-top: 1px dotted DarkGray;
padding-top: 19px;
}
h1, h2{
color: Black;
font-weight: normal;
}
h1{
font-size: 36px;
line-height: 40px;
margin: 40px 0 20px;
padding-bottom: 19px;
border-bottom: 1px dotted DarkGray;
}
h1 em{
font-style: normal;
color: DarkGray;
font-size: 16px;
line-height: 20px;
margin: 0 0 20px;
}
h2, h3{
font-size: 16px;
font-weight: 700;
line-height: 20px;
margin: 0 0 20px;
}
h3{
font-weight: 300;
}
a:link,
a:visited{
color: Black;
text-decoration: none;
padding: 0 2px;
background-color: WhiteSmoke;
border-bottom: 1px solid Gold;
}
a:focus{
outline: none;
}
a:focus,
a:hover,
a:active{
background-color: Khaki;
border-bottom: 1px solid GoldenRod;
}
p, ul{
padding: 0;
margin: 0 0 20px;
}
dl, ol{
padding: 0;
margin: 0;
}
ul{
list-style: circle;
}
ol li{
margin-bottom: 20px;
}
dd{
margin: 0 0 20px 0;
}
del{
text-decoration: line-through;
opacity: 0.75;
}
ins{
text-decoration: none;
}
code{
font-size: 14px;
line-height: 1;
}
textarea{
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 20px;
display: block;
width: 600px;
margin: 0 0 20px;
padding: 20px 0 0 15px;
border: 0;
color: Black;
background: Gainsboro;
border-left: 5px solid DarkGray;
}
#javascript-code{
height: 300px;
}
#css-code{
height: 1560px;
}
.summary em{
font-style: normal;
position: absolute;
color: DarkGray;
right: 0;
top: 18px;
width: 140px;
}
.summary em span{
position: absolute;
left: -9999px;
}
#download{
line-height: 60px;
padding: 0 40px 0 15px;
border-left: 5px solid DarkGray;
background: Gainsboro;
color: DimGray;
}
span.key{
color: Black;
text-transform: uppercase;
}
</style>
<!-- Hashgrid styles-->
<style type="text/css">
/**
* Hashgrid
*/
#grid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating Hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
</style>
</head><body><main id="content"><h1>#grid <em>v10</em></h1><p class="summary"><em>30 Nov 2015<span>:</span></em>#grid (or âHashgridâ) is a little tool that inserts a <a href="http://en.wikipedia.org/wiki/Grid_(page_layout)">layout grid</a> in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit <span class="key">g</span> on your keyboard.</p><h2>Download</h2><p id="download"><a href="https://github.com/dotjay/hashgrid/tags">Download #grid</a> from <a href="https://github.com/dotjay/hashgrid">GitHub</a></p><h2 id="features">Features</h2><ul><li>Adaptable for all layout widths and alignments</li><li>Adaptable for any vertical rhythm value</li><li>Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids</li><li>Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters</li></ul><p>#grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.</p><h2 id="installation">Installation</h2><ol><li><h3>Copy the <a href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts">hashgrid.js</a> script to your project</h3></li><li><h3>Add this script to your page(s) just before the closing <code></body></code> tag</h3><textarea id="javascript-code" cols="68" rows="15" readonly="readonly"><!-- Include the hashgrid script -->
<script type="text/javascript" src="hashgrid.js"></script>
<!-- Kick hashgrid into action -->
<script type="text/javascript">
var grid = new Hashgrid({ numberOfGrids: 2 });
</script>
<!-- Note: Use window onload if your css is not inlined -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
var grid = new Hashgrid({ numberOfGrids: 2 });
});
</script></textarea></li><li><h3>Add the CSS to your page(s)</h3><textarea id="css-code" cols="68" rows="64" readonly="readonly">/**
* Grid
*/
#hashgrid{
/*
* Spreads the whole page by default
* Adjust to match your container
*/
/*width: 100%;*/
width: 980px;
position: absolute;
height: 100%;
top: 0;
left: 50%;
margin-left: -490px;
overflow: hidden;
}
.hashgrid-column-container {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
/**
* Vertical grid lines
*
* Set the column width taking the borders into consideration,
* and use margins to set column gutters.
*/
.hashgrid__column{
width: 139px;
border: solid darkturquoise;
border-width: 0 1px;
margin-left: 19px;
height: 100%;
float: left;
}
/**
* Horizontal grid lines, defined by your base line height
*
* Remember, the CSS properties that define the box model:
* visible height = height + borders + margins + padding
*/
.hashgrid__row{
/* 20px line height */
height: 19px;
border-bottom: 1px dotted darkgray;
margin: 0;
padding: 0;
}
/**
* Classes for multiple grids
*
* When using more than one grid, remember to set the numberOfGrids
* option when instantiating hashgrid.
* e.g.
*
* var hg = new Hashgrid({
* numberOfGrids: 2
* });
*/
#hashgrid.hashgrid2,
#hashgrid.hashgrid2 .hashgrid-column-container{
/* Container width adjustments */
padding: 0 160px;
width: 660px;
}
#hashgrid.hashgrid2 .hashgrid__column{
/* Vertical grid line colour for grid 2 */
border-color: crimson;
}
-</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({
+</textarea></li><li><h3>Modify #grid to suit your needs</h3><p>The CSS and JavaScript is annotated to help you.</p></li></ol><h2 id="usage">Usage</h2><p>The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.</p><dl><dt><span class="key">g</span></dt><dd>Show the grid until you release.</dd><dt><span class="key">g</span> + <span class="key">h</span></dt><dd>Show and hold the grid (<span class="key">g</span> will remove it again).</dd><dt><span class="key">g</span> + <span class="key">f</span></dt><dd>Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.</dd><dt><span class="key">g</span> + <span class="key">j</span></dt><dd>Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.</dd></dl><p><em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em></p><h2 id="release-notes">Release Notes</h2><dl><dt>v10 — 30 Nov 2015</dt><dd>Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.</dd><dt>v9 — 30 May 2013</dt><dd>Minor release: Improved example usage to avoid conflicts.</dd><dt>v8 — 6 Oct 2012</dt><dd><ul><li>Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.</li><li>Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.</li><li>Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.</li><li>Optimisations.</li></ul></dd><dt>v7 — 11 Jun 2011</dt><dd>Minor release: Updated license references.</dd><dt>v6 — 10 Jun 2011</dt><dd>Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.</dd><dt>v5 — 3 Nov 2010</dt><dd><ul><li>Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.</li><li>Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.</li><li>Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.</li></ul></dd><dt>v4 — 29 Mar 2010</dt><dd>Fixes for multiple grid support under WebKit (Safari and Chrome).</dd><dt>v3 — 22 Feb 2010</dt><dd>Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.</dd><dt>v2 — 2 Feb 2010</dt><dd><ul><li>Keys are now more easily configured (see top of hashgrid.js).</li><li>Fixed crash when using with disabled CSS.</li><li>Renamed the GridOverlay object to hashgrid.</li></ul></dd><dt>v1 — 21 Dec 2009</dt><dd>First release.</dd></dl><h2 id="known-issues">Known Issues</h2><ul><li>No known issues.</li></ul><h2 id="license">License</h2><p>Copyright 2013-2022 Jon Gibbins</p><p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/></p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a><p><br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</p><p>This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.</p><div id="footer" role="contentinfo"><p>#grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.</p></div></main><!-- Include the hashgrid script--><script type="text/javascript" src="dist/javascripts/hashgrid.js"></script><!-- Kick hashgrid into action--><script>var hg = new Hashgrid({
numberOfGrids: 2
});</script></body></html>
\ No newline at end of file
diff --git a/src/index.jade b/src/index.jade
index 3cdd17d..395538a 100644
--- a/src/index.jade
+++ b/src/index.jade
@@ -1,157 +1,157 @@
doctype html
html(lang="en-GB")
head
meta(http-equiv="Content-Type", content="text/html; charset=utf-8")
link(rel="shortcut icon", type="image/x-icon", href="favicon.ico")
title #grid
// Demo styles
style(type="text/css")
include ./partial/demo.css
// Hashgrid styles
style(type="text/css")
include ./partial/hashgrid.css
body
main#content
h1
| #grid
em v10
p.summary
em 30 Nov 2015
span :
| #grid (or âHashgridâ) is a little tool that inserts a 
a(href="http://en.wikipedia.org/wiki/Grid_(page_layout)") layout grid
| in web pages, allows you to hold it in place, and toggle between displaying it in the foreground or background. To see it in action, hit
span(class="key") g
| on your keyboard.
h2 Download
p#download
a(href="https://github.com/dotjay/hashgrid/tags") Download #grid
| from
a(href="https://github.com/dotjay/hashgrid") GitHub
h2#features Features
ul
li Adaptable for all layout widths and alignments
li Adaptable for any vertical rhythm value
li Set keyboard shortcuts to show and hide the grid, hold it in place, toggle it to the foreground and background, and jump between multiple grids
li Uses a single JavaScript file and a little CSS to control the grid lines, columns and gutters
p #grid comes set up with a 980px-wide container that includes 20px gutters, and assumes one lead of 20px. A second 660px-wide container is included to show you how to set up multiple grids.
h2#installation Installation
ol
li
h3 Copy the
a(href="https://github.com/dotjay/hashgrid/tree/main/dist/javascripts") hashgrid.js
| script to your project
li
h3 Add this script to your page(s) just before the closing <code></body></code> tag
include ./partial/js_code.jade
li
h3 Add the CSS to your page(s)
include ./partial/css_code.jade
li
h3 Modify #grid to suit your needs
p The CSS and JavaScript is annotated to help you.
h2#usage Usage
p The document must have keyboard focus for #grid to work. You may need to click on the document background or <span class="key">TAB</span> into the page first.
dl
dt <span class="key">g</span>
dd Show the grid until you release.
dt <span class="key">g</span> + <span class="key">h</span>
dd Show and hold the grid (<span class="key">g</span> will remove it again).
dt <span class="key">g</span> + <span class="key">f</span>
dd Toggle the grid to the foreground and back. Pressing <span class="key">f</span> while the grid is held also works.
dt <span class="key">g</span> + <span class="key">j</span>
dd Jump to the next grid. Pressing <span class="key">j</span> while the grid is held also works.
p <em>Note: Hashgrid remembers the state of the grid when you refresh the page. While the grid is in front, you will not be able to interact with the page.</em>
h2#release-notes Release Notes
dl
dt v10 — 30 Nov 2015
dd Works with vanilla JavaScript - jQuery is no longer required - thanks to <a href="https://github.com/widatama">widatama</a>.
dt v9 — 30 May 2013
dd Minor release: Improved example usage to avoid conflicts.
dt v8 — 6 Oct 2012
dd
ul
- li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="http://www.tomarnold.de/">Tom Arnold</a>.
+ li Grid overlay can now be used inside a wrapping container with <code>position: relative;</code> rather than working inside the whole viewport. Thanks to <a href="https://www.tomarnold.de/">Tom Arnold</a>.
li Holding down the #grid keys will no longer make browsers cry. Thanks to <a href="https://github.com/callumacrae">Callum Macrae</a>.
li Fixes to cookie handling. Thanks to <a href="http://loonypandora.co.uk/">James Aitken</a>.
li Optimisations.
dt v7 — 11 Jun 2011
dd Minor release: Updated license references.
dt v6 — 10 Jun 2011
dd Minor release: Optimisations (thanks to <a href="https://github.com/ajaswa/">Andrew Jaswa</a> for contributions), and now released under an Apache License.
dt v5 — 3 Nov 2010
dd
ul
li Vertical grid lines can now be set using CSS… images are no longer required! Thanks to <a href="https://twitter.com/coates">Sean Coates</a> for the contribution.
- li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="http://twitter.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.
+ li Click events now interact with the page when the grid is in the foreground. Tested in WebKit and Gecko. Thanks to <a href="https://github.com/pdokas">Phil Dokas</a> for the tip about using the <code>pointer-events</code> CSS property.
li Improved grid rendering, fixing a compatibility issue with jQuery 1.4.3. Thanks to everybody who’s given feedback.
dt v4 — 29 Mar 2010
dd Fixes for multiple grid support under WebKit (Safari and Chrome).
dt v3 — 22 Feb 2010
dd Multiple grids can be set up and cycled through at a key press. To avoid keyboard shortcut conflicts, the default keys have been changed (see <a href="#usage">Usage</a>). Using <span class="key">CTRL</span>, <span class="key">ALT</span> or <span class="key">SHIFT</span> as a modifier key is now optional. Keys no longer show or affect the grid while typing in forms.
dt v2 — 2 Feb 2010
dd
ul
li Keys are now more easily configured (see top of hashgrid.js).
li Fixed crash when using with disabled CSS.
li Renamed the GridOverlay object to hashgrid.
dt v1 — 21 Dec 2009
dd First release.
h2#known-issues Known Issues
ul
li No known issues.
h2#license License
p Copyright 2013-2022 Jon Gibbins
p Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at<br/>
a(href="http://www.apache.org/licenses/LICENSE-2.0") http://www.apache.org/licenses/LICENSE-2.0
p <br/>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
p This essentially means that you’re free to copy, modify and distribute it for any project so long as you provide clear attribution to the author. <a href="https://dotjay.com/contact">Get in touch</a> if you need a different license.
div#footer(role="contentinfo")
p #grid was built by <a href="https://dotjay.com/">Jon Gibbins</a> and designed by <a href="https://jontangerine.com/">Jon Tan</a>. Oh, and the CSS for this page playfully uses <a href="http://www.w3.org/TR/css3-color/#svg-color">SVG colour keywords</a> only.
// Include the Hashgrid script
script(type="text/javascript" src="dist/javascripts/hashgrid.js")
// Kick Hashgrid into action
script.
var hg = new Hashgrid({
numberOfGrids: 2
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.