repo
string
commit
string
message
string
diff
string
mortenberg80/minimal_ircbot
1ee3c3e869afc879488982e47ea1d4765ec8b781
removed unused string import
diff --git a/minimal_bot.py b/minimal_bot.py index 89d89fa..d8d6c6b 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,44 +1,43 @@ # -*- coding: utf-8 -*- # Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket -import string import subprocess import config readbuffer='' s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) print 'Running' def parse(input): p = subprocess.Popen('python %s' % 'minimal_parser.py', shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) return p.communicate(input=input)[0].strip().split('\n') while 1: readbuffer = readbuffer + s.recv(1024) temp = readbuffer.split("\n") readbuffer = temp.pop() for line in temp: line = line.strip() tokens = line.split() if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) if line[0] == "PING": s.send("PONG %s\r\n" % tokens[1])
mortenberg80/minimal_ircbot
de21f9fb4313db4e09d9ad457a1879c3e3d6ef4f
added initial gitignore file
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..536343c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pyc +*.swp +local_config.py
mortenberg80/minimal_ircbot
5c40ec1366ab9dde3b89f477c45ff7c1b636d538
added import of local_config settings
diff --git a/config.py b/config.py index fc8e8ac..859b9b1 100644 --- a/config.py +++ b/config.py @@ -1,7 +1,11 @@ -HOST='irc.homelien.no' -PORT=6667 -NICK='myNick' -IDENT='pybot' -REALNAME='I am' +HOST = 'irc.homelien.no' +PORT = 6667 +NICK = 'mynick' +IDENT = 'pybot' +REALNAME = 'I am' +CHANNEL = '#mychannel' -CHANNEL='#mychannel' +try: + from local_config import * +except ImportError: + pass
mortenberg80/minimal_ircbot
ba435f749c2c656dfe4200fb90a0045e2db5e984
rewrote the parser to get entire incoming message and a bit more object oriented
diff --git a/minimal_bot.py b/minimal_bot.py index 6c4e082..89d89fa 100644 --- a/minimal_bot.py +++ b/minimal_bot.py @@ -1,44 +1,44 @@ # -*- coding: utf-8 -*- +# Based on the O'Reilly example at http://oreilly.com/pub/h/1968 import sys import socket import string import subprocess import config readbuffer='' s=socket.socket() s.connect((config.HOST, config.PORT)) s.send("NICK %s\r\n" % config.NICK) s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) s.send("JOIN %s\r\n" % config.CHANNEL) -def parse(string): - p = subprocess.Popen('python %s' % 'minimal_parser.py', shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - - try: - p.stdin.writelines(string) - finally: - p.stdin.close() +print 'Running' - return p.stdout.readlines() +def parse(input): + p = subprocess.Popen('python %s' % 'minimal_parser.py', + shell=True, + bufsize=1024, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) -print 'Running' + return p.communicate(input=input)[0].strip().split('\n') while 1: - readbuffer=readbuffer+s.recv(1024) - temp=string.split(readbuffer, "\n") - readbuffer=temp.pop() + readbuffer = readbuffer + s.recv(1024) + temp = readbuffer.split("\n") + readbuffer = temp.pop() for line in temp: - line=string.rstrip(line) - line=string.split(line) + line = line.strip() + tokens = line.split() - if line[1] == "PRIVMSG" and line[2] == config.CHANNEL: - messages = parse(line[3][1:]) + if tokens[1] == "PRIVMSG" and tokens[2] == config.CHANNEL: + messages = parse(line) for message in messages: s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) - if line[0]=="PING": - s.send("PONG %s\r\n" % line[1]) + if line[0] == "PING": + s.send("PONG %s\r\n" % tokens[1]) diff --git a/minimal_parser.py b/minimal_parser.py index d86cd74..1a1c66e 100644 --- a/minimal_parser.py +++ b/minimal_parser.py @@ -1,24 +1,55 @@ # -*- coding: utf-8 -*- import sys import datetime as dt import config -input = sys.stdin.readline() +class parser: + def __init__(self, input): + self.input = input + self.tokens = input.split() + self.message_tokens = self.tokens[3:] + self.message_tokens[0] = self.message_tokens[0][1:] -message = [] + def parse(self): + message = ' '.join(self.message_tokens) + output = [] -if input == "ping": - message = "Hei hei!" -elif input.startswith(config.NICK): - to_message = input[len(config.NICK):].lstrip() - print to_message - message = "Beklager... Jeg har ikke lært å snakke ennå :(" -elif input == "time": - message = dt.datetime.now().strftime("%Y-%m-%d %H:%M") + if message.lower() == "ping": + output = self.handle_ping() -if type(message) == str: - message = message.split('\n') + elif message.lower() == "time": + output = self.handle_time() -for message_line in message: - print message_line + elif self.message_tokens.pop(0) == '%s:' % config.NICK: + output = self.parse_personal_message() + + if type(output) == str: + output = output.split('\n') + + return output + + def parse_personal_message(self): + self.message = ' '.join(self.message_tokens) + + if self.message.lower() == 'how are you?': + return self.handle_personal_how_are_you() + else: + output = ["Beklager... Jeg har ikke lært meg ditt språk ennå."] + output += ["Prøv %s: how are you?" % config.NICK] + return output + + def handle_personal_how_are_you(self): + return 'I am bad to the bone!' + + def handle_ping(self): + return 'pong' + + def handle_time(self): + return dt.datetime.now().strftime("%Y-%m-%d %H:%M") + +p = parser(sys.stdin.readline()) +output = p.parse() + +for output_line in output: + print output_line
mortenberg80/minimal_ircbot
6fc0aa35ec94bc72b357bfa91b8db760d4641614
initial import
diff --git a/config.py b/config.py new file mode 100644 index 0000000..fc8e8ac --- /dev/null +++ b/config.py @@ -0,0 +1,7 @@ +HOST='irc.homelien.no' +PORT=6667 +NICK='myNick' +IDENT='pybot' +REALNAME='I am' + +CHANNEL='#mychannel' diff --git a/minimal_bot.py b/minimal_bot.py new file mode 100644 index 0000000..6c4e082 --- /dev/null +++ b/minimal_bot.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +import sys +import socket +import string +import subprocess + +import config + +readbuffer='' + +s=socket.socket() +s.connect((config.HOST, config.PORT)) +s.send("NICK %s\r\n" % config.NICK) +s.send("USER %s %s bla :%s\r\n" % (config.IDENT, config.HOST, config.REALNAME)) +s.send("JOIN %s\r\n" % config.CHANNEL) + +def parse(string): + p = subprocess.Popen('python %s' % 'minimal_parser.py', shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + try: + p.stdin.writelines(string) + finally: + p.stdin.close() + + return p.stdout.readlines() + +print 'Running' + +while 1: + readbuffer=readbuffer+s.recv(1024) + temp=string.split(readbuffer, "\n") + readbuffer=temp.pop() + + for line in temp: + line=string.rstrip(line) + line=string.split(line) + + if line[1] == "PRIVMSG" and line[2] == config.CHANNEL: + messages = parse(line[3][1:]) + for message in messages: + s.send("PRIVMSG %s :%s\r\n" % (config.CHANNEL, message)) + + if line[0]=="PING": + s.send("PONG %s\r\n" % line[1]) diff --git a/minimal_parser.py b/minimal_parser.py new file mode 100644 index 0000000..d86cd74 --- /dev/null +++ b/minimal_parser.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +import sys +import datetime as dt + +import config + +input = sys.stdin.readline() + +message = [] + +if input == "ping": + message = "Hei hei!" +elif input.startswith(config.NICK): + to_message = input[len(config.NICK):].lstrip() + print to_message + message = "Beklager... Jeg har ikke lært å snakke ennå :(" +elif input == "time": + message = dt.datetime.now().strftime("%Y-%m-%d %H:%M") + +if type(message) == str: + message = message.split('\n') + +for message_line in message: + print message_line
LupineDev/lupine_crypto
9e7df261e0749ec2246c6cbfab4eca96aac124c8
forgot licesnse in README.rdoc
diff --git a/README.rdoc b/README.rdoc index 933c03a..7f8d56c 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,21 +1,21 @@ = lupine_crypto Ruby implementation of some classic encryption algorithms. == Current Encryption Algorithms * Ceasar Cipher (the "Hellow World" of encryption) Hopefully there will be more to come... == Gem Status Just added a gem skeleton using jeweler https://github.com/technicalpickles/jeweler but have not fully integrated the old code into it so it's not quite ready for its first release ==== Copyright -Copyright (c) 2010 LupineDev. See LICENSE.txt for +Copyright (c) 2010 Christopher Sass. See LICENSE.txt for further details.
LupineDev/lupine_crypto
7fa1196c0105084debaf09719660f10bd2c835a9
Ignore vim swapfiles
diff --git a/.gitignore b/.gitignore index 2288186..ee0d9ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,42 +1,47 @@ # rcov generated coverage # rdoc generated rdoc # yard generated doc .yardoc # bundler .bundle # jeweler generated pkg +# ignore vim swapfiles +*.swp +*.swo +*.swn + # Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore: # # * Create a file at ~/.gitignore # * Include files you want ignored # * Run: git config --global core.excludesfile ~/.gitignore # # After doing this, these files will be ignored in all your git projects, # saving you from having to 'pollute' every project you touch with them # # Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line) # # For MacOS: # #.DS_Store # # For TextMate #*.tmproj #tmtags # # For emacs: #*~ #\#* #.\#* # # For vim: #*.swp
LupineDev/lupine_crypto
d3c6c733d32c8860a073e5492492da92630c1bff
Minor tweaks to rdoc, license, and lib/*
diff --git a/LICENSE.txt b/LICENSE.txt index 45d8019..aec4a84 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,20 +1,20 @@ -Copyright (c) 2010 LupineDev +Copyright (c) 2010 Christopher Sass Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.rdoc b/README.rdoc index ddd178a..933c03a 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,19 +1,21 @@ = lupine_crypto -Description goes here. +Ruby implementation of some classic encryption algorithms. + +== Current Encryption Algorithms + +* Ceasar Cipher (the "Hellow World" of encryption) + +Hopefully there will be more to come... + +== Gem Status + +Just added a gem skeleton using jeweler https://github.com/technicalpickles/jeweler but have not fully +integrated the old code into it so it's not quite ready for its first release -== Contributing to lupine_crypto -* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet -* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it -* Fork the project -* Start a feature/bugfix branch -* Commit and push until you are happy with your contribution -* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally. -* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it. - -== Copyright +==== Copyright Copyright (c) 2010 LupineDev. See LICENSE.txt for further details. diff --git a/lib/ceasar.rb b/lib/ceasar.rb index eb67e0e..4adca61 100644 --- a/lib/ceasar.rb +++ b/lib/ceasar.rb @@ -1,115 +1,117 @@ -class Ceasar - # class variables - private - # hash for letters -> numbers - @@numbers = { - 'A' => 1, - 'B' => 2, - 'C' => 3, - 'D' => 4, - 'E' => 5, - 'F' => 6, - 'G' => 7, - 'H' => 8, - 'I' => 9, - 'J' => 10, - 'K' => 11, - 'L' => 12, - 'M' => 13, - 'N' => 14, - 'O' => 15, - 'P' => 16, - 'Q' => 17, - 'R' => 18, - 'S' => 19, - 'T' => 20, - 'U' => 21, - 'V' => 22, - 'W' => 23, - 'X' => 24, - 'Y' => 25, - 'Z' => 26, - ' ' => ' ', - } +module LupineCrypto + class Ceasar + # class variables + private + # hash for letters -> numbers + @@numbers = { + 'A' => 1, + 'B' => 2, + 'C' => 3, + 'D' => 4, + 'E' => 5, + 'F' => 6, + 'G' => 7, + 'H' => 8, + 'I' => 9, + 'J' => 10, + 'K' => 11, + 'L' => 12, + 'M' => 13, + 'N' => 14, + 'O' => 15, + 'P' => 16, + 'Q' => 17, + 'R' => 18, + 'S' => 19, + 'T' => 20, + 'U' => 21, + 'V' => 22, + 'W' => 23, + 'X' => 24, + 'Y' => 25, + 'Z' => 26, + ' ' => ' ', + } + + # array for numbers -> letters + @@letters = [ 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] + + # method for shifting numbers + def shift(numbers, i) + @numbers = numbers.split(',') + @shifted = "" + @numbers.each do |num| + unless num.eql?(' ') + @shifted << (num.to_i + i).to_s + ',' + else + @shifted << ' ,' + end + end + @shifted + end + # method for returning mod 26 + def mod_26(n) + n % 26 + end + + public + # method for letters -> numbers + def to_numbers(input_str) + @alpha_str = input_str + # string of numbers to return + @num_str = "" + @alpha_str.upcase! + + # loop through @alpa_str + @alpha_str.each_char do |c| + #turn letter into number + unless c.eql?(' ') + @num_str << @@numbers[c].to_s + ',' + else + @num_str << ' ,' + end + end + @num_str + end - # array for numbers -> letters - @@letters = [ 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] - - # method for shifting numbers - def shift(numbers, i) - @numbers = numbers.split(',') - @shifted = "" - @numbers.each do |num| - unless num.eql?(' ') - @shifted << (num.to_i + i).to_s + ',' - else - @shifted << ' ,' - end - end - @shifted - end - # method for returning mod 26 - def mod_26(n) - n % 26 - end - - public - # method for letters -> numbers - def to_numbers(input_str) - @alpha_str = input_str - # string of numbers to return - @num_str = "" - @alpha_str.upcase! - - # loop through @alpa_str - @alpha_str.each_char do |c| - #turn letter into number - unless c.eql?(' ') - @num_str << @@numbers[c].to_s + ',' - else - @num_str << ' ,' - end - end - @num_str - end - - # method for numbers -> letters - def to_letters(input_str) - @num_str = input_str.split(',') - - #string of letters to return - @alpha_str = "" - - # loop through num_str + # method for numbers -> letters + def to_letters(input_str) + @num_str = input_str.split(',') + + #string of letters to return + @alpha_str = "" + + # loop through num_str @num_str.each do |c| unless c.eql?(' ') @alpha_str << @@letters[mod_26(c.to_i)] else # char is ' ' @alpha_str << ' ' end end @alpha_str end # method for encrypting letters with shif N def encrypt(plaintext, n) @ciphertext = plaintext puts plaintext #convert to numbers @ciphertext = to_numbers(@ciphertext) #shift numbers n @ciphertext = shift(@ciphertext, n) #convert back to letters @ciphertext = to_letters(@ciphertext) end # method for decrypting letters with shif N def decrypt(ciphertext, j) @plaintext = encrypt(ciphertext, j*(-1)) end + end end diff --git a/lib/lupine_crypto.rb b/lib/lupine_crypto.rb index e69de29..f987bd1 100644 --- a/lib/lupine_crypto.rb +++ b/lib/lupine_crypto.rb @@ -0,0 +1,2 @@ +module LupineCrypto +end
LupineDev/lupine_crypto
087f823e86c3ac4bb23bd8f4b6da056a34c8e483
Basic naked gem skeleton via jeweler
diff --git a/.document b/.document new file mode 100644 index 0000000..3d618dd --- /dev/null +++ b/.document @@ -0,0 +1,5 @@ +lib/**/*.rb +bin/* +- +features/**/*.feature +LICENSE.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2288186 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +# rcov generated +coverage + +# rdoc generated +rdoc + +# yard generated +doc +.yardoc + +# bundler +.bundle + +# jeweler generated +pkg + +# Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore: +# +# * Create a file at ~/.gitignore +# * Include files you want ignored +# * Run: git config --global core.excludesfile ~/.gitignore +# +# After doing this, these files will be ignored in all your git projects, +# saving you from having to 'pollute' every project you touch with them +# +# Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line) +# +# For MacOS: +# +#.DS_Store +# +# For TextMate +#*.tmproj +#tmtags +# +# For emacs: +#*~ +#\#* +#.\#* +# +# For vim: +#*.swp diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..749c7e3 --- /dev/null +++ b/Gemfile @@ -0,0 +1,13 @@ +source "http://rubygems.org" +# Add dependencies required to use your gem here. +# Example: +# gem "activesupport", ">= 2.3.5" + +# Add dependencies to develop your gem here. +# Include everything needed to run rake, tests, features, etc. +group :development do + gem "shoulda", ">= 0" + gem "bundler", "~> 1.0.0" + gem "jeweler", "~> 1.5.1" + gem "rcov", ">= 0" +end diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..45d8019 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2010 LupineDev + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..ddd178a --- /dev/null +++ b/README.rdoc @@ -0,0 +1,19 @@ += lupine_crypto + +Description goes here. + +== Contributing to lupine_crypto + +* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet +* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it +* Fork the project +* Start a feature/bugfix branch +* Commit and push until you are happy with your contribution +* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally. +* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it. + +== Copyright + +Copyright (c) 2010 LupineDev. See LICENSE.txt for +further details. + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..2bc15b2 --- /dev/null +++ b/Rakefile @@ -0,0 +1,53 @@ +require 'rubygems' +require 'bundler' +begin + Bundler.setup(:default, :development) +rescue Bundler::BundlerError => e + $stderr.puts e.message + $stderr.puts "Run `bundle install` to install missing gems" + exit e.status_code +end +require 'rake' + +require 'jeweler' +Jeweler::Tasks.new do |gem| + # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options + gem.name = "lupine_crypto" + gem.homepage = "http://github.com/LupineDev/lupine_crypto" + gem.license = "MIT" + gem.summary = %Q{TODO: one-line summary of your gem} + gem.description = %Q{TODO: longer description of your gem} + gem.email = "[email protected]" + gem.authors = ["LupineDev"] + # Include your dependencies below. Runtime dependencies are required when using your gem, + # and development dependencies are only needed for development (ie running rake tasks, tests, etc) + # gem.add_runtime_dependency 'jabber4r', '> 0.1' + # gem.add_development_dependency 'rspec', '> 1.2.3' +end +Jeweler::RubygemsDotOrgTasks.new + +require 'rake/testtask' +Rake::TestTask.new(:test) do |test| + test.libs << 'lib' << 'test' + test.pattern = 'test/**/test_*.rb' + test.verbose = true +end + +require 'rcov/rcovtask' +Rcov::RcovTask.new do |test| + test.libs << 'test' + test.pattern = 'test/**/test_*.rb' + test.verbose = true +end + +task :default => :test + +require 'rake/rdoctask' +Rake::RDocTask.new do |rdoc| + version = File.exist?('VERSION') ? File.read('VERSION') : "" + + rdoc.rdoc_dir = 'rdoc' + rdoc.title = "lupine_crypto #{version}" + rdoc.rdoc_files.include('README*') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/lib/lupine_crypto.rb b/lib/lupine_crypto.rb new file mode 100644 index 0000000..e69de29 diff --git a/test/helper.rb b/test/helper.rb new file mode 100644 index 0000000..5f81d66 --- /dev/null +++ b/test/helper.rb @@ -0,0 +1,18 @@ +require 'rubygems' +require 'bundler' +begin + Bundler.setup(:default, :development) +rescue Bundler::BundlerError => e + $stderr.puts e.message + $stderr.puts "Run `bundle install` to install missing gems" + exit e.status_code +end +require 'test/unit' +require 'shoulda' + +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) +$LOAD_PATH.unshift(File.dirname(__FILE__)) +require 'lupine_crypto' + +class Test::Unit::TestCase +end diff --git a/test/test_lupine_crypto.rb b/test/test_lupine_crypto.rb new file mode 100644 index 0000000..0a6ecaf --- /dev/null +++ b/test/test_lupine_crypto.rb @@ -0,0 +1,7 @@ +require 'helper' + +class TestLupineCrypto < Test::Unit::TestCase + should "probably rename this file and start testing for real" do + flunk "hey buddy, you should probably rename this file and start testing for real" + end +end
LupineDev/lupine_crypto
1a08b023e343c93e1687e8d2974d1903b9830947
Ceasar you can encrypt/and decrypt withthe ceasar cipher now
diff --git a/README b/README index bb5104c..bada500 100644 --- a/README +++ b/README @@ -1,3 +1,14 @@ This project will contain ruby implementations of various encryption algorithms. Starting with the kiddie ciphers... + +Ceaser cipher has been implemented + +Example +require "lib/ceasar.rb" + +ceasar = Ceasar.new +#encrypt +puts ceasar.encrypt("abcdefg", -2) +puts ceasar.encrypt("hello world", 23) +puts ceasar.decrypt("EBIIL TLOIA", 23) diff --git a/dev_file.rb b/dev_file.rb index 7a6b992..42df519 100644 --- a/dev_file.rb +++ b/dev_file.rb @@ -1,20 +1,8 @@ # This file will be used for early testing require "lib/ceasar.rb" - -#numbers -> letters ceasar = Ceasar.new -puts ceasar.to_numbers("ABCD") -#letters -> numbers - #encrypt -puts ceasar.encrypt("abcdefg", 2) -puts ceasar.encrypt("k", 2) -puts ceasar.encrypt("l", 2) -puts ceasar.encrypt("m", 2) -puts ceasar.encrypt("n", 2) -puts ceasar.encrypt("o", 2) -puts ceasar.encrypt("p", 2) -puts ceasar.encrypt("q", 2) -puts ceasar.encrypt("z", 2) - +puts ceasar.encrypt("abcdefg", -2) +puts ceasar.encrypt("hello world", 23) +puts ceasar.decrypt("EBIIL TLOIA", 23) diff --git a/lib/ceasar.rb b/lib/ceasar.rb index d1ecb46..eb67e0e 100644 --- a/lib/ceasar.rb +++ b/lib/ceasar.rb @@ -1,108 +1,115 @@ class Ceasar # class variables private # hash for letters -> numbers @@numbers = { 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, ' ' => ' ', } # array for numbers -> letters - @@letters = [ ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] + @@letters = [ 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] # method for shifting numbers def shift(numbers, i) - @numbers = numbers + @numbers = numbers.split(',') @shifted = "" - @numbers.each_char do |num| + @numbers.each do |num| unless num.eql?(' ') - @shifted << (num.to_i + i).to_s + @shifted << (num.to_i + i).to_s + ',' else - @shifted << ' ' + @shifted << ' ,' end end @shifted end # method for returning mod 26 def mod_26(n) n % 26 end public # method for letters -> numbers def to_numbers(input_str) @alpha_str = input_str # string of numbers to return @num_str = "" @alpha_str.upcase! # loop through @alpa_str @alpha_str.each_char do |c| #turn letter into number - @num_str << @@numbers[c].to_s + unless c.eql?(' ') + @num_str << @@numbers[c].to_s + ',' + else + @num_str << ' ,' + end end @num_str end # method for numbers -> letters def to_letters(input_str) - @num_str = input_str + @num_str = input_str.split(',') #string of letters to return @alpha_str = "" # loop through num_str - @num_str.each_char do |c| + @num_str.each do |c| unless c.eql?(' ') @alpha_str << @@letters[mod_26(c.to_i)] else # char is ' ' @alpha_str << ' ' end end @alpha_str end # method for encrypting letters with shif N def encrypt(plaintext, n) @ciphertext = plaintext puts plaintext #convert to numbers @ciphertext = to_numbers(@ciphertext) #shift numbers n - #@ciphertext = shift(@ciphertext, n) + @ciphertext = shift(@ciphertext, n) #convert back to letters @ciphertext = to_letters(@ciphertext) end # method for decrypting letters with shif N + def decrypt(ciphertext, j) + @plaintext = encrypt(ciphertext, j*(-1)) + end end
LupineDev/lupine_crypto
efc85be2b62a710198548326b3a300c123ee536e
Began implementing ceasar cipher, broken
diff --git a/README b/README index ac2f1ac..bb5104c 100644 --- a/README +++ b/README @@ -1 +1,3 @@ This project will contain ruby implementations of various encryption algorithms. + +Starting with the kiddie ciphers... diff --git a/dev_file.rb b/dev_file.rb new file mode 100644 index 0000000..7a6b992 --- /dev/null +++ b/dev_file.rb @@ -0,0 +1,20 @@ +# This file will be used for early testing +require "lib/ceasar.rb" + + +#numbers -> letters +ceasar = Ceasar.new +puts ceasar.to_numbers("ABCD") +#letters -> numbers + +#encrypt +puts ceasar.encrypt("abcdefg", 2) +puts ceasar.encrypt("k", 2) +puts ceasar.encrypt("l", 2) +puts ceasar.encrypt("m", 2) +puts ceasar.encrypt("n", 2) +puts ceasar.encrypt("o", 2) +puts ceasar.encrypt("p", 2) +puts ceasar.encrypt("q", 2) +puts ceasar.encrypt("z", 2) + diff --git a/lib/ceasar.rb b/lib/ceasar.rb index 833e1fc..d1ecb46 100644 --- a/lib/ceasar.rb +++ b/lib/ceasar.rb @@ -1,4 +1,108 @@ -class CeasarCipher - # bla - # +class Ceasar + # class variables + private + # hash for letters -> numbers + @@numbers = { + 'A' => 1, + 'B' => 2, + 'C' => 3, + 'D' => 4, + 'E' => 5, + 'F' => 6, + 'G' => 7, + 'H' => 8, + 'I' => 9, + 'J' => 10, + 'K' => 11, + 'L' => 12, + 'M' => 13, + 'N' => 14, + 'O' => 15, + 'P' => 16, + 'Q' => 17, + 'R' => 18, + 'S' => 19, + 'T' => 20, + 'U' => 21, + 'V' => 22, + 'W' => 23, + 'X' => 24, + 'Y' => 25, + 'Z' => 26, + ' ' => ' ', + } + + # array for numbers -> letters + @@letters = [ ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] + + # method for shifting numbers + def shift(numbers, i) + @numbers = numbers + @shifted = "" + @numbers.each_char do |num| + unless num.eql?(' ') + @shifted << (num.to_i + i).to_s + else + @shifted << ' ' + end + end + @shifted + end + # method for returning mod 26 + def mod_26(n) + n % 26 + end + + public + # method for letters -> numbers + def to_numbers(input_str) + @alpha_str = input_str + # string of numbers to return + @num_str = "" + @alpha_str.upcase! + + # loop through @alpa_str + @alpha_str.each_char do |c| + #turn letter into number + @num_str << @@numbers[c].to_s + end + @num_str + end + + # method for numbers -> letters + def to_letters(input_str) + @num_str = input_str + + #string of letters to return + @alpha_str = "" + + # loop through num_str + @num_str.each_char do |c| + unless c.eql?(' ') + @alpha_str << @@letters[mod_26(c.to_i)] + else + # char is ' ' + @alpha_str << ' ' + end + end + @alpha_str + end + + + # method for encrypting letters with shif N + def encrypt(plaintext, n) + @ciphertext = plaintext + puts plaintext + #convert to numbers + @ciphertext = to_numbers(@ciphertext) + + #shift numbers n + #@ciphertext = shift(@ciphertext, n) + + #convert back to letters + @ciphertext = to_letters(@ciphertext) + end + + # method for decrypting letters with shif N + end
actsasflinn/cache-contrib
d3f97fa0457dc3b72e9d342ad423cb69de60926d
add reset for Passenger cache fork
diff --git a/lib/active_support/cache/memcached_store.rb b/lib/active_support/cache/memcached_store.rb index 2902466..52965e8 100644 --- a/lib/active_support/cache/memcached_store.rb +++ b/lib/active_support/cache/memcached_store.rb @@ -1,95 +1,99 @@ require 'memcached' module ActiveSupport module Cache class MemcachedStore < Store attr_reader :addresses def initialize(*addresses) addresses = addresses.flatten options = addresses.extract_options! addresses = ["localhost"] if addresses.empty? @addresses = addresses @data = Memcached::Rails.new(addresses, options) extend Strategy::LocalCache end def read(key, options = nil) super @data.get(key, raw?(options)) rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") nil end # Set key = value. Pass :unless_exist => true if you don't # want to update the cache if the key is already set. def write(key, value, options = nil) super method = options && options[:unless_exist] ? :add : :set response = @data.send(method, key, value, expires_in(options), raw?(options)) response == nil rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") false end def delete(key, options = nil) super response = @data.delete(key) response == nil rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") false end def exist?(key, options = nil) # Doesn't call super, cause exist? in memcache is in fact a read # But who cares? Reading is very fast anyway !read(key, options).nil? end def increment(key, amount = 1) log("incrementing", key, amount) @data.incr(key, amount) rescue Memcached::Error nil end def decrement(key, amount = 1) log("decrement", key, amount) @data.decr(key, amount) rescue Memcached::Error nil end def delete_matched(matcher, options = nil) super raise "Not supported by Memcache" end def clear @data.respond_to?(:flush_all) ? @data.flush_all : @data.flush end def stats @data.stats end + def reset + @data.reset + end + private def expires_in(options) (options && options[:expires_in]) || 0 end def raw?(options) options && options[:raw] end # TODO: Remove these if they ever make it into core include ActiveSupport::Cache::Patches::AutoLoadMissingConstants include ActiveSupport::Cache::Patches::DefaultExpiresIn end end end
actsasflinn/cache-contrib
9fe8602630ff753592b0f1328c1438c69ed844f5
add local cache strategy
diff --git a/lib/active_support/cache/memcached_store.rb b/lib/active_support/cache/memcached_store.rb index c1c4c0f..2902466 100644 --- a/lib/active_support/cache/memcached_store.rb +++ b/lib/active_support/cache/memcached_store.rb @@ -1,94 +1,95 @@ require 'memcached' module ActiveSupport module Cache class MemcachedStore < Store attr_reader :addresses def initialize(*addresses) addresses = addresses.flatten options = addresses.extract_options! addresses = ["localhost"] if addresses.empty? @addresses = addresses @data = Memcached::Rails.new(addresses, options) + extend Strategy::LocalCache end def read(key, options = nil) super @data.get(key, raw?(options)) rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") nil end # Set key = value. Pass :unless_exist => true if you don't # want to update the cache if the key is already set. def write(key, value, options = nil) super method = options && options[:unless_exist] ? :add : :set response = @data.send(method, key, value, expires_in(options), raw?(options)) response == nil rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") false end def delete(key, options = nil) super response = @data.delete(key) response == nil rescue Memcached::Error => e logger.error("Memcached::Error (#{e}): #{e.message}") false end def exist?(key, options = nil) # Doesn't call super, cause exist? in memcache is in fact a read # But who cares? Reading is very fast anyway !read(key, options).nil? end def increment(key, amount = 1) log("incrementing", key, amount) @data.incr(key, amount) rescue Memcached::Error nil end def decrement(key, amount = 1) log("decrement", key, amount) @data.decr(key, amount) rescue Memcached::Error nil end def delete_matched(matcher, options = nil) super raise "Not supported by Memcache" end def clear @data.respond_to?(:flush_all) ? @data.flush_all : @data.flush end def stats @data.stats end private def expires_in(options) (options && options[:expires_in]) || 0 end def raw?(options) options && options[:raw] end # TODO: Remove these if they ever make it into core include ActiveSupport::Cache::Patches::AutoLoadMissingConstants include ActiveSupport::Cache::Patches::DefaultExpiresIn end end end
actsasflinn/cache-contrib
bf5b91b402227d695962e55bee741d0afc7908b2
fix for default expire
diff --git a/lib/active_support/cache/patches/default_expires_in.rb b/lib/active_support/cache/patches/default_expires_in.rb index 1fa4099..1394cb0 100644 --- a/lib/active_support/cache/patches/default_expires_in.rb +++ b/lib/active_support/cache/patches/default_expires_in.rb @@ -1,17 +1,17 @@ module ActiveSupport module Cache module Patches module DefaultExpiresIn def self.included(base) super base.send(:attr_accessor, :expires_in) base.send(:alias_method_chain, :expires_in, :default_value) end def expires_in_with_default_value(options) - ((options && options[:expires_in]) || @expires_in).to_i + (options && options.include?(:expires_in) ? options[:expires_in] : @expires_in).to_i end end end end end
actsasflinn/cache-contrib
c0ee99b711c762d2f352656e6b2c79828374a9fa
add memcached session store
diff --git a/lib/action_controller/session/memcached_store.rb b/lib/action_controller/session/memcached_store.rb new file mode 100644 index 0000000..93bbcf3 --- /dev/null +++ b/lib/action_controller/session/memcached_store.rb @@ -0,0 +1,51 @@ +begin + require_library_or_gem 'memcached' + + module ActionController + module Session + class MemcachedStore < AbstractStore + def initialize(app, options = {}) + # Support old :expires option + options[:expire_after] ||= options[:expires] + + super + + @default_options = { + :namespace => 'rack:session', + :memcache_server => 'localhost:11211' + }.merge(@default_options) + + @pool = options[:cache] || Rails::Memcached.new(@default_options[:memcache_server], @default_options) +# unless @pool.servers.any? { |s| s.alive? } +# raise "#{self} unable to find server during initialization." +# end + @mutex = Mutex.new + + super + end + + private + def get_session(env, sid) + sid ||= generate_sid + begin + session = @pool.get(sid) || {} + rescue Memcached::Error, Errno::ECONNREFUSED + session = {} + end + [sid, session] + end + + def set_session(env, sid, session_data) + options = env['rack.session.options'] + expiry = options[:expire_after] || 0 + @pool.set(sid, session_data, expiry) + return true + rescue Memcached::Error, Errno::ECONNREFUSED + return false + end + end + end + end +rescue LoadError + # MemCache wasn't available so neither can the store be +end
actsasflinn/cache-contrib
d86d3d3a1df9efcedc5ddd252e3318d2c0ccb49e
try to load memcache before trying to patch
diff --git a/init.rb b/init.rb index 119b5bb..7955261 100644 --- a/init.rb +++ b/init.rb @@ -1,30 +1,35 @@ # Fixes for memcache -require 'memcache/make_cache_key_with_underscore' -require 'memcache/timeout' +begin + require 'memcache' + require 'memcache/make_cache_key_with_underscore' + require 'memcache/timeout' +rescue LoadError + puts $stderr.puts "memcache-client not installed, skipping patches" +end # Add a default expires_in value for cache stores that use it require 'active_support/cache/patches/default_expires_in' # Fix to autoload missing classes with unmarshaling require 'active_support/cache/patches/auto_load_missing_constants' # Fix for fetch when cache_classes is false require 'active_support/cache/patches/dependency_load_fix' module ActiveSupport::Cache # Make :memcached_store available for use autoload :MemcachedStore, 'active_support/cache/memcached_store' class Store # Add to base even though non-memcached formats don't support it, # it's an ugly workaround for the fact that plugins are loaded after initialize_cache attr_writer :expires_in include Patches::DependencyLoadFix if ActiveSupport::Dependencies.mechanism == :load end class MemCacheStore < Store include Patches::AutoLoadMissingConstants include Patches::DefaultExpiresIn end end
actsasflinn/cache-contrib
a60ea82bf7585e60a4133950f8c24949ac25bd54
resolve namespace issue
diff --git a/init.rb b/init.rb index aaa6de7..119b5bb 100644 --- a/init.rb +++ b/init.rb @@ -1,30 +1,30 @@ # Fixes for memcache require 'memcache/make_cache_key_with_underscore' require 'memcache/timeout' # Add a default expires_in value for cache stores that use it require 'active_support/cache/patches/default_expires_in' # Fix to autoload missing classes with unmarshaling require 'active_support/cache/patches/auto_load_missing_constants' # Fix for fetch when cache_classes is false require 'active_support/cache/patches/dependency_load_fix' module ActiveSupport::Cache # Make :memcached_store available for use autoload :MemcachedStore, 'active_support/cache/memcached_store' class Store # Add to base even though non-memcached formats don't support it, # it's an ugly workaround for the fact that plugins are loaded after initialize_cache attr_writer :expires_in - include Patches::DependencyLoadFix if Dependencies.mechanism == :load + include Patches::DependencyLoadFix if ActiveSupport::Dependencies.mechanism == :load end class MemCacheStore < Store include Patches::AutoLoadMissingConstants include Patches::DefaultExpiresIn end end
actsasflinn/cache-contrib
30ebdcef0aec2216d53f5eec757a14159fa20215
initial import, extracted from github.com/actsasflinn/snippy
diff --git a/README b/README new file mode 100644 index 0000000..c69b34f --- /dev/null +++ b/README @@ -0,0 +1,7 @@ += CacheContrib + +A collection of patches and extensions for dealing with caching for use with Rails. + +== License + +Unless otherwise noted the files are pubic domain. \ No newline at end of file diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..aaa6de7 --- /dev/null +++ b/init.rb @@ -0,0 +1,30 @@ +# Fixes for memcache +require 'memcache/make_cache_key_with_underscore' +require 'memcache/timeout' + +# Add a default expires_in value for cache stores that use it +require 'active_support/cache/patches/default_expires_in' + +# Fix to autoload missing classes with unmarshaling +require 'active_support/cache/patches/auto_load_missing_constants' + +# Fix for fetch when cache_classes is false +require 'active_support/cache/patches/dependency_load_fix' + +module ActiveSupport::Cache + # Make :memcached_store available for use + autoload :MemcachedStore, 'active_support/cache/memcached_store' + + class Store + # Add to base even though non-memcached formats don't support it, + # it's an ugly workaround for the fact that plugins are loaded after initialize_cache + attr_writer :expires_in + + include Patches::DependencyLoadFix if Dependencies.mechanism == :load + end + + class MemCacheStore < Store + include Patches::AutoLoadMissingConstants + include Patches::DefaultExpiresIn + end +end diff --git a/install.rb b/install.rb new file mode 100644 index 0000000..bd23f1b --- /dev/null +++ b/install.rb @@ -0,0 +1 @@ +puts IO.read(File.join(File.dirname(__FILE__), 'README')) diff --git a/lib/active_support/cache/memcached_store.rb b/lib/active_support/cache/memcached_store.rb new file mode 100644 index 0000000..c1c4c0f --- /dev/null +++ b/lib/active_support/cache/memcached_store.rb @@ -0,0 +1,94 @@ +require 'memcached' + +module ActiveSupport + module Cache + class MemcachedStore < Store + attr_reader :addresses + + def initialize(*addresses) + addresses = addresses.flatten + options = addresses.extract_options! + addresses = ["localhost"] if addresses.empty? + @addresses = addresses + @data = Memcached::Rails.new(addresses, options) + end + + def read(key, options = nil) + super + @data.get(key, raw?(options)) + rescue Memcached::Error => e + logger.error("Memcached::Error (#{e}): #{e.message}") + nil + end + + # Set key = value. Pass :unless_exist => true if you don't + # want to update the cache if the key is already set. + def write(key, value, options = nil) + super + method = options && options[:unless_exist] ? :add : :set + response = @data.send(method, key, value, expires_in(options), raw?(options)) + response == nil + rescue Memcached::Error => e + logger.error("Memcached::Error (#{e}): #{e.message}") + false + end + + def delete(key, options = nil) + super + response = @data.delete(key) + response == nil + rescue Memcached::Error => e + logger.error("Memcached::Error (#{e}): #{e.message}") + false + end + + def exist?(key, options = nil) + # Doesn't call super, cause exist? in memcache is in fact a read + # But who cares? Reading is very fast anyway + !read(key, options).nil? + end + + def increment(key, amount = 1) + log("incrementing", key, amount) + + @data.incr(key, amount) + rescue Memcached::Error + nil + end + + def decrement(key, amount = 1) + log("decrement", key, amount) + + @data.decr(key, amount) + rescue Memcached::Error + nil + end + + def delete_matched(matcher, options = nil) + super + raise "Not supported by Memcache" + end + + def clear + @data.respond_to?(:flush_all) ? @data.flush_all : @data.flush + end + + def stats + @data.stats + end + + private + def expires_in(options) + (options && options[:expires_in]) || 0 + end + + def raw?(options) + options && options[:raw] + end + + # TODO: Remove these if they ever make it into core + include ActiveSupport::Cache::Patches::AutoLoadMissingConstants + include ActiveSupport::Cache::Patches::DefaultExpiresIn + end + end +end diff --git a/lib/active_support/cache/patches/auto_load_missing_constants.rb b/lib/active_support/cache/patches/auto_load_missing_constants.rb new file mode 100644 index 0000000..2be6067 --- /dev/null +++ b/lib/active_support/cache/patches/auto_load_missing_constants.rb @@ -0,0 +1,27 @@ +# Copyright (c) 2007 Chris Wanstrath +module ActiveSupport + module Cache + module Patches + module AutoLoadMissingConstants + def self.included(base) + super + base.alias_method_chain :read, :auto_load + end + + def autoload_missing_constants + yield + rescue ArgumentError, MemCache::MemCacheError => error + lazy_load ||= Hash.new { |hash, hash_key| hash[hash_key] = true; false } + if error.to_s[/undefined class|referred/] && !lazy_load[error.to_s.split.last.constantize] then retry + else raise error end + end + + def read_with_auto_load(*args) + autoload_missing_constants do + read_without_auto_load(*args) + end + end + end + end + end +end \ No newline at end of file diff --git a/lib/active_support/cache/patches/default_expires_in.rb b/lib/active_support/cache/patches/default_expires_in.rb new file mode 100644 index 0000000..1fa4099 --- /dev/null +++ b/lib/active_support/cache/patches/default_expires_in.rb @@ -0,0 +1,17 @@ +module ActiveSupport + module Cache + module Patches + module DefaultExpiresIn + def self.included(base) + super + base.send(:attr_accessor, :expires_in) + base.send(:alias_method_chain, :expires_in, :default_value) + end + + def expires_in_with_default_value(options) + ((options && options[:expires_in]) || @expires_in).to_i + end + end + end + end +end diff --git a/lib/active_support/cache/patches/dependency_load_fix.rb b/lib/active_support/cache/patches/dependency_load_fix.rb new file mode 100644 index 0000000..e00d426 --- /dev/null +++ b/lib/active_support/cache/patches/dependency_load_fix.rb @@ -0,0 +1,21 @@ +# Fix fetch caching when using :load for dependencies (cache_classes = false) +# This fixes cache calls (due to class reloading in dev) by simply calling the fetch block +# Parts taken from http://blog.bashme.org/2008/07/25/rails-21-model-caching-issue/ and +# http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching#comment-1171 +# +module ActiveSupport + module Cache + module Patches + module DependencyLoadFix + def self.included(base) + super + base.alias_method_chain :fetch, :dependency_load_fix + end + + def fetch_with_dependency_load_fix(*arguments) + block_given? ? yield : fetch_without_dependency_load_fix(*arguments) + end + end + end + end +end diff --git a/lib/memcache/make_cache_key_with_underscore.rb b/lib/memcache/make_cache_key_with_underscore.rb new file mode 100644 index 0000000..1758739 --- /dev/null +++ b/lib/memcache/make_cache_key_with_underscore.rb @@ -0,0 +1,7 @@ +# Ensure cache keys do not contain spaces +class MemCache + def make_cache_key_with_underscore(key) + make_cache_key_without_underscore(key.gsub(' ', '_')) + end + alias_method_chain :make_cache_key, :underscore +end \ No newline at end of file diff --git a/lib/memcache/timeout.rb b/lib/memcache/timeout.rb new file mode 100644 index 0000000..90cb719 --- /dev/null +++ b/lib/memcache/timeout.rb @@ -0,0 +1,60 @@ +# Fix for infinite waits on TCP Socket timeouts +# From http://blog.rapleaf.com/dev/?p=14 +require "timeout" + +class MemCache + alias_method :old_get, :get + alias_method :old_set, :set + alias_method :old_incr, :incr + alias_method :old_add, :add + alias_method :old_delete, :delete + alias_method :old_get_multi, :get_multi + + def get(key, raw = false, timeout = 1.0) + Timeout::timeout(timeout) do + old_get(key, raw) + end + rescue Timeout::Error + nil + end + + def set(key, value, expiry = 0, raw = false, timeout = 1.0) + Timeout::timeout(timeout) do + old_set(key, value, expiry, raw) + end + end + + def incr(key, amount = 1, timeout = 1.0) + Timeout::timeout(timeout) do + old_incr(key, amount) + end + end + + def add(key, value, expiry = 0, raw = false, timeout = 1.0) + Timeout::timeout(timeout) do + old_add(key, value, expiry, raw) + end + end + + def delete(key, expiry = 0, timeout = 1.0) + Timeout::timeout(timeout) do + old_delete(key, expiry) + end + end + + def get_multi(*args) + if args.last.is_a?(Float) || args.last.is_a?(Fixnum) + # assume it's a timeout + timeout = args.pop + Timeout::timeout(timeout) do + old_get_multi(*args) + end + else + Timeout::timeout(15) do + old_get_multi(*args) + end + end + rescue Timeout::Error + {} + end +end \ No newline at end of file
smith/namespacedotjs
a28da387ceaf36f86a339803fd850c58fdf27779
Fixed IE loading
diff --git a/Namespace.js b/Namespace.js index 0fb2848..faf1c56 100644 --- a/Namespace.js +++ b/Namespace.js @@ -1,498 +1,500 @@ /* Script: Namespace.js Namespace utility Copyright: Copyright (c) 2009 Maxime Bouroumeau-Fuseau License: MIT-style license. Version: 1.1 */ /*jslint evil : true */ /*global Namespace, XMLHttpRequest, ActiveXObject, window, document */ var Namespace = (function() { var _listeners = {}; var _includedIdentifiers = []; /** * Returns an object in an array unless the object is an array * * @param mixed obj * @return Array */ var _toArray = function(obj) { // checks if it's an array if (typeof(obj) == 'object' && obj.sort) { return obj; } return Array(obj); }; /** * Creates an XMLHttpRequest object * * @return XMLHttpRequest */ var _createXmlHttpRequest = function() { var xhr; try { xhr = new XMLHttpRequest(); } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e2) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e3) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e4) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e5) { throw new Error( "This browser does not support XMLHttpRequest." ); } } } } } return xhr; }; /** * Checks if an http request is successful based on its status code. * Borrowed from dojo (http://www.dojotoolkit.org). * * @param Integer status Http status code * @return Boolean */ var _isHttpRequestSuccessful = function(status) { return (status >= 200 && status < 300) || // Boolean status == 304 || // allow any 2XX response code status == 1223 || // get it out of the cache (!status && (window.location.protocol == "file:" || window.location.protocol == "chrome:") ); // Internet Explorer mangled the status code }; /** * Creates a script tag with the specified data as content * * @param String data The content of the script */ var _createScript = function(data) { var script = document.createElement('script'); script.type = 'text/javascript'; script.text = data; - try { // Attempt body insertion - document.body.appendChild(script); - } catch (e) { // Fall back on eval - if (typeof window.execScript === "function") { - window.execScript(data); - } else { window['eval'](data); } + if (typeof window.execScript === "object") { // According to IE + window.execScript(data); + } else { + try { // Attempt body insertion + document.body.appendChild(script); + } catch (e) { // Fall back on eval + window['eval'](data); + } } }; /** * Dispatches an event * * @param String eventName * @param Object properties */ var _dispatchEvent = function(eventName, properties) { if (!_listeners[eventName]) { return; } properties.event = eventName; for (var i = 0; i < _listeners[eventName].length; i++) { _listeners[eventName][i](properties); } }; /** * Creates an Object following the specified namespace identifier. * * @public * @param String identifier The namespace string * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace * @return Object The most inner object */ var _namespace = function(identifier) { var klasses = arguments[1] || false; var ns = window; if (identifier !== '') { var parts = identifier.split(Namespace.separator); for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { ns[parts[i]] = {}; } ns = ns[parts[i]]; } } if (klasses) { for (var klass in klasses) { if (klasses.hasOwnProperty(klass)) { ns[klass] = klasses[klass]; } } } _dispatchEvent('create', { 'identifier': identifier }); return ns; }; /** * Checks if the specified identifier is defined * * @public * @param String identifier The namespace string * @return Boolean */ _namespace.exist = function(identifier) { if (identifier === '') { return true; } var parts = identifier.split(Namespace.separator); var ns = window; for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { return false; } ns = ns[parts[i]]; } return true; }; /** * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. * * @public * @param String identifier The namespace identifier * @return String The uri */ _namespace.mapIdentifierToUri = function(identifier) { var regexp = new RegExp('\\' + Namespace.separator, 'g'); return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; }; /** * Loads a remote script atfer mapping the identifier to an uri * * @param String identifier The namespace identifier * @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded * @param Function errorCallback Callback to be called when an error occurs * @return Boolean Success of failure when loading synchronously */ var _loadScript = function(identifier) { var successCallback = arguments[1]; var errorCallback = arguments[2]; var async = typeof successCallback === "function"; var uri = _namespace.mapIdentifierToUri(identifier); var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback }; var xhr = _createXmlHttpRequest(); xhr.open("GET", uri, async); if (async) { xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); successCallback(); return; } event.status = xhr.status; _dispatchEvent('includeError', event); if (typeof errorCallback === "function") { errorCallback(); } } }; } xhr.send(null); if (!async) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); return true; } event.status = xhr.status; _dispatchEvent('includeError', event); return false; } }; /** * Includes a remote javascript file identified by the specified namespace string. The identifier * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the remote script has been included */ _namespace.include = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; // checks if the identifier is not already included if (_includedIdentifiers[identifier]) { if (typeof successCallback === "function") { successCallback(); } return true; } if (successCallback) { _loadScript(identifier, function() { _includedIdentifiers[identifier] = true; successCallback(); }, errorCallback); } else { if (_loadScript(identifier)) { _includedIdentifiers[identifier] = true; return true; } return false; } }; /** * Imports properties from the specified namespace to the global space (ie. under window) * * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) * which will import all properties from the namespace. * * If not, the targeted namespace will be imported (ie. if com.test is imported, the test object * will now be global). If the targeted object is not found, it will be included using include(). * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude */ _namespace.use = function(identifier) { var identifiers = _toArray(identifier); var callback = arguments[1] || false; var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; var event = { 'identifier': identifier }; var parts, target, ns; for (var i = 0; i < identifiers.length; i++) { identifier = identifiers[i]; parts = identifier.split(Namespace.separator); target = parts.pop(); ns = _namespace(parts.join(Namespace.separator)); if (target == '*') { // imports all objects from the identifier, can't use include() in that case for (var objectName in ns) { if (ns.hasOwnProperty(objectName)) { window[objectName] = ns[objectName]; } } } else { // imports only one object if (ns[target]) { // the object exists, import it window[target] = ns[target]; } else { // the object does not exist if (autoInclude) { // try to auto include it if (callback) { _namespace.include(identifier, function() { window[target] = ns[target]; if (i + 1 < identifiers.length) { // we continue to unpack the rest from here _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); } else { // no more identifiers to unpack _dispatchEvent('use', event); if (typeof callback === "function") { callback(); } } }); return; } else { _namespace.include(identifier); window[target] = ns[target]; } } } } } // all identifiers have been unpacked _dispatchEvent('use', event); if (typeof callback === "function") { callback(); } }; /** * Binds the include() and unpack() method to a specified identifier * * @public * @param String identifier The namespace identifier * @return Object */ _namespace.from = function(identifier) { return { /** * Includes the identifier specified in from() * * @see Namespace.include() */ include: function() { var callback = arguments[0] || false; _namespace.include(identifier, callback); }, /** * Includes the identifier specified in from() and unpack * the specified indentifier in _identifier * * @see Namespace.use() */ use: function(_identifier) { var callback = arguments[1] || false; if (_identifier.charAt(0) == '.') { _identifier = identifier + _identifier; } if (callback) { _namespace.include(identifier, function() { _namespace.use(_identifier, callback, false); }); } else { _namespace.include(identifier); _namespace.use(_identifier, callback, false); } } }; }; /** * Registers a namespace so it won't be included * * Idea and code submitted by Nathan Smith (http://github.com/smith) * * @param String|Array identifier */ _namespace.provide = function(identifier) { var identifiers = _toArray(identifier); for (var i = 0; i < identifiers.length; i++) { if (!(identifier in _includedIdentifiers)) { _dispatchEvent('provide', { 'identifier': identifier }); _includedIdentifiers[identifier] = true; } } }; /** * Registers a function to be called when the specified event is dispatched * * @param String eventName * @param Function callback */ _namespace.addEventListener = function(eventName, callback) { if (!_listeners[eventName]) { _listeners[eventName] = []; } _listeners[eventName].push(callback); }; /** * Unregisters an event listener * * @param String eventName * @param Function callback */ _namespace.removeEventListener = function(eventName, callback) { if (!_listeners[eventName]) { return; } for (var i = 0; i < _listeners[eventName].length; i++) { if (_listeners[eventName][i] == callback) { delete _listeners[eventName][i]; return; } } }; /** * Adds methods to javascript native's object * Inspired by http://thinkweb2.com/projects/prototype/namespacing-made-easy/ * * @public */ _namespace.registerNativeExtensions = function() { /** * @see Namespace() */ String.prototype.namespace = function() { var klasses = arguments[0] || {}; return _namespace(this.valueOf(), klasses); }; /** * @see Namespace.include() */ String.prototype.include = function() { var callback = arguments[0] || false; return _namespace.include(this.valueOf(), callback); }; /** * @see Namespace.use() */ String.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this.valueOf(), callback); }; /** * @see Namespace.from() */ String.prototype.from = function() { return _namespace.from(this.valueOf()); }; /** * @see Namespace.provide() * Idea and code submitted by Nathan Smith (http://github.com/smith) */ String.prototype.provide = function() { return _namespace.provide(this.valueOf()); }; /** * @see Namespace.use() */ Array.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this, callback); }; /** * @see Namespace.provide() */ Array.prototype.provide = function() { return _namespace.provide(this); }; }; return _namespace; })(); /** * Namespace segment separator * * @var String */ Namespace.separator = '.'; /** * Base uri when using Namespace.include() * Must end with a slash * * @var String */ Namespace.baseUri = './'; /** * Whether to automatically call Namespace.include() when Namespace.import() * does not find the targeted object. * * @var Boolean */ Namespace.autoInclude = true;
smith/namespacedotjs
356cc77d26a1d314f69d0fd357d9c2886fbecbae
JSLint fixes
diff --git a/Namespace.js b/Namespace.js index 7f93d23..0fb2848 100644 --- a/Namespace.js +++ b/Namespace.js @@ -1,485 +1,498 @@ /* Script: Namespace.js Namespace utility Copyright: Copyright (c) 2009 Maxime Bouroumeau-Fuseau License: MIT-style license. Version: 1.1 */ + +/*jslint evil : true */ +/*global Namespace, XMLHttpRequest, ActiveXObject, window, document */ + var Namespace = (function() { var _listeners = {}; var _includedIdentifiers = []; /** * Returns an object in an array unless the object is an array * * @param mixed obj * @return Array */ var _toArray = function(obj) { // checks if it's an array if (typeof(obj) == 'object' && obj.sort) { return obj; } - return new Array(obj); + return Array(obj); }; /** * Creates an XMLHttpRequest object * * @return XMLHttpRequest */ var _createXmlHttpRequest = function() { var xhr; - try { xhr = new XMLHttpRequest() } catch(e) { - try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) { - try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) { - try { xhr = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) { - try { xhr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) { - throw new Error( "This browser does not support XMLHttpRequest." ) + try { xhr = new XMLHttpRequest(); } catch(e) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e2) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e3) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e4) { + try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e5) { + throw new Error( "This browser does not support XMLHttpRequest." ); } } } } } return xhr; }; /** * Checks if an http request is successful based on its status code. * Borrowed from dojo (http://www.dojotoolkit.org). * * @param Integer status Http status code * @return Boolean */ var _isHttpRequestSuccessful = function(status) { return (status >= 200 && status < 300) || // Boolean status == 304 || // allow any 2XX response code status == 1223 || // get it out of the cache - (!status && (location.protocol == "file:" || location.protocol == "chrome:") ); // Internet Explorer mangled the status code + (!status && (window.location.protocol == "file:" || window.location.protocol == "chrome:") ); // Internet Explorer mangled the status code }; /** * Creates a script tag with the specified data as content * * @param String data The content of the script */ var _createScript = function(data) { var script = document.createElement('script'); script.type = 'text/javascript'; script.text = data; try { // Attempt body insertion document.body.appendChild(script); } catch (e) { // Fall back on eval if (typeof window.execScript === "function") { window.execScript(data); - } else { window.eval(data); } + } else { window['eval'](data); } } }; /** * Dispatches an event * * @param String eventName * @param Object properties */ var _dispatchEvent = function(eventName, properties) { - if (!_listeners[eventName]) return; + if (!_listeners[eventName]) { return; } properties.event = eventName; for (var i = 0; i < _listeners[eventName].length; i++) { _listeners[eventName][i](properties); } }; /** * Creates an Object following the specified namespace identifier. * * @public * @param String identifier The namespace string * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace * @return Object The most inner object */ var _namespace = function(identifier) { var klasses = arguments[1] || false; var ns = window; - if (identifier != '') { + if (identifier !== '') { var parts = identifier.split(Namespace.separator); for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { ns[parts[i]] = {}; } ns = ns[parts[i]]; } } if (klasses) { for (var klass in klasses) { - ns[klass] = klasses[klass]; + if (klasses.hasOwnProperty(klass)) { + ns[klass] = klasses[klass]; + } } } _dispatchEvent('create', { 'identifier': identifier }); return ns; }; /** * Checks if the specified identifier is defined * * @public * @param String identifier The namespace string * @return Boolean */ _namespace.exist = function(identifier) { - if (identifier == '') return true; + if (identifier === '') { return true; } var parts = identifier.split(Namespace.separator); var ns = window; for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { return false; } ns = ns[parts[i]]; } return true; }; /** * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. * * @public * @param String identifier The namespace identifier * @return String The uri */ _namespace.mapIdentifierToUri = function(identifier) { var regexp = new RegExp('\\' + Namespace.separator, 'g'); return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; }; /** * Loads a remote script atfer mapping the identifier to an uri * * @param String identifier The namespace identifier * @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded * @param Function errorCallback Callback to be called when an error occurs * @return Boolean Success of failure when loading synchronously */ - _loadScript = function(identifier) { - var successCallback = arguments[1] || false; - var errorCallback = arguments[2] || false; - var async = successCallback != false; + var _loadScript = function(identifier) { + var successCallback = arguments[1]; + var errorCallback = arguments[2]; + var async = typeof successCallback === "function"; var uri = _namespace.mapIdentifierToUri(identifier); var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback }; var xhr = _createXmlHttpRequest(); xhr.open("GET", uri, async); if (async) { xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); successCallback(); return; } event.status = xhr.status; _dispatchEvent('includeError', event); - errorCallback && errorCallback(); + if (typeof errorCallback === "function") { + errorCallback(); + } } }; } xhr.send(null); if (!async) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); return true; } event.status = xhr.status; _dispatchEvent('includeError', event); return false; } }; /** * Includes a remote javascript file identified by the specified namespace string. The identifier * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the remote script has been included */ _namespace.include = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; // checks if the identifier is not already included if (_includedIdentifiers[identifier]) { - successCallback && successCallback(); + if (typeof successCallback === "function") { successCallback(); } return true; } if (successCallback) { _loadScript(identifier, function() { _includedIdentifiers[identifier] = true; successCallback(); }, errorCallback); } else { if (_loadScript(identifier)) { _includedIdentifiers[identifier] = true; return true; } return false; } }; /** * Imports properties from the specified namespace to the global space (ie. under window) * * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) * which will import all properties from the namespace. * * If not, the targeted namespace will be imported (ie. if com.test is imported, the test object * will now be global). If the targeted object is not found, it will be included using include(). * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude */ _namespace.use = function(identifier) { var identifiers = _toArray(identifier); var callback = arguments[1] || false; var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; var event = { 'identifier': identifier }; + var parts, target, ns; for (var i = 0; i < identifiers.length; i++) { identifier = identifiers[i]; - var parts = identifier.split(Namespace.separator); - var target = parts.pop(); - var ns = _namespace(parts.join(Namespace.separator)); + parts = identifier.split(Namespace.separator); + target = parts.pop(); + ns = _namespace(parts.join(Namespace.separator)); if (target == '*') { // imports all objects from the identifier, can't use include() in that case for (var objectName in ns) { - window[objectName] = ns[objectName]; + if (ns.hasOwnProperty(objectName)) { + window[objectName] = ns[objectName]; + } } } else { // imports only one object if (ns[target]) { // the object exists, import it window[target] = ns[target]; } else { // the object does not exist if (autoInclude) { // try to auto include it if (callback) { _namespace.include(identifier, function() { window[target] = ns[target]; if (i + 1 < identifiers.length) { // we continue to unpack the rest from here _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); } else { // no more identifiers to unpack _dispatchEvent('use', event); - callback && callback(); + if (typeof callback === "function") { + callback(); + } } }); return; } else { _namespace.include(identifier); window[target] = ns[target]; } } } } } // all identifiers have been unpacked _dispatchEvent('use', event); - callback && callback(); + if (typeof callback === "function") { callback(); } }; /** * Binds the include() and unpack() method to a specified identifier * * @public * @param String identifier The namespace identifier * @return Object */ _namespace.from = function(identifier) { return { /** * Includes the identifier specified in from() * * @see Namespace.include() */ include: function() { var callback = arguments[0] || false; _namespace.include(identifier, callback); }, /** * Includes the identifier specified in from() and unpack * the specified indentifier in _identifier * * @see Namespace.use() */ use: function(_identifier) { var callback = arguments[1] || false; if (_identifier.charAt(0) == '.') { _identifier = identifier + _identifier; } if (callback) { _namespace.include(identifier, function() { _namespace.use(_identifier, callback, false); }); } else { _namespace.include(identifier); _namespace.use(_identifier, callback, false); } } }; }; /** * Registers a namespace so it won't be included * * Idea and code submitted by Nathan Smith (http://github.com/smith) * * @param String|Array identifier */ _namespace.provide = function(identifier) { var identifiers = _toArray(identifier); for (var i = 0; i < identifiers.length; i++) { if (!(identifier in _includedIdentifiers)) { _dispatchEvent('provide', { 'identifier': identifier }); _includedIdentifiers[identifier] = true; } } }; /** * Registers a function to be called when the specified event is dispatched * * @param String eventName * @param Function callback */ _namespace.addEventListener = function(eventName, callback) { - if (!_listeners[eventName]) _listeners[eventName] = []; + if (!_listeners[eventName]) { _listeners[eventName] = []; } _listeners[eventName].push(callback); }; /** * Unregisters an event listener * * @param String eventName * @param Function callback */ _namespace.removeEventListener = function(eventName, callback) { - if (!_listeners[eventName]) return; + if (!_listeners[eventName]) { return; } for (var i = 0; i < _listeners[eventName].length; i++) { if (_listeners[eventName][i] == callback) { delete _listeners[eventName][i]; return; } } }; /** * Adds methods to javascript native's object * Inspired by http://thinkweb2.com/projects/prototype/namespacing-made-easy/ * * @public */ _namespace.registerNativeExtensions = function() { /** * @see Namespace() */ String.prototype.namespace = function() { var klasses = arguments[0] || {}; return _namespace(this.valueOf(), klasses); }; /** * @see Namespace.include() */ String.prototype.include = function() { var callback = arguments[0] || false; return _namespace.include(this.valueOf(), callback); - } + }; /** * @see Namespace.use() */ String.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this.valueOf(), callback); - } + }; /** * @see Namespace.from() */ String.prototype.from = function() { return _namespace.from(this.valueOf()); - } + }; /** * @see Namespace.provide() * Idea and code submitted by Nathan Smith (http://github.com/smith) */ String.prototype.provide = function() { return _namespace.provide(this.valueOf()); - } + }; /** * @see Namespace.use() */ Array.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this, callback); - } + }; /** * @see Namespace.provide() */ Array.prototype.provide = function() { return _namespace.provide(this); - } + }; }; return _namespace; })(); /** * Namespace segment separator * * @var String */ Namespace.separator = '.'; /** * Base uri when using Namespace.include() * Must end with a slash * * @var String */ Namespace.baseUri = './'; /** * Whether to automatically call Namespace.include() when Namespace.import() * does not find the targeted object. * * @var Boolean */ Namespace.autoInclude = true;
smith/namespacedotjs
2fbfe8e53bf2581521f20085523cdfae7446d6b1
Added eval
diff --git a/Namespace.js b/Namespace.js index 06068ee..7f93d23 100644 --- a/Namespace.js +++ b/Namespace.js @@ -1,478 +1,485 @@ /* Script: Namespace.js Namespace utility Copyright: Copyright (c) 2009 Maxime Bouroumeau-Fuseau License: MIT-style license. Version: 1.1 */ var Namespace = (function() { var _listeners = {}; var _includedIdentifiers = []; /** * Returns an object in an array unless the object is an array * * @param mixed obj * @return Array */ var _toArray = function(obj) { // checks if it's an array if (typeof(obj) == 'object' && obj.sort) { return obj; } return new Array(obj); }; /** * Creates an XMLHttpRequest object * * @return XMLHttpRequest */ var _createXmlHttpRequest = function() { var xhr; try { xhr = new XMLHttpRequest() } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) { throw new Error( "This browser does not support XMLHttpRequest." ) } } } } } return xhr; }; /** * Checks if an http request is successful based on its status code. * Borrowed from dojo (http://www.dojotoolkit.org). * * @param Integer status Http status code * @return Boolean */ var _isHttpRequestSuccessful = function(status) { return (status >= 200 && status < 300) || // Boolean status == 304 || // allow any 2XX response code status == 1223 || // get it out of the cache (!status && (location.protocol == "file:" || location.protocol == "chrome:") ); // Internet Explorer mangled the status code }; /** * Creates a script tag with the specified data as content * * @param String data The content of the script */ var _createScript = function(data) { var script = document.createElement('script'); script.type = 'text/javascript'; script.text = data; - document.body.appendChild(script); + + try { // Attempt body insertion + document.body.appendChild(script); + } catch (e) { // Fall back on eval + if (typeof window.execScript === "function") { + window.execScript(data); + } else { window.eval(data); } + } }; /** * Dispatches an event * * @param String eventName * @param Object properties */ var _dispatchEvent = function(eventName, properties) { if (!_listeners[eventName]) return; properties.event = eventName; for (var i = 0; i < _listeners[eventName].length; i++) { _listeners[eventName][i](properties); } }; /** * Creates an Object following the specified namespace identifier. * * @public * @param String identifier The namespace string * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace * @return Object The most inner object */ var _namespace = function(identifier) { var klasses = arguments[1] || false; var ns = window; if (identifier != '') { var parts = identifier.split(Namespace.separator); for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { ns[parts[i]] = {}; } ns = ns[parts[i]]; } } if (klasses) { for (var klass in klasses) { ns[klass] = klasses[klass]; } } _dispatchEvent('create', { 'identifier': identifier }); return ns; }; /** * Checks if the specified identifier is defined * * @public * @param String identifier The namespace string * @return Boolean */ _namespace.exist = function(identifier) { if (identifier == '') return true; var parts = identifier.split(Namespace.separator); var ns = window; for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { return false; } ns = ns[parts[i]]; } return true; }; /** * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. * * @public * @param String identifier The namespace identifier * @return String The uri */ _namespace.mapIdentifierToUri = function(identifier) { var regexp = new RegExp('\\' + Namespace.separator, 'g'); return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; }; /** * Loads a remote script atfer mapping the identifier to an uri * * @param String identifier The namespace identifier * @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded * @param Function errorCallback Callback to be called when an error occurs * @return Boolean Success of failure when loading synchronously */ _loadScript = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; var async = successCallback != false; var uri = _namespace.mapIdentifierToUri(identifier); var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback }; var xhr = _createXmlHttpRequest(); xhr.open("GET", uri, async); if (async) { xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); successCallback(); return; } event.status = xhr.status; _dispatchEvent('includeError', event); errorCallback && errorCallback(); } }; } xhr.send(null); if (!async) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); return true; } event.status = xhr.status; _dispatchEvent('includeError', event); return false; } }; /** * Includes a remote javascript file identified by the specified namespace string. The identifier * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the remote script has been included */ _namespace.include = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; // checks if the identifier is not already included if (_includedIdentifiers[identifier]) { successCallback && successCallback(); return true; } if (successCallback) { _loadScript(identifier, function() { _includedIdentifiers[identifier] = true; successCallback(); }, errorCallback); } else { if (_loadScript(identifier)) { _includedIdentifiers[identifier] = true; return true; } return false; } }; /** * Imports properties from the specified namespace to the global space (ie. under window) * * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) * which will import all properties from the namespace. * * If not, the targeted namespace will be imported (ie. if com.test is imported, the test object * will now be global). If the targeted object is not found, it will be included using include(). * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude */ _namespace.use = function(identifier) { var identifiers = _toArray(identifier); var callback = arguments[1] || false; var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; var event = { 'identifier': identifier }; for (var i = 0; i < identifiers.length; i++) { identifier = identifiers[i]; var parts = identifier.split(Namespace.separator); var target = parts.pop(); var ns = _namespace(parts.join(Namespace.separator)); if (target == '*') { // imports all objects from the identifier, can't use include() in that case for (var objectName in ns) { window[objectName] = ns[objectName]; } } else { // imports only one object if (ns[target]) { // the object exists, import it window[target] = ns[target]; } else { // the object does not exist if (autoInclude) { // try to auto include it if (callback) { _namespace.include(identifier, function() { window[target] = ns[target]; if (i + 1 < identifiers.length) { // we continue to unpack the rest from here _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); } else { // no more identifiers to unpack _dispatchEvent('use', event); callback && callback(); } }); return; } else { _namespace.include(identifier); window[target] = ns[target]; } } } } } // all identifiers have been unpacked _dispatchEvent('use', event); callback && callback(); }; /** * Binds the include() and unpack() method to a specified identifier * * @public * @param String identifier The namespace identifier * @return Object */ _namespace.from = function(identifier) { return { /** * Includes the identifier specified in from() * * @see Namespace.include() */ include: function() { var callback = arguments[0] || false; _namespace.include(identifier, callback); }, /** * Includes the identifier specified in from() and unpack * the specified indentifier in _identifier * * @see Namespace.use() */ use: function(_identifier) { var callback = arguments[1] || false; if (_identifier.charAt(0) == '.') { _identifier = identifier + _identifier; } if (callback) { _namespace.include(identifier, function() { _namespace.use(_identifier, callback, false); }); } else { _namespace.include(identifier); _namespace.use(_identifier, callback, false); } } }; }; /** * Registers a namespace so it won't be included * * Idea and code submitted by Nathan Smith (http://github.com/smith) * * @param String|Array identifier */ _namespace.provide = function(identifier) { var identifiers = _toArray(identifier); for (var i = 0; i < identifiers.length; i++) { if (!(identifier in _includedIdentifiers)) { _dispatchEvent('provide', { 'identifier': identifier }); _includedIdentifiers[identifier] = true; } } }; /** * Registers a function to be called when the specified event is dispatched * * @param String eventName * @param Function callback */ _namespace.addEventListener = function(eventName, callback) { if (!_listeners[eventName]) _listeners[eventName] = []; _listeners[eventName].push(callback); }; /** * Unregisters an event listener * * @param String eventName * @param Function callback */ _namespace.removeEventListener = function(eventName, callback) { if (!_listeners[eventName]) return; for (var i = 0; i < _listeners[eventName].length; i++) { if (_listeners[eventName][i] == callback) { delete _listeners[eventName][i]; return; } } }; /** * Adds methods to javascript native's object * Inspired by http://thinkweb2.com/projects/prototype/namespacing-made-easy/ * * @public */ _namespace.registerNativeExtensions = function() { /** * @see Namespace() */ String.prototype.namespace = function() { var klasses = arguments[0] || {}; return _namespace(this.valueOf(), klasses); }; /** * @see Namespace.include() */ String.prototype.include = function() { var callback = arguments[0] || false; return _namespace.include(this.valueOf(), callback); } /** * @see Namespace.use() */ String.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this.valueOf(), callback); } /** * @see Namespace.from() */ String.prototype.from = function() { return _namespace.from(this.valueOf()); } /** * @see Namespace.provide() * Idea and code submitted by Nathan Smith (http://github.com/smith) */ String.prototype.provide = function() { return _namespace.provide(this.valueOf()); } /** * @see Namespace.use() */ Array.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this, callback); } /** * @see Namespace.provide() */ Array.prototype.provide = function() { return _namespace.provide(this); } }; return _namespace; })(); /** * Namespace segment separator * * @var String */ Namespace.separator = '.'; /** * Base uri when using Namespace.include() * Must end with a slash * * @var String */ Namespace.baseUri = './'; /** * Whether to automatically call Namespace.include() when Namespace.import() * does not find the targeted object. * * @var Boolean */ Namespace.autoInclude = true;
smith/namespacedotjs
007dc1cc5b929d54b24e988dbd9efe4d6ca6c3ee
Added include test
diff --git a/test/unit/fixtures/a.js b/test/unit/fixtures/a.js new file mode 100644 index 0000000..948ec99 --- /dev/null +++ b/test/unit/fixtures/a.js @@ -0,0 +1 @@ +a = {}; diff --git a/test/unit/index.html b/test/unit/index.html index 19be29f..40dd91c 100644 --- a/test/unit/index.html +++ b/test/unit/index.html @@ -1,29 +1,28 @@ <!DOCTYPE html> <html> <head> <title>Namespace.js unit test file</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script src="../assets/jsunittest.js"></script> <script src="../../Namespace.js"></script> <link rel="stylesheet" href="../assets/unittest.css" /> </head> <body> <div id="content"> <div id="header"> <h1>Namespace.js unit test file</h1> <p> - This file tests <strong>Namespace.js.js</strong>. + This file tests <strong>Namespace.js</strong>. </p> </div> <!-- Log output (one per Runner, via {testLog: "testlog"} option)--> <div id="testlog"></div> <!-- Put sample/test html here --> <div id="sample"> </div> </div> - <script src="namespace_test.js"></script> </body> </html> diff --git a/test/unit/namespace_test.js b/test/unit/namespace_test.js index 8739b0c..90b1f83 100644 --- a/test/unit/namespace_test.js +++ b/test/unit/namespace_test.js @@ -1,103 +1,113 @@ -/*global window, document, console, Test, Namespace, a */ +/*global window, document, Test, Namespace, a */ var t = new Test.Unit.Runner({ setup : function () { - + Namespace.separator = "."; + Namespace.baseUri = "./"; }, teardown : function () { // Delete any global objects that were created - delete window.a; + // IE has problems here + try { + delete window.a; + } catch (e) { window.a = undefined; } // Remove script tags other than Namespace.js, namespace_test.js // and unittest.js var tags = document.getElementsByTagName("SCRIPT"), tag; for (var i = 0; i < tags.length; i += 1) { tag = tags[i]; if (tag.src.match("amespace") === null && tag.src.match("unittest") === null) { tag.parentNode.removeChild(tag); } } }, testNamespace : function () { this.assert(typeof Namespace === "function"); // Create some objects using namespace Namespace("a.b.c"); this.assert(typeof a === "object"); this.assert(typeof a.b === "object"); this.assert(typeof a.b.c === "object"); // Create some properties and make sure they are preserved a.b.foo = true; a.b.bar = "hello"; Namespace("a.b.baz"); this.assert(a.b.foo); this.assertIdentical(a.b.bar, "hello"); this.assert(typeof a.b.baz === "object"); }, testExist : function () { this.assert(typeof Namespace.exist === "function"); this.assert(!Namespace.exist("a")); a = {}; a.b = function () {}; a.b.c = "something"; this.assert(Namespace.exist("a")); this.assert(Namespace.exist("a.b")); this.assert(Namespace.exist("a.b.c")); - delete window.a; + try { + delete window.a; + } catch (e) { window.a = undefined; } this.assert(!Namespace.exist("a")); }, testMapIdentifierToUri : function () { this.assert(typeof Namespace.mapIdentifierToUri === "function"); this.assertIdentical(Namespace.mapIdentifierToUri("a.b.c"), "./a/b/c.js"); Namespace.separator = ":"; this.assertIdentical(Namespace.mapIdentifierToUri("a:b:c"), "./a/b/c.js"); Namespace.separator = "."; Namespace.baseUri = "/foo/bar/"; this.assertIdentical(Namespace.mapIdentifierToUri("a.b.c"), "/foo/bar/a/b/c.js"); }, testInclude : function () { + this.assert(typeof Namespace.include === "function"); + Namespace.include("fixtures/a"); + + this.assert(typeof a === "object"); }, testUse : function () { }, testFrom : function () { }, testProvide : function () { }, testAddEventListener : function () { }, testRemoveEventListener : function () { }, testRegisterNativeExtensions : function () { } });
smith/namespacedotjs
8071495307fba396eec063ec5a8a24cfb4cf3d71
Added tests
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..feda09d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/jsunittest"] + path = vendor/jsunittest + url = git://github.com/drnic/jsunittest.git diff --git a/test/assets/jsunittest.js b/test/assets/jsunittest.js new file mode 100644 index 0000000..6854cea --- /dev/null +++ b/test/assets/jsunittest.js @@ -0,0 +1,1004 @@ +/* Jsunittest, version 0.7.2 + * (c) 2008 Dr Nic Williams + * + * Jsunittest is freely distributable under + * the terms of an MIT-style license. + * For details, see the web site: http://jsunittest.rubyforge.org + * + *--------------------------------------------------------------------------*/ + +var JsUnitTest = { + Unit: {}, + inspect: function(object) { + try { + if (typeof object == "undefined") return 'undefined'; + if (object === null) return 'null'; + if (typeof object == "string") { + var useDoubleQuotes = arguments[1]; + var escapedString = this.gsub(object, /[\x00-\x1f\\]/, function(match) { + var character = String.specialChar[match[0]]; + return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); + }); + if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + }; + return String(object); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + $: function(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push(this.$(arguments[i])); + return elements; + } + if (typeof element == "string") + element = document.getElementById(element); + return element; + }, + gsub: function(source, pattern, replacement) { + var result = '', match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += JsUnitTest.String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + scan: function(source, pattern, iterator) { + this.gsub(source, pattern, iterator); + return String(source); + }, + escapeHTML: function(data) { + return data.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); + }, + arrayfromargs: function(args) { + var myarray = new Array(); + var i; + + for (i=0;i<args.length;i++) + myarray[i] = args[i]; + + return myarray; + }, + hashToSortedArray: function(hash) { + var results = []; + for (key in hash) { + results.push([key, hash[key]]); + } + return results.sort(); + }, + flattenArray: function(array) { + var results = arguments[1] || []; + for (var i=0; i < array.length; i++) { + var object = array[i]; + if (object != null && typeof object == "object" && + 'splice' in object && 'join' in object) { + this.flattenArray(object, results); + } else { + results.push(object); + } + }; + return results; + }, + selectorMatch: function(expression, element) { + var tokens = []; + var patterns = { + // combinators must be listed first + // (and descendant needs to be last combinator) + laterSibling: /^\s*~\s*/, + child: /^\s*>\s*/, + adjacent: /^\s*\+\s*/, + descendant: /^\s/, + + // selectors follow + tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, + id: /^#([\w\-\*]+)(\b|$)/, + className: /^\.([\w\-\*]+)(\b|$)/, + pseudo: + /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/, + attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/, + attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ + }; + + var assertions = { + tagName: function(element, matches) { + return matches[1].toUpperCase() == element.tagName.toUpperCase(); + }, + + className: function(element, matches) { + return Element.hasClassName(element, matches[1]); + }, + + id: function(element, matches) { + return element.id === matches[1]; + }, + + attrPresence: function(element, matches) { + return Element.hasAttribute(element, matches[1]); + }, + + attr: function(element, matches) { + var nodeValue = Element.readAttribute(element, matches[1]); + return nodeValue && operators[matches[2]](nodeValue, matches[5] || matches[6]); + } + }; + var e = this.expression, ps = patterns, as = assertions; + var le, p, m; + + while (e && le !== e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + // use the Selector.assertions methods unless the selector + // is too complex. + if (as[i]) { + tokens.push([i, Object.clone(m)]); + e = e.replace(m[0], ''); + } + } + } + } + + var match = true, name, matches; + for (var i = 0, token; token = tokens[i]; i++) { + name = token[0], matches = token[1]; + if (!assertions[name](element, matches)) { + match = false; break; + } + } + + return match; + }, + toQueryParams: function(query, separator) { + var query = query || window.location.search; + var match = query.replace(/^\s+/, '').replace(/\s+$/, '').match(/([^?#]*)(#.*)?$/); + if (!match) return { }; + + var hash = {}; + var parts = match[1].split(separator || '&'); + for (var i=0; i < parts.length; i++) { + var pair = parts[i].split('='); + if (pair[0]) { + var key = decodeURIComponent(pair.shift()); + var value = pair.length > 1 ? pair.join('=') : pair[0]; + if (value != undefined) value = decodeURIComponent(value); + + if (key in hash) { + var object = hash[key]; + var isArray = object != null && typeof object == "object" && + 'splice' in object && 'join' in object + if (!isArray) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + }; + return hash; + }, + + String: { + interpret: function(value) { + return value == null ? '' : String(value); + } + } +}; + +JsUnitTest.gsub.prepareReplacement = function(replacement) { + if (typeof replacement == "function") return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +}; + +JsUnitTest.Version = '0.7.2'; + +JsUnitTest.Template = function(template, pattern) { + this.template = template; //template.toString(); + this.pattern = pattern || JsUnitTest.Template.Pattern; +}; + +JsUnitTest.Template.prototype.evaluate = function(object) { + if (typeof object.toTemplateReplacements == "function") + object = object.toTemplateReplacements(); + + return JsUnitTest.gsub(this.template, this.pattern, function(match) { + if (object == null) return ''; + + var before = match[1] || ''; + if (before == '\\') return match[2]; + + var ctx = object, expr = match[3]; + var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; + match = pattern.exec(expr); + if (match == null) return before; + + while (match != null) { + var comp = (match[1].indexOf('[]') === 0) ? match[2].gsub('\\\\]', ']') : match[1]; + ctx = ctx[comp]; + if (null == ctx || '' == match[3]) break; + expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); + match = pattern.exec(expr); + } + + return before + JsUnitTest.String.interpret(ctx); + }); +} + +JsUnitTest.Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; +JsUnitTest.Event = {}; +// written by Dean Edwards, 2005 +// with input from Tino Zijdel, Matthias Miller, Diego Perini +// namespaced by Dr Nic Williams 2008 + +// http://dean.edwards.name/weblog/2005/10/add-event/ +// http://dean.edwards.name/weblog/2005/10/add-event2/ +JsUnitTest.Event.addEvent = function(element, type, handler) { + if (element.addEventListener) { + element.addEventListener(type, handler, false); + } else { + // assign each event handler a unique ID + if (!handler.$$guid) handler.$$guid = JsUnitTest.Event.addEvent.guid++; + // create a hash table of event types for the element + if (!element.events) element.events = {}; + // create a hash table of event handlers for each element/event pair + var handlers = element.events[type]; + if (!handlers) { + handlers = element.events[type] = {}; + // store the existing event handler (if there is one) + if (element["on" + type]) { + handlers[0] = element["on" + type]; + } + } + // store the event handler in the hash table + handlers[handler.$$guid] = handler; + // assign a global event handler to do all the work + element["on" + type] = this.handleEvent; + } +}; +// a counter used to create unique IDs +JsUnitTest.Event.addEvent.guid = 1; + +JsUnitTest.Event.removeEvent = function(element, type, handler) { + if (element.removeEventListener) { + element.removeEventListener(type, handler, false); + } else { + // delete the event handler from the hash table + if (element.events && element.events[type]) { + delete element.events[type][handler.$$guid]; + } + } +}; + +JsUnitTest.Event.handleEvent = function(event) { + var returnValue = true; + // grab the event object (IE uses a global event object) + event = event || JsUnitTest.Event.fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event); + // get a reference to the hash table of event handlers + var handlers = this.events[event.type]; + // execute each event handler + for (var i in handlers) { + this.$$handleEvent = handlers[i]; + if (this.$$handleEvent(event) === false) { + returnValue = false; + } + } + return returnValue; +}; + +JsUnitTest.Event.fixEvent = function(event) { + // add W3C standard event methods + event.preventDefault = this.fixEvent.preventDefault; + event.stopPropagation = this.fixEvent.stopPropagation; + return event; +}; +JsUnitTest.Event.fixEvent.preventDefault = function() { + this.returnValue = false; +}; +JsUnitTest.Event.fixEvent.stopPropagation = function() { + this.cancelBubble = true; +}; + +JsUnitTest.Unit.Logger = function(element) { + this.element = JsUnitTest.$(element); + if (this.element) this._createLogTable(); +}; + +JsUnitTest.Unit.Logger.prototype.start = function(testName) { + if (!this.element) return; + var tbody = this.element.getElementsByTagName('tbody')[0]; + + var tr = document.createElement('tr'); + var td; + + //testname + td = document.createElement('td'); + td.appendChild(document.createTextNode(testName)); + tr.appendChild(td) + + tr.appendChild(document.createElement('td'));//status + tr.appendChild(document.createElement('td'));//message + + tbody.appendChild(tr); +}; + +JsUnitTest.Unit.Logger.prototype.setStatus = function(status) { + var logline = this.getLastLogLine(); + logline.className = status; + var statusCell = logline.getElementsByTagName('td')[1]; + statusCell.appendChild(document.createTextNode(status)); +}; + +JsUnitTest.Unit.Logger.prototype.finish = function(status, summary) { + if (!this.element) return; + this.setStatus(status); + this.message(summary); +}; + +JsUnitTest.Unit.Logger.prototype.message = function(message) { + if (!this.element) return; + var cell = this.getMessageCell(); + + // cell.appendChild(document.createTextNode(this._toHTML(message))); + cell.innerHTML = this._toHTML(message); +}; + +JsUnitTest.Unit.Logger.prototype.summary = function(summary) { + if (!this.element) return; + var div = this.element.getElementsByTagName('div')[0]; + div.innerHTML = this._toHTML(summary); +}; + +JsUnitTest.Unit.Logger.prototype.getLastLogLine = function() { + var tbody = this.element.getElementsByTagName('tbody')[0]; + var loglines = tbody.getElementsByTagName('tr'); + return loglines[loglines.length - 1]; +}; + +JsUnitTest.Unit.Logger.prototype.getMessageCell = function() { + var logline = this.getLastLogLine(); + return logline.getElementsByTagName('td')[2]; +}; + +JsUnitTest.Unit.Logger.prototype._createLogTable = function() { + var html = '<div class="logsummary">running...</div>' + + '<table class="logtable">' + + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + + '<tbody class="loglines"></tbody>' + + '</table>'; + this.element.innerHTML = html; +}; + +JsUnitTest.Unit.Logger.prototype.appendActionButtons = function(actions) { + // actions = $H(actions); + // if (!actions.any()) return; + // var div = new Element("div", {className: 'action_buttons'}); + // actions.inject(div, function(container, action) { + // var button = new Element("input").setValue(action.key).observe("click", action.value); + // button.type = "button"; + // return container.insert(button); + // }); + // this.getMessageCell().insert(div); +}; + +JsUnitTest.Unit.Logger.prototype._toHTML = function(txt) { + return JsUnitTest.escapeHTML(txt).replace(/\n/g,"<br/>"); +}; +JsUnitTest.Unit.MessageTemplate = function(string) { + var parts = []; + var str = JsUnitTest.scan((string || ''), /(?=[^\\])\?|(?:\\\?|[^\?])+/, function(part) { + parts.push(part[0]); + }); + this.parts = parts; +}; + +JsUnitTest.Unit.MessageTemplate.prototype.evaluate = function(params) { + var results = []; + for (var i=0; i < this.parts.length; i++) { + var part = this.parts[i]; + var result = (part == '?') ? JsUnitTest.inspect(params.shift()) : part.replace(/\\\?/, '?'); + results.push(result); + }; + return results.join(''); +}; +// A generic function for performming AJAX requests +// It takes one argument, which is an object that contains a set of options +// All of which are outline in the comments, below +// From John Resig's book Pro JavaScript Techniques +// published by Apress, 2006-8 +JsUnitTest.ajax = function( options ) { + + // Load the options object with defaults, if no + // values were provided by the user + options = { + // The type of HTTP Request + type: options.type || "POST", + + // The URL the request will be made to + url: options.url || "", + + // How long to wait before considering the request to be a timeout + timeout: options.timeout || 5000, + + // Functions to call when the request fails, succeeds, + // or completes (either fail or succeed) + onComplete: options.onComplete || function(){}, + onError: options.onError || function(){}, + onSuccess: options.onSuccess || function(){}, + + // The data type that'll be returned from the server + // the default is simply to determine what data was returned from the + // and act accordingly. + data: options.data || "" + }; + + // Create the request object + var xml = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); + + // Open the asynchronous POST request + xml.open(options.type, options.url, true); + + // We're going to wait for a request for 5 seconds, before giving up + var timeoutLength = 5000; + + // Keep track of when the request has been succesfully completed + var requestDone = false; + + // Initalize a callback which will fire 5 seconds from now, cancelling + // the request (if it has not already occurred). + setTimeout(function(){ + requestDone = true; + }, timeoutLength); + + // Watch for when the state of the document gets updated + xml.onreadystatechange = function(){ + // Wait until the data is fully loaded, + // and make sure that the request hasn't already timed out + if ( xml.readyState == 4 && !requestDone ) { + + // Check to see if the request was successful + if ( httpSuccess( xml ) ) { + + // Execute the success callback with the data returned from the server + options.onSuccess( httpData( xml, options.type ) ); + + // Otherwise, an error occurred, so execute the error callback + } else { + options.onError(); + } + + // Call the completion callback + options.onComplete(); + + // Clean up after ourselves, to avoid memory leaks + xml = null; + } + }; + + // Establish the connection to the server + xml.send(null); + + // Determine the success of the HTTP response + function httpSuccess(r) { + try { + // If no server status is provided, and we're actually + // requesting a local file, then it was successful + return !r.status && location.protocol == "file:" || + + // Any status in the 200 range is good + ( r.status >= 200 && r.status < 300 ) || + + // Successful if the document has not been modified + r.status == 304 || + + // Safari returns an empty status if the file has not been modified + navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined"; + } catch(e){} + + // If checking the status failed, then assume that the request failed too + return false; + } + + // Extract the correct data from the HTTP response + function httpData(r,type) { + // Get the content-type header + var ct = r.getResponseHeader("content-type"); + + // If no default type was provided, determine if some + // form of XML was returned from the server + var data = !type && ct && ct.indexOf("xml") >= 0; + + // Get the XML Document object if XML was returned from + // the server, otherwise return the text contents returned by the server + data = type == "xml" || data ? r.responseXML : r.responseText; + + // If the specified type is "script", execute the returned text + // response as if it was JavaScript + if ( type == "script" ) + eval.call( window, data ); + + // Return the response data (either an XML Document or a text string) + return data; + } + +}; +JsUnitTest.Unit.Assertions = { + buildMessage: function(message, template) { + var args = JsUnitTest.arrayfromargs(arguments).slice(2); + return (message ? message + '\n' : '') + + new JsUnitTest.Unit.MessageTemplate(template).evaluate(args); + }, + + flunk: function(message) { + this.assertBlock(message || 'Flunked', function() { return false }); + }, + + assertBlock: function(message, block) { + try { + block.call(this) ? this.pass() : this.fail(message); + } catch(e) { this.error(e) } + }, + + assert: function(expression, message) { + message = this.buildMessage(message || 'assert', 'got <?>', expression); + this.assertBlock(message, function() { return expression }); + }, + + assertEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertEqual', 'expected <?>, actual: <?>', expected, actual); + this.assertBlock(message, function() { return expected == actual }); + }, + + assertNotEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertNotEqual', 'expected <?>, actual: <?>', expected, actual); + this.assertBlock(message, function() { return expected != actual }); + }, + + assertEnumEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertEnumEqual', 'expected <?>, actual: <?>', expected, actual); + var expected_array = JsUnitTest.flattenArray(expected); + var actual_array = JsUnitTest.flattenArray(actual); + this.assertBlock(message, function() { + if (expected_array.length == actual_array.length) { + for (var i=0; i < expected_array.length; i++) { + if (expected_array[i] != actual_array[i]) return false; + }; + return true; + } + return false; + }); + }, + + assertEnumNotEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertEnumNotEqual', '<?> was the same as <?>', expected, actual); + var expected_array = JsUnitTest.flattenArray(expected); + var actual_array = JsUnitTest.flattenArray(actual); + this.assertBlock(message, function() { + if (expected_array.length == actual_array.length) { + for (var i=0; i < expected_array.length; i++) { + if (expected_array[i] != actual_array[i]) return true; + }; + return false; + } + return true; + }); + }, + + assertHashEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertHashEqual', 'expected <?>, actual: <?>', expected, actual); + var expected_array = JsUnitTest.flattenArray(JsUnitTest.hashToSortedArray(expected)); + var actual_array = JsUnitTest.flattenArray(JsUnitTest.hashToSortedArray(actual)); + var block = function() { + if (expected_array.length == actual_array.length) { + for (var i=0; i < expected_array.length; i++) { + if (expected_array[i] != actual_array[i]) return false; + }; + return true; + } + return false; + }; + this.assertBlock(message, block); + }, + + assertHashNotEqual: function(expected, actual, message) { + message = this.buildMessage(message || 'assertHashNotEqual', '<?> was the same as <?>', expected, actual); + var expected_array = JsUnitTest.flattenArray(JsUnitTest.hashToSortedArray(expected)); + var actual_array = JsUnitTest.flattenArray(JsUnitTest.hashToSortedArray(actual)); + // from now we recursively zip & compare nested arrays + var block = function() { + if (expected_array.length == actual_array.length) { + for (var i=0; i < expected_array.length; i++) { + if (expected_array[i] != actual_array[i]) return true; + }; + return false; + } + return true; + }; + this.assertBlock(message, block); + }, + + assertIdentical: function(expected, actual, message) { + message = this.buildMessage(message || 'assertIdentical', 'expected <?>, actual: <?>', expected, actual); + this.assertBlock(message, function() { return expected === actual }); + }, + + assertNotIdentical: function(expected, actual, message) { + message = this.buildMessage(message || 'assertNotIdentical', 'expected <?>, actual: <?>', expected, actual); + this.assertBlock(message, function() { return expected !== actual }); + }, + + assertNull: function(obj, message) { + message = this.buildMessage(message || 'assertNull', 'got <?>', obj); + this.assertBlock(message, function() { return obj === null }); + }, + + assertNotNull: function(obj, message) { + message = this.buildMessage(message || 'assertNotNull', 'got <?>', obj); + this.assertBlock(message, function() { return obj !== null }); + }, + + assertUndefined: function(obj, message) { + message = this.buildMessage(message || 'assertUndefined', 'got <?>', obj); + this.assertBlock(message, function() { return typeof obj == "undefined" }); + }, + + assertNotUndefined: function(obj, message) { + message = this.buildMessage(message || 'assertNotUndefined', 'got <?>', obj); + this.assertBlock(message, function() { return typeof obj != "undefined" }); + }, + + assertNullOrUndefined: function(obj, message) { + message = this.buildMessage(message || 'assertNullOrUndefined', 'got <?>', obj); + this.assertBlock(message, function() { return obj == null }); + }, + + assertNotNullOrUndefined: function(obj, message) { + message = this.buildMessage(message || 'assertNotNullOrUndefined', 'got <?>', obj); + this.assertBlock(message, function() { return obj != null }); + }, + + assertMatch: function(expected, actual, message) { + message = this.buildMessage(message || 'assertMatch', 'regex <?> did not match <?>', expected, actual); + this.assertBlock(message, function() { return new RegExp(expected).exec(actual) }); + }, + + assertNoMatch: function(expected, actual, message) { + message = this.buildMessage(message || 'assertNoMatch', 'regex <?> matched <?>', expected, actual); + this.assertBlock(message, function() { return !(new RegExp(expected).exec(actual)) }); + }, + + assertHasClass: function(element, klass, message) { + element = JsUnitTest.$(element); + message = this.buildMessage(message || 'assertHasClass', '? doesn\'t have class <?>.', element, klass); + this.assertBlock(message, function() { + return !!element.className.match(new RegExp(klass)) + }); + }, + + assertHidden: function(element, message) { + element = JsUnitTest.$(element); + message = this.buildMessage(message || 'assertHidden', '? isn\'t hidden.', element); + this.assertBlock(message, function() { return !element.style.display || element.style.display == 'none' }); + }, + + assertInstanceOf: function(expected, actual, message) { + message = this.buildMessage(message || 'assertInstanceOf', '<?> was not an instance of the expected type', actual); + this.assertBlock(message, function() { return actual instanceof expected }); + }, + + assertNotInstanceOf: function(expected, actual, message) { + message = this.buildMessage(message || 'assertNotInstanceOf', '<?> was an instance of the expected type', actual); + this.assertBlock(message, function() { return !(actual instanceof expected) }); + }, + + assertRespondsTo: function(method, obj, message) { + message = this.buildMessage(message || 'assertRespondsTo', 'object doesn\'t respond to <?>', method); + this.assertBlock(message, function() { return (method in obj && typeof obj[method] == 'function') }); + }, + + assertRaise: function(exceptionName, method, message) { + message = this.buildMessage(message || 'assertRaise', '<?> exception expected but none was raised', exceptionName); + var block = function() { + try { + method(); + return false; + } catch(e) { + if (e.name == exceptionName) return true; + else throw e; + } + }; + this.assertBlock(message, block); + }, + + assertNothingRaised: function(method, message) { + try { + method(); + this.assert(true, "Expected nothing to be thrown"); + } catch(e) { + message = this.buildMessage(message || 'assertNothingRaised', '<?> was thrown when nothing was expected.', e); + this.flunk(message); + } + }, + + _isVisible: function(element) { + element = JsUnitTest.$(element); + if(!element.parentNode) return true; + this.assertNotNull(element); + if(element.style && (element.style.display == 'none')) + return false; + + return arguments.callee.call(this, element.parentNode); + }, + + assertVisible: function(element, message) { + message = this.buildMessage(message, '? was not visible.', element); + this.assertBlock(message, function() { return this._isVisible(element) }); + }, + + assertNotVisible: function(element, message) { + message = this.buildMessage(message, '? was not hidden and didn\'t have a hidden parent either.', element); + this.assertBlock(message, function() { return !this._isVisible(element) }); + }, + + assertElementsMatch: function() { + var pass = true, expressions = JsUnitTest.arrayfromargs(arguments); + var elements = expressions.shift(); + if (elements.length != expressions.length) { + message = this.buildMessage('assertElementsMatch', 'size mismatch: ? elements, ? expressions (?).', elements.length, expressions.length, expressions); + this.flunk(message); + pass = false; + } + for (var i=0; i < expressions.length; i++) { + var expression = expressions[i]; + var element = JsUnitTest.$(elements[i]); + if (JsUnitTest.selectorMatch(expression, element)) { + pass = true; + break; + } + message = this.buildMessage('assertElementsMatch', 'In index <?>: expected <?> but got ?', index, expression, element); + this.flunk(message); + pass = false; + }; + this.assert(pass, "Expected all elements to match."); + }, + + assertElementMatches: function(element, expression, message) { + this.assertElementsMatch([element], expression); + } +}; +JsUnitTest.Unit.Runner = function(testcases) { + var argumentOptions = arguments[1] || {}; + var options = this.options = {}; + options.testLog = ('testLog' in argumentOptions) ? argumentOptions.testLog : 'testlog'; + options.resultsURL = this.queryParams.resultsURL; + options.testLog = JsUnitTest.$(options.testLog); + + this.tests = this.getTests(testcases); + this.currentTest = 0; + this.logger = new JsUnitTest.Unit.Logger(options.testLog); + + var self = this; + JsUnitTest.Event.addEvent(window, "load", function() { + setTimeout(function() { + self.runTests(); + }, 0.1); + }); +}; + +JsUnitTest.Unit.Runner.prototype.queryParams = JsUnitTest.toQueryParams(); + +JsUnitTest.Unit.Runner.prototype.portNumber = function() { + if (window.location.search.length > 0) { + var matches = window.location.search.match(/\:(\d{3,5})\//); + if (matches) { + return parseInt(matches[1]); + } + } + return null; +}; + +JsUnitTest.Unit.Runner.prototype.getTests = function(testcases) { + var tests = [], options = this.options; + if (this.queryParams.tests) tests = this.queryParams.tests.split(','); + else if (options.tests) tests = options.tests; + else if (options.test) tests = [option.test]; + else { + for (testname in testcases) { + if (testname.match(/^test/)) tests.push(testname); + } + } + var results = []; + for (var i=0; i < tests.length; i++) { + var test = tests[i]; + if (testcases[test]) + results.push( + new JsUnitTest.Unit.Testcase(test, testcases[test], testcases.setup, testcases.teardown) + ); + }; + return results; +}; + +JsUnitTest.Unit.Runner.prototype.getResult = function() { + var results = { + tests: this.tests.length, + assertions: 0, + failures: 0, + errors: 0, + warnings: 0 + }; + + for (var i=0; i < this.tests.length; i++) { + var test = this.tests[i]; + results.assertions += test.assertions; + results.failures += test.failures; + results.errors += test.errors; + results.warnings += test.warnings; + }; + return results; +}; + +JsUnitTest.Unit.Runner.prototype.postResults = function() { + if (this.options.resultsURL) { + // new Ajax.Request(this.options.resultsURL, + // { method: 'get', parameters: this.getResult(), asynchronous: false }); + var results = this.getResult(); + var url = this.options.resultsURL + "?"; + url += "tests="+ this.tests.length + "&"; + url += "assertions="+ results.assertions + "&"; + url += "warnings=" + results.warnings + "&"; + url += "failures=" + results.failures + "&"; + url += "errors=" + results.errors; + JsUnitTest.ajax({ + url: url, + type: 'GET' + }) + } +}; + +JsUnitTest.Unit.Runner.prototype.runTests = function() { + var test = this.tests[this.currentTest], actions; + + if (!test) return this.finish(); + if (!test.isWaiting) this.logger.start(test.name); + test.run(); + var self = this; + if(test.isWaiting) { + this.logger.message("Waiting for " + test.timeToWait + "ms"); + // setTimeout(this.runTests.bind(this), test.timeToWait || 1000); + setTimeout(function() { + self.runTests(); + }, test.timeToWait || 1000); + return; + } + + this.logger.finish(test.status(), test.summary()); + if (actions = test.actions) this.logger.appendActionButtons(actions); + this.currentTest++; + // tail recursive, hopefully the browser will skip the stackframe + this.runTests(); +}; + +JsUnitTest.Unit.Runner.prototype.finish = function() { + this.postResults(); + this.logger.summary(this.summary()); +}; + +JsUnitTest.Unit.Runner.prototype.summary = function() { + return new JsUnitTest.Template('#{tests} tests, #{assertions} assertions, #{failures} failures, #{errors} errors, #{warnings} warnings').evaluate(this.getResult()); +}; +JsUnitTest.Unit.Testcase = function(name, test, setup, teardown) { + this.name = name; + this.test = test || function() {}; + this.setup = setup || function() {}; + this.teardown = teardown || function() {}; + this.messages = []; + this.actions = {}; +}; +// import JsUnitTest.Unit.Assertions + +for (method in JsUnitTest.Unit.Assertions) { + JsUnitTest.Unit.Testcase.prototype[method] = JsUnitTest.Unit.Assertions[method]; +} + +JsUnitTest.Unit.Testcase.prototype.isWaiting = false; +JsUnitTest.Unit.Testcase.prototype.timeToWait = 1000; +JsUnitTest.Unit.Testcase.prototype.assertions = 0; +JsUnitTest.Unit.Testcase.prototype.failures = 0; +JsUnitTest.Unit.Testcase.prototype.errors = 0; +JsUnitTest.Unit.Testcase.prototype.warnings = 0; +JsUnitTest.Unit.Testcase.prototype.isRunningFromRake = window.location.port; + +// JsUnitTest.Unit.Testcase.prototype.isRunningFromRake = window.location.port == 4711; + +JsUnitTest.Unit.Testcase.prototype.wait = function(time, nextPart) { + this.isWaiting = true; + this.test = nextPart; + this.timeToWait = time; +}; + +JsUnitTest.Unit.Testcase.prototype.run = function(rethrow) { + try { + try { + if (!this.isWaiting) this.setup(); + this.isWaiting = false; + this.test(); + } finally { + if(!this.isWaiting) { + this.teardown(); + } + } + } + catch(e) { + if (rethrow) throw e; + this.error(e, this); + } +}; + +JsUnitTest.Unit.Testcase.prototype.summary = function() { + var msg = '#{assertions} assertions, #{failures} failures, #{errors} errors, #{warnings} warnings\n'; + return new JsUnitTest.Template(msg).evaluate(this) + + this.messages.join("\n"); +}; + +JsUnitTest.Unit.Testcase.prototype.pass = function() { + this.assertions++; +}; + +JsUnitTest.Unit.Testcase.prototype.fail = function(message) { + this.failures++; + var line = ""; + try { + throw new Error("stack"); + } catch(e){ + line = (/\.html:(\d+)/.exec(e.stack || '') || ['',''])[1]; + } + this.messages.push("Failure: " + message + (line ? " Line #" + line : "")); +}; + +JsUnitTest.Unit.Testcase.prototype.warning = function(message) { + this.warnings++; + var line = ""; + try { + throw new Error("stack"); + } catch(e){ + line = (/\.html:(\d+)/.exec(e.stack || '') || ['',''])[1]; + } + this.messages.push("Warning: " + message + (line ? " Line #" + line : "")); +}; +JsUnitTest.Unit.Testcase.prototype.warn = JsUnitTest.Unit.Testcase.prototype.warning; + +JsUnitTest.Unit.Testcase.prototype.info = function(message) { + this.messages.push("Info: " + message); +}; + +JsUnitTest.Unit.Testcase.prototype.error = function(error, test) { + this.errors++; + this.actions['retry with throw'] = function() { test.run(true) }; + this.messages.push(error.name + ": "+ error.message + "(" + JsUnitTest.inspect(error) + ")"); +}; + +JsUnitTest.Unit.Testcase.prototype.status = function() { + if (this.failures > 0) return 'failed'; + if (this.errors > 0) return 'error'; + if (this.warnings > 0) return 'warning'; + return 'passed'; +}; + +JsUnitTest.Unit.Testcase.prototype.benchmark = function(operation, iterations) { + var startAt = new Date(); + (iterations || 1).times(operation); + var timeTaken = ((new Date())-startAt); + this.info((arguments[2] || 'Operation') + ' finished ' + + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); + return timeTaken; +}; + +Test = JsUnitTest \ No newline at end of file diff --git a/test/assets/unittest.css b/test/assets/unittest.css new file mode 100644 index 0000000..e1b7605 --- /dev/null +++ b/test/assets/unittest.css @@ -0,0 +1,54 @@ +body, div, p, h1, h2, h3, ul, ol, span, a, table, td, form, img, li { + font-family: sans-serif; +} + +body { + font-size:0.8em; +} + +#log { + padding-bottom: 1em; + border-bottom: 2px solid #000; + margin-bottom: 2em; +} + +.logsummary { + margin-top: 1em; + margin-bottom: 1em; + padding: 1ex; + border: 1px solid #000; + font-weight: bold; +} + +.logtable { + width:100%; + border-collapse: collapse; + border: 1px dotted #666; +} + +.logtable td, .logtable th { + text-align: left; + padding: 3px 8px; + border: 1px dotted #666; +} + +.logtable .passed { + background-color: #cfc; +} + +.logtable .failed, .logtable .error { + background-color: #fcc; +} + +.logtable .warning { + background-color: #FC6; +} + +.logtable td div.action_buttons { + display: inline; +} + +.logtable td div.action_buttons input { + margin: 0 5px; + font-size: 10px; +} diff --git a/test/unit/index.html b/test/unit/index.html new file mode 100644 index 0000000..19be29f --- /dev/null +++ b/test/unit/index.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html> +<head> + <title>Namespace.js unit test file</title> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <script src="../assets/jsunittest.js"></script> + <script src="../../Namespace.js"></script> + <link rel="stylesheet" href="../assets/unittest.css" /> +</head> +<body> +<div id="content"> + <div id="header"> + <h1>Namespace.js unit test file</h1> + <p> + This file tests <strong>Namespace.js.js</strong>. + </p> + </div> + + <!-- Log output (one per Runner, via {testLog: "testlog"} option)--> + <div id="testlog"></div> + + <!-- Put sample/test html here --> + <div id="sample"> + </div> +</div> + +<script src="namespace_test.js"></script> +</body> +</html> diff --git a/test/unit/namespace_test.js b/test/unit/namespace_test.js new file mode 100644 index 0000000..8739b0c --- /dev/null +++ b/test/unit/namespace_test.js @@ -0,0 +1,103 @@ +/*global window, document, console, Test, Namespace, a */ + +var t = new Test.Unit.Runner({ + setup : function () { + + }, + + teardown : function () { + // Delete any global objects that were created + delete window.a; + + // Remove script tags other than Namespace.js, namespace_test.js + // and unittest.js + var tags = document.getElementsByTagName("SCRIPT"), tag; + for (var i = 0; i < tags.length; i += 1) { + tag = tags[i]; + if (tag.src.match("amespace") === null && + tag.src.match("unittest") === null) { + tag.parentNode.removeChild(tag); + } + } + }, + + testNamespace : function () { + this.assert(typeof Namespace === "function"); + // Create some objects using namespace + Namespace("a.b.c"); + + this.assert(typeof a === "object"); + this.assert(typeof a.b === "object"); + this.assert(typeof a.b.c === "object"); + + // Create some properties and make sure they are preserved + a.b.foo = true; + a.b.bar = "hello"; + Namespace("a.b.baz"); + + this.assert(a.b.foo); + this.assertIdentical(a.b.bar, "hello"); + this.assert(typeof a.b.baz === "object"); + }, + + testExist : function () { + this.assert(typeof Namespace.exist === "function"); + + this.assert(!Namespace.exist("a")); + + a = {}; + a.b = function () {}; + a.b.c = "something"; + + this.assert(Namespace.exist("a")); + this.assert(Namespace.exist("a.b")); + this.assert(Namespace.exist("a.b.c")); + + delete window.a; + + this.assert(!Namespace.exist("a")); + }, + + testMapIdentifierToUri : function () { + this.assert(typeof Namespace.mapIdentifierToUri === "function"); + + this.assertIdentical(Namespace.mapIdentifierToUri("a.b.c"), "./a/b/c.js"); + + Namespace.separator = ":"; + + this.assertIdentical(Namespace.mapIdentifierToUri("a:b:c"), "./a/b/c.js"); + + Namespace.separator = "."; + Namespace.baseUri = "/foo/bar/"; + + this.assertIdentical(Namespace.mapIdentifierToUri("a.b.c"), "/foo/bar/a/b/c.js"); + }, + + testInclude : function () { + + }, + + testUse : function () { + + }, + + testFrom : function () { + + }, + + testProvide : function () { + + }, + + testAddEventListener : function () { + + }, + + testRemoveEventListener : function () { + + }, + + testRegisterNativeExtensions : function () { + + } +}); diff --git a/vendor/jsunittest b/vendor/jsunittest new file mode 160000 index 0000000..b289816 --- /dev/null +++ b/vendor/jsunittest @@ -0,0 +1 @@ +Subproject commit b2898168fdd5a09adba67689e0e5fa20daa32ca2
smith/namespacedotjs
1d688b7d079d1f47284e889052c1648b421acdd7
Added provide method
diff --git a/Namespace.js b/Namespace.js index 8e29a22..a4362dd 100644 --- a/Namespace.js +++ b/Namespace.js @@ -1,447 +1,467 @@ /* Script: Namespace.js Namespace utility Copyright: Copyright (c) 2009 Maxime Bouroumeau-Fuseau License: MIT-style license. Version: 1.0 */ var Namespace = (function() { var _listeners = {}; var _includedIdentifiers = []; /** * Returns an object in an array unless the object is an array * * @param mixed obj * @return Array */ var _toArray = function(obj) { // checks if it's an array if (typeof(obj) == 'object' && obj.sort) { return obj; } return new Array(obj); }; /** * Creates an XMLHttpRequest object * * @return XMLHttpRequest */ var _createXmlHttpRequest = function() { var xhr; try { xhr = new XMLHttpRequest() } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) { throw new Error( "This browser does not support XMLHttpRequest." ) } } } } } return xhr; }; /** * Checks if an http request is successful based on its status code. * Borrowed from dojo (http://www.dojotoolkit.org). * * @param Integer status Http status code * @return Boolean */ var _isHttpRequestSuccessful = function(status) { return (status >= 200 && status < 300) || // Boolean status == 304 || // allow any 2XX response code status == 1223 || // get it out of the cache (!status && (location.protocol == "file:" || location.protocol == "chrome:") ); // Internet Explorer mangled the status code }; /** * Creates a script tag with the specified data as content * * @param String data The content of the script */ var _createScript = function(data) { var script = document.createElement('script'); script.type = 'text/javascript'; script.text = data; document.body.appendChild(script); }; /** * Dispatches an event * * @param String eventName * @param Object properties */ var _dispatchEvent = function(eventName, properties) { if (!_listeners[eventName]) return; properties.event = eventName; for (var i = 0; i < _listeners[eventName].length; i++) { _listeners[eventName][i](properties); } }; /** * Creates an Object following the specified namespace identifier. * * @public * @param String identifier The namespace string * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace * @return Object The most inner object */ var _namespace = function(identifier) { var klasses = arguments[1] || false; var ns = window; if (identifier != '') { var parts = identifier.split(Namespace.separator); for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { ns[parts[i]] = {}; } ns = ns[parts[i]]; } } if (klasses) { for (var klass in klasses) { ns[klass] = klasses[klass]; } } _dispatchEvent('create', { 'identifier': identifier }); return ns; }; /** * Checks if the specified identifier is defined * * @public * @param String identifier The namespace string * @return Boolean */ _namespace.exist = function(identifier) { if (identifier == '') return true; var parts = identifier.split(Namespace.separator); var ns = window; for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { return false; } ns = ns[parts[i]]; } return true; }; /** * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. * * @public * @param String identifier The namespace identifier * @return String The uri */ _namespace.mapIdentifierToUri = function(identifier) { var regexp = new RegExp('\\' + Namespace.separator, 'g'); return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; }; /** * Loads a remote script atfer mapping the identifier to an uri * * @param String identifier The namespace identifier * @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded * @param Function errorCallback Callback to be called when an error occurs * @return Boolean Success of failure when loading synchronously */ _loadScript = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; var async = successCallback != false; var uri = _namespace.mapIdentifierToUri(identifier); var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback }; var xhr = _createXmlHttpRequest(); xhr.open("GET", uri, async); if (async) { xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); successCallback(); return; } event.status = xhr.status; _dispatchEvent('includeError', event); errorCallback && errorCallback(); } }; } xhr.send(null); if (!async) { if (_isHttpRequestSuccessful(xhr.status || 0)) { _createScript(xhr.responseText); _dispatchEvent('include', event); return true; } event.status = xhr.status; _dispatchEvent('includeError', event); return false; } }; /** * Includes a remote javascript file identified by the specified namespace string. The identifier * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the remote script has been included */ _namespace.include = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; // checks if the identifier is not already included if (_includedIdentifiers[identifier]) { successCallback && successCallback(); return true; } if (successCallback) { _loadScript(identifier, function() { _includedIdentifiers[identifier] = true; successCallback(); }, errorCallback); } else { if (_loadScript(identifier)) { _includedIdentifiers[identifier] = true; return true; } return false; } }; + /** + * Add an identifier to the list of included scripts without actually loading it. + * + * @public + * @param String identifier The namespace string + */ + _namespace.provide = function(identifier) { + if (!identifier in _includedIdentifiers) { + _includedItentifiers[identifier] = true; + return true; + } + return false; + }; + /** * Imports properties from the specified namespace to the global space (ie. under window) * * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) * which will import all properties from the namespace. * * If not, the targeted namespace will be imported (ie. if com.test is imported, the test object * will now be global). If the targeted object is not found, it will be included using include(). * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude */ _namespace.use = function(identifier) { var identifiers = _toArray(identifier); var callback = arguments[1] || false; var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; var event = { 'identifier': identifier }; for (var i = 0; i < identifiers.length; i++) { identifier = identifiers[i]; var parts = identifier.split(Namespace.separator); var target = parts.pop(); var ns = _namespace(parts.join(Namespace.separator)); if (target == '*') { // imports all objects from the identifier, can't use include() in that case for (var objectName in ns) { window[objectName] = ns[objectName]; } } else { // imports only one object if (ns[target]) { // the object exists, import it window[target] = ns[target]; } else { // the object does not exist if (autoInclude) { // try to auto include it if (callback) { _namespace.include(identifier, function() { window[target] = ns[target]; if (i + 1 < identifiers.length) { // we continue to unpack the rest from here _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); } else { // no more identifiers to unpack _dispatchEvent('use', event); callback && callback(); } }); return; } else { _namespace.include(identifier); window[target] = ns[target]; } } } } } // all identifiers have been unpacked _dispatchEvent('use', event); callback && callback(); }; /** * Binds the include() and unpack() method to a specified identifier * * @public * @param String identifier The namespace identifier * @return Object */ _namespace.from = function(identifier) { return { /** * Includes the identifier specified in from() * * @see Namespace.include() */ include: function() { var callback = arguments[0] || false; _namespace.include(identifier, callback); }, /** * Includes the identifier specified in from() and unpack * the specified indentifier in _identifier * * @see Namespace.use() */ use: function(_identifier) { var callback = arguments[1] || false; if (_identifier.charAt(0) == '.') { _identifier = identifier + _identifier; } if (callback) { _namespace.include(identifier, function() { _namespace.use(_identifier, callback, false); }); } else { _namespace.include(identifier); _namespace.use(_identifier, callback, false); } } }; }; /** * Registers a function to be called when the specified event is dispatched * * @param String eventName * @param Function callback */ _namespace.addEventListener = function(eventName, callback) { if (!_listeners[eventName]) _listeners[eventName] = []; _listeners[eventName].push(callback); }; /** * Unregisters an event listener * * @param String eventName * @param Function callback */ _namespace.removeEventListener = function(eventName, callback) { if (!_listeners[eventName]) return; for (var i = 0; i < _listeners[eventName].length; i++) { if (_listeners[eventName][i] == callback) { delete _listeners[eventName][i]; return; } } }; /** * Adds methods to javascript native's object * Inspired by http://thinkweb2.com/projects/prototype/namespacing-made-easy/ * * @public */ _namespace.registerNativeExtensions = function() { /** * @see Namespace() */ String.prototype.namespace = function() { var klasses = arguments[0] || {}; return _namespace(this.valueOf(), klasses); }; /** * @see Namespace.include() */ String.prototype.include = function() { var callback = arguments[0] || false; return _namespace.include(this.valueOf(), callback); } + /** + * @see Namespace.provide() + */ + String.prototype.provide = function() { + return _namespace.provide(this.valueOf()); + }; /** * @see Namespace.use() */ String.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this.valueOf(), callback); } /** * @see Namespace.from() */ String.prototype.from = function() { return _namespace.from(this.valueOf()); } /** * @see Namespace.use() */ Array.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this, callback); } }; return _namespace; })(); /** * Namespace segment separator * * @var String */ Namespace.separator = '.'; /** * Base uri when using Namespace.include() * Must end with a slash * * @var String */ Namespace.baseUri = './'; /** * Whether to automatically call Namespace.include() when Namespace.import() * does not find the targeted object. * * @var Boolean */ Namespace.autoInclude = true;
smith/namespacedotjs
8567e993a56a10df0824c80086427b8ac9ab7879
missing documentation and added include event
diff --git a/Namespace.js b/Namespace.js index 9880413..d66cc89 100644 --- a/Namespace.js +++ b/Namespace.js @@ -1,431 +1,439 @@ /* Script: Namespace.js Namespace utility Copyright: Copyright (c) 2009 Maxime Bouroumeau-Fuseau License: MIT-style license. Version: 1.0 */ var Namespace = (function() { var _listeners = {}; var _includedIdentifiers = []; - var _isIE = navigator.userAgent.indexOf('MSIE') != -1; - var _isOpera = window.opera ? true : false; /** * Returns an object in an array unless the object is an array * * @param mixed obj * @return Array */ var _toArray = function(obj) { // checks if it's an array if (typeof(obj) == 'object' && obj.sort) { return obj; } return new Array(obj); }; /** + * Creates an XMLHttpRequest object * + * @return XMLHttpRequest */ var _createXmlHttpRequest = function() { var xhr; try { xhr = new XMLHttpRequest() } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) { throw new Error( "This browser does not support XMLHttpRequest." ) } } } } } return xhr; }; /** * Checks if an http request is successful based on its status code. * Borrowed from dojo (http://www.dojotoolkit.org). * * @param Integer status Http status code * @return Boolean */ var _isHttpRequestSuccessful = function(status) { return (status >= 200 && status < 300) || // Boolean status == 304 || // allow any 2XX response code status == 1223 || // get it out of the cache (!status && (location.protocol == "file:" || location.protocol == "chrome:") ); // Internet Explorer mangled the status code }; /** + * Creates a script tag with the specified data as content * + * @param String data The content of the script */ var _createScript = function(data) { var script = document.createElement('script'); script.type = 'text/javascript'; script.text = data; document.body.appendChild(script); }; - /** - * - */ - var _loadScript = function(uri) { - var successCallback = arguments[1] || false; - var errorCallback = arguments[2] || false; - var async = successCallback != false; - var event = { 'uri': uri, 'async': async, 'callback': successCallback }; - - var xhr = _createXmlHttpRequest(); - xhr.open("GET", uri, async); - - if (async) { - xhr.onreadystatechange = function() { - if (xhr.readyState == 4) { - if (_isHttpRequestSuccessful(xhr.status || 0)) { - _createScript(xhr.responseText); - successCallback(); - return; - } - event.status = xhr.status; - _dispatchEvent('includeError', event); - errorCallback && errorCallback(); - } - }; - } - - xhr.send(null); - - if (!async) { - if (_isHttpRequestSuccessful(xhr.status || 0)) { - _createScript(xhr.responseText); - return true; - } - event.status = xhr.status; - _dispatchEvent('includeError', event); - return false; - } - }; - /** * Dispatches an event * * @param String eventName * @param Object properties */ var _dispatchEvent = function(eventName, properties) { if (!_listeners[eventName]) return; properties.event = eventName; for (var i = 0; i < _listeners[eventName].length; i++) { _listeners[eventName][i](properties); } }; /** * Creates an Object following the specified namespace identifier. * * @public * @param String identifier The namespace string * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace * @return Object The most inner object */ var _namespace = function(identifier) { var klasses = arguments[1] || false; var ns = window; if (identifier != '') { var parts = identifier.split(Namespace.separator); for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { ns[parts[i]] = {}; } ns = ns[parts[i]]; } } if (klasses) { for (var klass in klasses) { ns[klass] = klasses[klass]; } } _dispatchEvent('create', { 'identifier': identifier }); return ns; }; /** * Checks if the specified identifier is defined * * @public * @param String identifier The namespace string * @return Boolean */ _namespace.exist = function(identifier) { if (identifier == '') return true; var parts = identifier.split(Namespace.separator); var ns = window; for (var i = 0; i < parts.length; i++) { if (!ns[parts[i]]) { return false; } ns = ns[parts[i]]; } return true; }; /** * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. * * @public * @param String identifier The namespace identifier * @return String The uri */ _namespace.mapIdentifierToUri = function(identifier) { var regexp = new RegExp('\\' + Namespace.separator, 'g'); return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; }; + /** + * Loads a remote script atfer mapping the identifier to an uri + * + * @param String identifier The namespace identifier + * @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded + * @param Function errorCallback Callback to be called when an error occurs + * @return Boolean Success of failure when loading synchronously + */ + _loadScript = function(identifier) { + var successCallback = arguments[1] || false; + var errorCallback = arguments[2] || false; + var async = successCallback != false; + var uri = _namespace.mapIdentifierToUri(identifier); + var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback }; + + var xhr = _createXmlHttpRequest(); + xhr.open("GET", uri, async); + + if (async) { + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (_isHttpRequestSuccessful(xhr.status || 0)) { + _createScript(xhr.responseText); + _dispatchEvent('include', event); + successCallback(); + return; + } + event.status = xhr.status; + _dispatchEvent('includeError', event); + errorCallback && errorCallback(); + } + }; + } + + xhr.send(null); + + if (!async) { + if (_isHttpRequestSuccessful(xhr.status || 0)) { + _createScript(xhr.responseText); + _dispatchEvent('include', event); + return true; + } + event.status = xhr.status; + _dispatchEvent('includeError', event); + return false; + } + }; + /** * Includes a remote javascript file identified by the specified namespace string. The identifier * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the remote script has been included */ _namespace.include = function(identifier) { var successCallback = arguments[1] || false; var errorCallback = arguments[2] || false; - var uri = _namespace.mapIdentifierToUri(identifier); // checks if the identifier is not already included if (_includedIdentifiers[identifier]) { successCallback && successCallback(); return true; } if (successCallback) { - _loadScript(uri, function() { + _loadScript(identifier, function() { _includedIdentifiers[identifier] = true; successCallback(); }, errorCallback); } else { - if (_loadScript(uri)) { + if (_loadScript(identifier)) { _includedIdentifiers[identifier] = true; return true; } return false; } }; /** * Imports properties from the specified namespace to the global space (ie. under window) * * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) - * which will unpack all properties from the namespace. + * which will import all properties from the namespace. * - * If not, the targeted namespace will be unpacked (ie. if com.test is unpacked, the test object - * will now be global). - * If the targeted object is not found, it will be included using include(). + * If not, the targeted namespace will be imported (ie. if com.test is imported, the test object + * will now be global). If the targeted object is not found, it will be included using include(). * * @public * @param String identifier The namespace string * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude */ _namespace.use = function(identifier) { var identifiers = _toArray(identifier); var callback = arguments[1] || false; var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; var event = { 'identifier': identifier }; for (var i = 0; i < identifiers.length; i++) { identifier = identifiers[i]; var parts = identifier.split(Namespace.separator); var target = parts.pop(); var ns = _namespace(parts.join(Namespace.separator)); if (target == '*') { // imports all objects from the identifier, can't use include() in that case for (var objectName in ns) { window[objectName] = ns[objectName]; } } else { // imports only one object if (ns[target]) { // the object exists, import it window[target] = ns[target]; } else { // the object does not exist if (autoInclude) { // try to auto include it if (callback) { _namespace.include(identifier, function() { window[target] = ns[target]; if (i + 1 < identifiers.length) { // we continue to unpack the rest from here _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); } else { // no more identifiers to unpack - _dispatchEvent('unpack', event); + _dispatchEvent('use', event); callback && callback(); } }); return; } else { _namespace.include(identifier); window[target] = ns[target]; } } } } } // all identifiers have been unpacked - _dispatchEvent('unpack', event); + _dispatchEvent('use', event); callback && callback(); }; /** * Binds the include() and unpack() method to a specified identifier * * @public * @param String identifier The namespace identifier * @return Object */ _namespace.from = function(identifier) { return { /** * Includes the identifier specified in from() * * @see Namespace.include() */ include: function() { var callback = arguments[0] || false; _namespace.include(identifier, callback); }, /** * Includes the identifier specified in from() and unpack * the specified indentifier in _identifier * * @see Namespace.use() */ use: function(_identifier) { var callback = arguments[1] || false; if (_identifier.charAt(0) == '.') { _identifier = identifier + _identifier; } if (callback) { _namespace.include(identifier, function() { _namespace.use(_identifier, callback, false); }); } else { _namespace.include(identifier); _namespace.use(_identifier, callback, false); } } }; }; /** * Registers a function to be called when the specified event is dispatched * * @param String eventName * @param Function callback */ _namespace.addEventListener = function(eventName, callback) { if (!_listeners[eventName]) _listeners[eventName] = []; _listeners[eventName].push(callback); }; /** * Unregisters an event listener * * @param String eventName * @param Function callback */ _namespace.removeEventListener = function(eventName, callback) { if (!_listeners[eventName]) return; for (var i = 0; i < _listeners[eventName].length; i++) { if (_listeners[eventName][i] == callback) { delete _listeners[eventName][i]; return; } } }; /** * Adds methods to javascript native's object * * @public */ _namespace.registerNativeExtensions = function() { /** * @see Namespace() */ String.prototype.namespace = function() { var klasses = arguments[0] || {}; return _namespace(this.valueOf(), klasses); }; /** * @see Namespace.include() */ String.prototype.include = function() { var callback = arguments[0] || false; return _namespace.include(this.valueOf(), callback); } /** * @see Namespace.unpack() */ String.prototype.use = function() { var callback = arguments[0] || false; return _namespace.use(this.valueOf(), callback); } /** * @see Namespace.from() */ String.prototype.from = function() { return _namespace.from(this.valueOf()); } }; return _namespace; })(); /** * Namespace segment separator * * @var String */ Namespace.separator = '.'; /** * Base uri when using Namespace.include() * Must end with a slash * * @var String */ Namespace.baseUri = './'; /** * Whether to automatically call Namespace.include() when Namespace.import() * does not find the targeted object. * * @var Boolean */ Namespace.autoInclude = true; diff --git a/example/sandbox.js b/example/sandbox.js index ba8ab81..5002cdc 100644 --- a/example/sandbox.js +++ b/example/sandbox.js @@ -1,50 +1,50 @@ // creates an empty namespace Namespace('com.sandbox'); // creates or use a namespace and fill it with the specified properties Namespace('com.sandbox', { Console: { log: function(message) { var element = document.getElementById('console'); element.innerHTML = element.innerHTML + message + '<br />'; } } }); // calls Console using the fully qualified name (fqn) com.sandbox.Console.log('hello world'); // imports all properties from com.sandbox into the global space Namespace.use('com.sandbox.*'); Console.log('unpacked hello world'); // includes com/sandbox/SayHiClass.js // as we use a callback, file is loaded asynchronously Namespace.include('com.sandbox.SayHiClass', function() { new com.sandbox.SayHiClass(); }); // auto includes com/sandbox/MyNameIsClass.js file and imports MyNameIsClass into the global space // unpack() will use include(). will be async as we use a callback Namespace.use('com.sandbox.MyNameIsClass', function() { new MyNameIsClass('peter'); }); // imports all properties from com.sandbox.classes after including the file com/sandbox/classes.js // the use() identifier can also be relative to the identifier used in from() by starting // with a dot (would be .* in this case) Namespace.from('com.sandbox.classes').use('com.sandbox.classes.*', function() { new MyClass1(); new MyClass2(); }); // register a listener for the includeError event Namespace.addEventListener('includeError', function(event) { - Console.log('an error occured loading ' + event.uri); + Console.log('an error occured loading ' + event.identifier); }); // try to include an inexistant file Namespace.include('com.sandbox.toto');
smith/namespacedotjs
a64c08aafe64fa34aa1fbc156d6dcd27acf9cad6
first release
diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..a8e01b0 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,24 @@ +NAMESPACE.JS + +The MIT License + +Copyright (c) 2009 Maxime Bouroumeau-Fuseau + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/Namespace.js b/Namespace.js new file mode 100644 index 0000000..9880413 --- /dev/null +++ b/Namespace.js @@ -0,0 +1,431 @@ +/* +Script: Namespace.js + Namespace utility + +Copyright: + Copyright (c) 2009 Maxime Bouroumeau-Fuseau + +License: + MIT-style license. + +Version: + 1.0 +*/ +var Namespace = (function() { + + var _listeners = {}; + var _includedIdentifiers = []; + var _isIE = navigator.userAgent.indexOf('MSIE') != -1; + var _isOpera = window.opera ? true : false; + + /** + * Returns an object in an array unless the object is an array + * + * @param mixed obj + * @return Array + */ + var _toArray = function(obj) { + // checks if it's an array + if (typeof(obj) == 'object' && obj.sort) { + return obj; + } + return new Array(obj); + }; + + /** + * + */ + var _createXmlHttpRequest = function() { + var xhr; + try { xhr = new XMLHttpRequest() } catch(e) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) { + try { xhr = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) { + try { xhr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) { + throw new Error( "This browser does not support XMLHttpRequest." ) + } + } + } + } + } + return xhr; + }; + + /** + * Checks if an http request is successful based on its status code. + * Borrowed from dojo (http://www.dojotoolkit.org). + * + * @param Integer status Http status code + * @return Boolean + */ + var _isHttpRequestSuccessful = function(status) { + return (status >= 200 && status < 300) || // Boolean + status == 304 || // allow any 2XX response code + status == 1223 || // get it out of the cache + (!status && (location.protocol == "file:" || location.protocol == "chrome:") ); // Internet Explorer mangled the status code + }; + + /** + * + */ + var _createScript = function(data) { + var script = document.createElement('script'); + script.type = 'text/javascript'; + script.text = data; + document.body.appendChild(script); + }; + + /** + * + */ + var _loadScript = function(uri) { + var successCallback = arguments[1] || false; + var errorCallback = arguments[2] || false; + var async = successCallback != false; + var event = { 'uri': uri, 'async': async, 'callback': successCallback }; + + var xhr = _createXmlHttpRequest(); + xhr.open("GET", uri, async); + + if (async) { + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (_isHttpRequestSuccessful(xhr.status || 0)) { + _createScript(xhr.responseText); + successCallback(); + return; + } + event.status = xhr.status; + _dispatchEvent('includeError', event); + errorCallback && errorCallback(); + } + }; + } + + xhr.send(null); + + if (!async) { + if (_isHttpRequestSuccessful(xhr.status || 0)) { + _createScript(xhr.responseText); + return true; + } + event.status = xhr.status; + _dispatchEvent('includeError', event); + return false; + } + }; + + /** + * Dispatches an event + * + * @param String eventName + * @param Object properties + */ + var _dispatchEvent = function(eventName, properties) { + if (!_listeners[eventName]) return; + properties.event = eventName; + for (var i = 0; i < _listeners[eventName].length; i++) { + _listeners[eventName][i](properties); + } + }; + + /** + * Creates an Object following the specified namespace identifier. + * + * @public + * @param String identifier The namespace string + * @param Object klasses (OPTIONAL) An object which properties will be added to the namespace + * @return Object The most inner object + */ + var _namespace = function(identifier) { + var klasses = arguments[1] || false; + var ns = window; + + if (identifier != '') { + var parts = identifier.split(Namespace.separator); + for (var i = 0; i < parts.length; i++) { + if (!ns[parts[i]]) { + ns[parts[i]] = {}; + } + ns = ns[parts[i]]; + } + } + + if (klasses) { + for (var klass in klasses) { + ns[klass] = klasses[klass]; + } + } + + _dispatchEvent('create', { 'identifier': identifier }); + return ns; + }; + + /** + * Checks if the specified identifier is defined + * + * @public + * @param String identifier The namespace string + * @return Boolean + */ + _namespace.exist = function(identifier) { + if (identifier == '') return true; + + var parts = identifier.split(Namespace.separator); + var ns = window; + for (var i = 0; i < parts.length; i++) { + if (!ns[parts[i]]) { + return false; + } + ns = ns[parts[i]]; + } + + return true; + }; + + /** + * Maps an identifier to a uri. Is public so it can be overriden by custom scripts. + * + * @public + * @param String identifier The namespace identifier + * @return String The uri + */ + _namespace.mapIdentifierToUri = function(identifier) { + var regexp = new RegExp('\\' + Namespace.separator, 'g'); + return Namespace.baseUri + identifier.replace(regexp, '/') + '.js'; + }; + + /** + * Includes a remote javascript file identified by the specified namespace string. The identifier + * must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended. + * + * @public + * @param String identifier The namespace string + * @param Function callback (OPTIONAL) A function to call when the remote script has been included + */ + _namespace.include = function(identifier) { + var successCallback = arguments[1] || false; + var errorCallback = arguments[2] || false; + var uri = _namespace.mapIdentifierToUri(identifier); + + // checks if the identifier is not already included + if (_includedIdentifiers[identifier]) { + successCallback && successCallback(); + return true; + } + + if (successCallback) { + _loadScript(uri, function() { + _includedIdentifiers[identifier] = true; + successCallback(); + }, errorCallback); + } else { + if (_loadScript(uri)) { + _includedIdentifiers[identifier] = true; + return true; + } + return false; + } + }; + + /** + * Imports properties from the specified namespace to the global space (ie. under window) + * + * The identifier string can contain the * wildcard character as its last segment (eg: com.test.*) + * which will unpack all properties from the namespace. + * + * If not, the targeted namespace will be unpacked (ie. if com.test is unpacked, the test object + * will now be global). + * If the targeted object is not found, it will be included using include(). + * + * @public + * @param String identifier The namespace string + * @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used) + * @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude + */ + _namespace.use = function(identifier) { + var identifiers = _toArray(identifier); + var callback = arguments[1] || false; + var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude; + var event = { 'identifier': identifier }; + + for (var i = 0; i < identifiers.length; i++) { + identifier = identifiers[i]; + + var parts = identifier.split(Namespace.separator); + var target = parts.pop(); + var ns = _namespace(parts.join(Namespace.separator)); + + if (target == '*') { + // imports all objects from the identifier, can't use include() in that case + for (var objectName in ns) { + window[objectName] = ns[objectName]; + } + } else { + // imports only one object + if (ns[target]) { + // the object exists, import it + window[target] = ns[target]; + } else { + // the object does not exist + if (autoInclude) { + // try to auto include it + if (callback) { + _namespace.include(identifier, function() { + window[target] = ns[target]; + + if (i + 1 < identifiers.length) { + // we continue to unpack the rest from here + _namespace.unpack(identifiers.slice(i + 1), callback, autoInclude); + } else { + // no more identifiers to unpack + _dispatchEvent('unpack', event); + callback && callback(); + } + }); + return; + } else { + _namespace.include(identifier); + window[target] = ns[target]; + } + } + } + } + + } + + // all identifiers have been unpacked + _dispatchEvent('unpack', event); + callback && callback(); + }; + + /** + * Binds the include() and unpack() method to a specified identifier + * + * @public + * @param String identifier The namespace identifier + * @return Object + */ + _namespace.from = function(identifier) { + return { + /** + * Includes the identifier specified in from() + * + * @see Namespace.include() + */ + include: function() { + var callback = arguments[0] || false; + _namespace.include(identifier, callback); + }, + /** + * Includes the identifier specified in from() and unpack + * the specified indentifier in _identifier + * + * @see Namespace.use() + */ + use: function(_identifier) { + var callback = arguments[1] || false; + if (_identifier.charAt(0) == '.') { + _identifier = identifier + _identifier; + } + + if (callback) { + _namespace.include(identifier, function() { + _namespace.use(_identifier, callback, false); + }); + } else { + _namespace.include(identifier); + _namespace.use(_identifier, callback, false); + } + } + }; + }; + + /** + * Registers a function to be called when the specified event is dispatched + * + * @param String eventName + * @param Function callback + */ + _namespace.addEventListener = function(eventName, callback) { + if (!_listeners[eventName]) _listeners[eventName] = []; + _listeners[eventName].push(callback); + }; + + /** + * Unregisters an event listener + * + * @param String eventName + * @param Function callback + */ + _namespace.removeEventListener = function(eventName, callback) { + if (!_listeners[eventName]) return; + for (var i = 0; i < _listeners[eventName].length; i++) { + if (_listeners[eventName][i] == callback) { + delete _listeners[eventName][i]; + return; + } + } + }; + + /** + * Adds methods to javascript native's object + * + * @public + */ + _namespace.registerNativeExtensions = function() { + /** + * @see Namespace() + */ + String.prototype.namespace = function() { + var klasses = arguments[0] || {}; + return _namespace(this.valueOf(), klasses); + }; + /** + * @see Namespace.include() + */ + String.prototype.include = function() { + var callback = arguments[0] || false; + return _namespace.include(this.valueOf(), callback); + } + /** + * @see Namespace.unpack() + */ + String.prototype.use = function() { + var callback = arguments[0] || false; + return _namespace.use(this.valueOf(), callback); + } + /** + * @see Namespace.from() + */ + String.prototype.from = function() { + return _namespace.from(this.valueOf()); + } + }; + + return _namespace; +})(); + +/** + * Namespace segment separator + * + * @var String + */ +Namespace.separator = '.'; + +/** + * Base uri when using Namespace.include() + * Must end with a slash + * + * @var String + */ +Namespace.baseUri = './'; + +/** + * Whether to automatically call Namespace.include() when Namespace.import() + * does not find the targeted object. + * + * @var Boolean + */ +Namespace.autoInclude = true; + diff --git a/example/com/sandbox/MyNameIsClass.js b/example/com/sandbox/MyNameIsClass.js new file mode 100644 index 0000000..78bf0b6 --- /dev/null +++ b/example/com/sandbox/MyNameIsClass.js @@ -0,0 +1,9 @@ + +Namespace('com.sandbox', { + + MyNameIsClass: function(name) { + com.sandbox.Console.log('my name is ' + name); + return {}; + } + +}); diff --git a/example/com/sandbox/SayHiClass.js b/example/com/sandbox/SayHiClass.js new file mode 100644 index 0000000..a62fcca --- /dev/null +++ b/example/com/sandbox/SayHiClass.js @@ -0,0 +1,9 @@ + +Namespace('com.sandbox', { + + SayHiClass: function() { + com.sandbox.Console.log('hi'); + return {}; + } + +}); diff --git a/example/com/sandbox/classes.js b/example/com/sandbox/classes.js new file mode 100644 index 0000000..4282d10 --- /dev/null +++ b/example/com/sandbox/classes.js @@ -0,0 +1,14 @@ + +Namespace('com.sandbox.classes', { + + MyClass1: function() { + com.sandbox.Console.log('MyClass1'); + return {}; + }, + + MyClass2: function() { + com.sandbox.Console.log('MyClass2'); + return {}; + } + +}); diff --git a/example/index.html b/example/index.html new file mode 100644 index 0000000..21e5110 --- /dev/null +++ b/example/index.html @@ -0,0 +1,12 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <title>sandbox</title> + <script type="text/javascript" src="../Namespace.js"></script> + </head> + <body> + <div id="console"></div> + <script type="text/javascript" src="sandbox.js"></script> + </body> +</html> diff --git a/example/sandbox.js b/example/sandbox.js new file mode 100644 index 0000000..ba8ab81 --- /dev/null +++ b/example/sandbox.js @@ -0,0 +1,50 @@ + +// creates an empty namespace +Namespace('com.sandbox'); + +// creates or use a namespace and fill it with the specified properties +Namespace('com.sandbox', { + + Console: { + log: function(message) { + var element = document.getElementById('console'); + element.innerHTML = element.innerHTML + message + '<br />'; + } + } + +}); + +// calls Console using the fully qualified name (fqn) +com.sandbox.Console.log('hello world'); + +// imports all properties from com.sandbox into the global space +Namespace.use('com.sandbox.*'); +Console.log('unpacked hello world'); + +// includes com/sandbox/SayHiClass.js +// as we use a callback, file is loaded asynchronously +Namespace.include('com.sandbox.SayHiClass', function() { + new com.sandbox.SayHiClass(); +}); + +// auto includes com/sandbox/MyNameIsClass.js file and imports MyNameIsClass into the global space +// unpack() will use include(). will be async as we use a callback +Namespace.use('com.sandbox.MyNameIsClass', function() { + new MyNameIsClass('peter'); +}); + +// imports all properties from com.sandbox.classes after including the file com/sandbox/classes.js +// the use() identifier can also be relative to the identifier used in from() by starting +// with a dot (would be .* in this case) +Namespace.from('com.sandbox.classes').use('com.sandbox.classes.*', function() { + new MyClass1(); + new MyClass2(); +}); + +// register a listener for the includeError event +Namespace.addEventListener('includeError', function(event) { + Console.log('an error occured loading ' + event.uri); +}); +// try to include an inexistant file +Namespace.include('com.sandbox.toto'); +
openstreetmap/shp2osm
bfe015a390f3363ff919c0e6ff1b653f1d5bc4bf
Improve GDAL installation information.
diff --git a/polyshp2osm.py b/polyshp2osm.py index de63c27..e502039 100644 --- a/polyshp2osm.py +++ b/polyshp2osm.py @@ -1,397 +1,408 @@ #!/usr/bin/python """ This script is designed to act as assistance in converting shapefiles to OpenStreetMap data. This file is optimized and tested with MassGIS shapefiles, converted to EPSG:4326 before being passed to the script. You can perform this conversion with ogr2ogr -t_srs EPSG:4326 new_file.shp old_file.shp -Requires OGR: Tested with 1.3.2 and 1.6.0 - It is expected that you will modify the fixed_tags, tag_mapping, and boring_tags attributes of this script before running. You should read, or at least skim, the code up until it says: DO NOT CHANGE AFTER THIS LINE. to accomodate your own data. """ __author__ = "Christopher Schmidt <[email protected]>" __version__ = "$Id$" +gdal_install = """ +Installing GDAL depends on your platform. Information is available at: + + http://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries + +For Debian-based systems: + + apt-get install python-gdal + +will usually suffice. +""" + # These tags are attached to all exterior ways. You can put any key/value pairs # in this dictionary. fixed_tags = { 'source': 'MassGIS OpenSpace (http://www.mass.gov/mgis/osp.htm)', 'area': 'yes', 'created_by': 'polyshp2osm' } # Here are a number of functions: These functions define tag mappings. The API # For these functions is that they are passed the attributes from a feature, # and they return a list of two-tuples which match to key/value pairs. def access(data): """Access restrictions.""" keys = { 'Y': 'yes', 'N': 'private', 'L': 'restricted' } if 'pub_access' in data: if data['pub_access'] in keys: return [('access', keys[data['pub_access']])] return None def protection(data): keys = { 'P': 'perpetuity', 'T': 'temporary', 'L': 'limited', } if 'lev_prot' in data: if data['lev_prot'] in keys: return [('protected', keys[data['lev_prot']])] return None def owner_type(data): """See wiki:Key:ownership""" keys = { 'F': 'national', 'S': 'state', 'C': 'county', 'M': 'municipal', 'N': 'private_nonprofit', 'P': 'private', 'B': 'public_nonprofit', 'L': 'land_trust', 'G': 'conservation_rganization', 'I': 'inholding', } if 'owner_type' in data: if data['owner_type'] in keys: return [['ownership', keys[data['owner_type']]]] def purpose(data): """Based on a discussion on IRC""" keys = { 'R': [('leisure', 'recreation_ground')], 'C': [('leisure', 'nature_reserve'), ('landuse', 'conservation')], 'B': [('landuse','conservation'), ('leisure','recreation_ground')], 'H': [('historical', 'yes')], 'A': [('agricultural', 'yes'), ('landuse','farm')], 'W': [('landuse', 'resevoir')], 'S': [('scenic','yes')], 'F': [('landuse','land')], 'Q': [('landuse','conservation')], 'U': [('water','yes')] } if 'prim_purp' in data: if data['prim_purp'] in keys: return keys[data['prim_purp']] def name_tags(data): """This function returns two things: a 'pretty' name to use, and may return a landuse of either 'cemetery' or 'forest' if the name contains those words; based on evaluation the dataset in question.""" tags = [] name = data.get('site_name', None) if not name: return name = name.title() if "cemetery" in name.lower(): tags.append(['landuse', 'cemetery']) elif "forest" in name.lower(): tags.append(['landuse', 'forest']) tags.append(['name', name]) return tags def cal_date(data): """Return YYYY-MM-DD or YYYY formatted dates, based on (m)m/(d)d/yyyy dates""" date = data.get('cal_date_r', None) if not date: return try: m, d, y = map(int, date.split("/")) if m == 1 and d == 1: return [['start_date', '%4i' % y]] return [['start_date', '%04i-%02i-%02i' % (y, m, d)]] except: print "Invalid date: %s" % date return None # The most important part of the code: define a set of key/value pairs # to iterate over to generate keys. This is a list of two-tuples: first # is a 'key', which is only used if the second value is a string. In # that case, it is a map of lowercased fielnames to OSM tag names: so # fee_owner maps to 'owner' in the OSM output. # if the latter is callable (has a __call__; is a function), then that # method is called, passing in a dict of feature attributes with # lowercased key names. Those functions can then return a list of # two-tuples to be used as tags, or nothin' to skip the tags. tag_mapping = [ ('fee_owner', 'owner'), ('cal_date', cal_date), ('pub_access', access), ('lev_prot', protection), ('owner_type', owner_type), ('prim_purp', purpose), ('site_name', name_tags), ] # These tags are not exported, even with the source data; this should be # used for tags which are usually calculated in a GIS. AREA and LEN are # common. boring_tags = [ 'AREA', 'LEN', 'GIS_ACRES' ] # Namespace is used to prefix existing data attributes. If 'None', or # '--no-source' is set, then source attributes are not exported, only # attributes in tag_mapping. namespace = "massgis" #namespace = None # Uncomment the "DONT_RUN = False" line to get started. -#DONT_RUN = True -DONT_RUN = False +DONT_RUN = True +#DONT_RUN = False # =========== DO NOT CHANGE AFTER THIS LINE. =========================== # Below here is regular code, part of the file. This is not designed to # be modified by users. # ====================================================================== import sys try: try: from osgeo import ogr except ImportError: import ogr except ImportError: + __doc__ += gdal_install if DONT_RUN: print __doc__ sys.exit(2) - print "OGR Python Bindings not installed. Fix that, please." + print "OGR Python Bindings not installed.\n%s" % gdal_install sys.exit(1) def close_file(): """ Internal. Close an open file.""" global open_file if not open_file.closed: open_file.write("</osm>") open_file.close() def start_new_file(): """ Internal. Open a new file, closing existing file if neccesary.""" global open_file, file_counter file_counter += 1 if open_file: close_file() open_file = open("%s.%s.osm" % (file_name, file_counter), "w") print >>open_file, "<osm version='0.5'>" def clean_attr(val): """Internal. Hacky way to make attribute XML safe.""" val = str(val) val = val.replace("&", "&amp;").replace("'", "&quot;").replace("<", "&lt;").replace(">", "&gt;").strip() return val def add_ring_nodes(ring): """Internal. Write the first ring nodes.""" global open_file, id_counter ids = [] if range(ring.GetPointCount() - 1) == 0 or ring.GetPointCount() == 0: print >>sys.stderr, "Degenerate ring." return for count in range(ring.GetPointCount()-1): ids.append(id_counter) print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count id_counter += 1 return ids def add_ring_way(ring): """Internal. write out the 'holes' in a polygon.""" global open_file, id_counter ids = [] for count in range(ring.GetPointCount()-1): ids.append(id_counter) print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count id_counter += 1 if len(ids) == 0: return None print >>open_file, "<way id='-%s'>" % id_counter way_id = id_counter id_counter += 1 for i in ids: print >>open_file, "<nd ref='-%s' />" % i print >>open_file, "<nd ref='-%s' />" % ids[0] print >>open_file, "</way>" return way_id open_file = None file_name = None id_counter = 1 file_counter = 0 counter = 0 class AppError(Exception): pass def run(filename, slice_count=1, obj_count=50000, output_location=None, no_source=False): """Run the converter. Requires open_file, file_name, id_counter, file_counter, counter to be defined in global space; not really a very good singleton.""" global id_counter, file_counter, counter, file_name, open_file, namespace if no_source: namespace=None if output_location: file_name = output_location ds = ogr.Open(filename) if not ds: raise AppError("OGR Could not open the file %s" % filename) l = ds.GetLayer(0) max_objs_per_file = obj_count extent = l.GetExtent() if extent[0] < -180 or extent[0] > 180 or extent[2] < -90 or extent[2] > 90: raise AppError("Extent does not look like degrees; are you sure it is? \n(%s, %s, %s, %s)" % (extent[0], extent[2], extent[1], extent[3])) slice_width = (extent[1] - extent[0]) / slice_count seen = {} print "Running %s slices with %s base filename against shapefile %s" % ( slice_count, file_name, filename) for i in range(slice_count): l.ResetReading() l.SetSpatialFilterRect(extent[0] + slice_width * i, extent[2], extent[0] + (slice_width * (i + 1)), extent[3]) start_new_file() f = l.GetNextFeature() obj_counter = 0 last_obj_split = 0 while f: start_id_counter = id_counter if f.GetFID() in seen: f = l.GetNextFeature() continue seen[f.GetFID()] = True if (obj_counter - last_obj_split) > max_objs_per_file: print "Splitting file with %s objs" % (obj_counter - last_obj_split) start_new_file() last_obj_split = obj_counter ways = [] geom = f.GetGeometryRef() ring = geom.GetGeometryRef(0) ids = add_ring_nodes(ring) if not ids or len(ids) == 0: f = l.GetNextFeature() continue print >>open_file, "<way id='-%s'>" % id_counter ways.append(id_counter) id_counter += 1 for i in ids: print >>open_file, "<nd ref='-%s' />" % i print >>open_file, "<nd ref='-%s' />" % ids[0] field_count = f.GetFieldCount() fields = {} for field in range(field_count): value = f.GetFieldAsString(field) name = f.GetFieldDefnRef(field).GetName() if namespace and name and value and name not in boring_tags: print >>open_file, "<tag k='%s:%s' v='%s' />" % (namespace, name, clean_attr(value)) fields[name.lower()] = value tags={} for tag_name, map_value in tag_mapping: if hasattr(map_value, '__call__'): tag_values = map_value(fields) if tag_values: for tag in tag_values: tags[tag[0]] = tag[1] else: if tag_name in fields: tags[map_value] = fields[tag_name].title() for key, value in tags.items(): if key and value: print >>open_file, "<tag k='%s' v='%s' />" % (key, clean_attr(value)) for name, value in fixed_tags.items(): print >>open_file, "<tag k='%s' v='%s' />" % (name, clean_attr(value)) print >>open_file, "</way>" if geom.GetGeometryCount() > 1: for i in range(1, geom.GetGeometryCount()): ways.append(add_ring_way(geom.GetGeometryRef(i))) print >>open_file, "<relation id='-%s'><tag k='type' v='multipolygon' />" % id_counter id_counter += 1 print >>open_file, '<member type="way" ref="-%s" role="outer" />' % ways[0] for way in ways[1:]: print >>open_file, '<member type="way" ref="-%s" role="inner" />' % way print >>open_file, "</relation>" counter += 1 f = l.GetNextFeature() obj_counter += (id_counter - start_id_counter) close_file() if __name__ == "__main__": if DONT_RUN: print __doc__ sys.exit(2) from optparse import OptionParser parse = OptionParser(usage="%prog [args] filename.shp", version=__version__) parse.add_option("-s", "--slice-count", dest="slice_count", help="Number of horizontal slices of data", default=1, action="store", type="int") parse.add_option("-o", "--obj-count", dest="obj_count", help="Target Maximum number of objects in a single .osm file", default=50000, type="int") parse.add_option("-n", "--no-source", dest="no_source", help="Do not store source attributes as tags.", action="store_true", default=False) parse.add_option("-l", "--output-location", dest="output_location", help="base filepath for output files.", default="poly_output") (options, args) = parse.parse_args() if not len(args): print "No shapefile name given!" parse.print_help() sys.exit(3) kw = {} for key in ('slice_count', 'obj_count', 'output_location', 'no_source'): kw[key] = getattr(options, key) try: run(args[0], **kw) except AppError, E: print "An error occurred: \n%s" % E
openstreetmap/shp2osm
34a73eb0d321e388b25f12676d0f960581e09907
more cleanup.
diff --git a/polyshp2osm.py b/polyshp2osm.py index 3368617..de63c27 100644 --- a/polyshp2osm.py +++ b/polyshp2osm.py @@ -1,366 +1,397 @@ #!/usr/bin/python """ This script is designed to act as assistance in converting shapefiles to OpenStreetMap data. This file is optimized and tested with MassGIS shapefiles, converted to EPSG:4326 before being passed to the script. You can perform this conversion with ogr2ogr -t_srs EPSG:4326 new_file.shp old_file.shp Requires OGR: Tested with 1.3.2 and 1.6.0 It is expected that you will modify the fixed_tags, tag_mapping, and boring_tags attributes of this script before running. You should read, or at least skim, the code up until it says: DO NOT CHANGE AFTER THIS LINE. to accomodate your own data. """ __author__ = "Christopher Schmidt <[email protected]>" __version__ = "$Id$" # These tags are attached to all exterior ways. You can put any key/value pairs # in this dictionary. fixed_tags = { 'source': 'MassGIS OpenSpace (http://www.mass.gov/mgis/osp.htm)', 'area': 'yes', 'created_by': 'polyshp2osm' } # Here are a number of functions: These functions define tag mappings. The API # For these functions is that they are passed the attributes from a feature, # and they return a list of two-tuples which match to key/value pairs. def access(data): """Access restrictions.""" keys = { 'Y': 'yes', 'N': 'private', 'L': 'restricted' } if 'pub_access' in data: if data['pub_access'] in keys: return [('access', keys[data['pub_access']])] return None def protection(data): keys = { 'P': 'perpetuity', 'T': 'temporary', 'L': 'limited', } if 'lev_prot' in data: if data['lev_prot'] in keys: return [('protected', keys[data['lev_prot']])] return None def owner_type(data): """See wiki:Key:ownership""" keys = { 'F': 'national', 'S': 'state', 'C': 'county', 'M': 'municipal', 'N': 'private_nonprofit', 'P': 'private', 'B': 'public_nonprofit', 'L': 'land_trust', 'G': 'conservation_rganization', 'I': 'inholding', } if 'owner_type' in data: if data['owner_type'] in keys: return [['ownership', keys[data['owner_type']]]] def purpose(data): """Based on a discussion on IRC""" keys = { 'R': [('leisure', 'recreation_ground')], 'C': [('leisure', 'nature_reserve'), ('landuse', 'conservation')], 'B': [('landuse','conservation'), ('leisure','recreation_ground')], 'H': [('historical', 'yes')], 'A': [('agricultural', 'yes'), ('landuse','farm')], 'W': [('landuse', 'resevoir')], 'S': [('scenic','yes')], 'F': [('landuse','land')], 'Q': [('landuse','conservation')], 'U': [('water','yes')] } if 'prim_purp' in data: if data['prim_purp'] in keys: return keys[data['prim_purp']] def name_tags(data): """This function returns two things: a 'pretty' name to use, and may return a landuse of either 'cemetery' or 'forest' if the name contains those words; based on evaluation the dataset in question.""" tags = [] name = data.get('site_name', None) if not name: return name = name.title() if "cemetery" in name.lower(): tags.append(['landuse', 'cemetery']) elif "forest" in name.lower(): tags.append(['landuse', 'forest']) tags.append(['name', name]) return tags def cal_date(data): """Return YYYY-MM-DD or YYYY formatted dates, based on (m)m/(d)d/yyyy dates""" date = data.get('cal_date_r', None) if not date: return try: m, d, y = map(int, date.split("/")) if m == 1 and d == 1: return [['start_date', '%4i' % y]] return [['start_date', '%04i-%02i-%02i' % (y, m, d)]] except: print "Invalid date: %s" % date return None # The most important part of the code: define a set of key/value pairs # to iterate over to generate keys. This is a list of two-tuples: first # is a 'key', which is only used if the second value is a string. In # that case, it is a map of lowercased fielnames to OSM tag names: so # fee_owner maps to 'owner' in the OSM output. # if the latter is callable (has a __call__; is a function), then that # method is called, passing in a dict of feature attributes with # lowercased key names. Those functions can then return a list of # two-tuples to be used as tags, or nothin' to skip the tags. tag_mapping = [ ('fee_owner', 'owner'), ('cal_date', cal_date), ('pub_access', access), ('lev_prot', protection), ('owner_type', owner_type), ('prim_purp', purpose), ('site_name', name_tags), ] # These tags are not exported, even with the source data; this should be # used for tags which are usually calculated in a GIS. AREA and LEN are # common. boring_tags = [ 'AREA', 'LEN', 'GIS_ACRES' ] +# Namespace is used to prefix existing data attributes. If 'None', or +# '--no-source' is set, then source attributes are not exported, only +# attributes in tag_mapping. + +namespace = "massgis" +#namespace = None + # Uncomment the "DONT_RUN = False" line to get started. -DONT_RUN = True -#DONT_RUN = False +#DONT_RUN = True +DONT_RUN = False # =========== DO NOT CHANGE AFTER THIS LINE. =========================== # Below here is regular code, part of the file. This is not designed to # be modified by users. # ====================================================================== import sys try: try: from osgeo import ogr except ImportError: import ogr except ImportError: if DONT_RUN: print __doc__ sys.exit(2) print "OGR Python Bindings not installed. Fix that, please." sys.exit(1) def close_file(): """ Internal. Close an open file.""" global open_file if not open_file.closed: open_file.write("</osm>") open_file.close() def start_new_file(): """ Internal. Open a new file, closing existing file if neccesary.""" global open_file, file_counter file_counter += 1 if open_file: close_file() open_file = open("%s.%s.osm" % (file_name, file_counter), "w") print >>open_file, "<osm version='0.5'>" def clean_attr(val): """Internal. Hacky way to make attribute XML safe.""" val = str(val) val = val.replace("&", "&amp;").replace("'", "&quot;").replace("<", "&lt;").replace(">", "&gt;").strip() return val def add_ring_nodes(ring): """Internal. Write the first ring nodes.""" global open_file, id_counter ids = [] if range(ring.GetPointCount() - 1) == 0 or ring.GetPointCount() == 0: print >>sys.stderr, "Degenerate ring." return for count in range(ring.GetPointCount()-1): ids.append(id_counter) print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count id_counter += 1 return ids def add_ring_way(ring): """Internal. write out the 'holes' in a polygon.""" global open_file, id_counter ids = [] for count in range(ring.GetPointCount()-1): ids.append(id_counter) print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count id_counter += 1 if len(ids) == 0: return None print >>open_file, "<way id='-%s'>" % id_counter way_id = id_counter id_counter += 1 for i in ids: print >>open_file, "<nd ref='-%s' />" % i print >>open_file, "<nd ref='-%s' />" % ids[0] print >>open_file, "</way>" return way_id open_file = None file_name = None id_counter = 1 file_counter = 0 counter = 0 -def run(filename, slice_count=1, obj_count=50000, output_location=None): +class AppError(Exception): pass + +def run(filename, slice_count=1, obj_count=50000, output_location=None, no_source=False): """Run the converter. Requires open_file, file_name, id_counter, file_counter, counter to be defined in global space; not really a very good singleton.""" - global id_counter, file_counter, counter, file_name, open_file + global id_counter, file_counter, counter, file_name, open_file, namespace + if no_source: + namespace=None + if output_location: file_name = output_location ds = ogr.Open(filename) + if not ds: + raise AppError("OGR Could not open the file %s" % filename) l = ds.GetLayer(0) max_objs_per_file = obj_count extent = l.GetExtent() + if extent[0] < -180 or extent[0] > 180 or extent[2] < -90 or extent[2] > 90: + raise AppError("Extent does not look like degrees; are you sure it is? \n(%s, %s, %s, %s)" % (extent[0], extent[2], extent[1], extent[3])) slice_width = (extent[1] - extent[0]) / slice_count seen = {} + + print "Running %s slices with %s base filename against shapefile %s" % ( + slice_count, file_name, filename) + for i in range(slice_count): l.ResetReading() l.SetSpatialFilterRect(extent[0] + slice_width * i, extent[2], extent[0] + (slice_width * (i + 1)), extent[3]) start_new_file() f = l.GetNextFeature() obj_counter = 0 last_obj_split = 0 while f: start_id_counter = id_counter if f.GetFID() in seen: f = l.GetNextFeature() continue seen[f.GetFID()] = True if (obj_counter - last_obj_split) > max_objs_per_file: print "Splitting file with %s objs" % (obj_counter - last_obj_split) start_new_file() last_obj_split = obj_counter ways = [] geom = f.GetGeometryRef() ring = geom.GetGeometryRef(0) ids = add_ring_nodes(ring) if not ids or len(ids) == 0: f = l.GetNextFeature() continue print >>open_file, "<way id='-%s'>" % id_counter ways.append(id_counter) id_counter += 1 for i in ids: print >>open_file, "<nd ref='-%s' />" % i print >>open_file, "<nd ref='-%s' />" % ids[0] field_count = f.GetFieldCount() fields = {} for field in range(field_count): value = f.GetFieldAsString(field) name = f.GetFieldDefnRef(field).GetName() - if name and value and name not in boring_tags: - print >>open_file, "<tag k='massgis:%s' v='%s' />" % (name, clean_attr(value)) + if namespace and name and value and name not in boring_tags: + print >>open_file, "<tag k='%s:%s' v='%s' />" % (namespace, name, clean_attr(value)) fields[name.lower()] = value tags={} for tag_name, map_value in tag_mapping: if hasattr(map_value, '__call__'): tag_values = map_value(fields) if tag_values: for tag in tag_values: tags[tag[0]] = tag[1] else: if tag_name in fields: tags[map_value] = fields[tag_name].title() for key, value in tags.items(): if key and value: print >>open_file, "<tag k='%s' v='%s' />" % (key, clean_attr(value)) for name, value in fixed_tags.items(): print >>open_file, "<tag k='%s' v='%s' />" % (name, clean_attr(value)) print >>open_file, "</way>" if geom.GetGeometryCount() > 1: for i in range(1, geom.GetGeometryCount()): ways.append(add_ring_way(geom.GetGeometryRef(i))) print >>open_file, "<relation id='-%s'><tag k='type' v='multipolygon' />" % id_counter id_counter += 1 print >>open_file, '<member type="way" ref="-%s" role="outer" />' % ways[0] for way in ways[1:]: print >>open_file, '<member type="way" ref="-%s" role="inner" />' % way print >>open_file, "</relation>" counter += 1 f = l.GetNextFeature() obj_counter += (id_counter - start_id_counter) close_file() if __name__ == "__main__": if DONT_RUN: print __doc__ sys.exit(2) from optparse import OptionParser - parse = OptionParser(usage="%s [args] filename.shp") + parse = OptionParser(usage="%prog [args] filename.shp", version=__version__) parse.add_option("-s", "--slice-count", dest="slice_count", help="Number of horizontal slices of data", default=1, action="store", type="int") parse.add_option("-o", "--obj-count", dest="obj_count", help="Target Maximum number of objects in a single .osm file", default=50000, type="int") + parse.add_option("-n", "--no-source", dest="no_source", + help="Do not store source attributes as tags.", + action="store_true", default=False) parse.add_option("-l", "--output-location", dest="output_location", help="base filepath for output files.", default="poly_output") (options, args) = parse.parse_args() + if not len(args): + print "No shapefile name given!" + parse.print_help() + sys.exit(3) + kw = {} - for key in ('slice_count', 'obj_count', 'output_location'): + for key in ('slice_count', 'obj_count', 'output_location', 'no_source'): kw[key] = getattr(options, key) - run(args[0], **kw) + try: + run(args[0], **kw) + except AppError, E: + print "An error occurred: \n%s" % E
openstreetmap/shp2osm
1be049626b76c5c60c93216166aa49442777a127
Add polygon-shape-to-osm tool to SVN. Developed as part of http://wiki.openstreetmap.org/wiki/MassGis_Layer_Openspace .
diff --git a/polyshp2osm.py b/polyshp2osm.py new file mode 100644 index 0000000..3368617 --- /dev/null +++ b/polyshp2osm.py @@ -0,0 +1,366 @@ +#!/usr/bin/python + +""" +This script is designed to act as assistance in converting shapefiles +to OpenStreetMap data. This file is optimized and tested with MassGIS +shapefiles, converted to EPSG:4326 before being passed to the script. +You can perform this conversion with + + ogr2ogr -t_srs EPSG:4326 new_file.shp old_file.shp + +Requires OGR: Tested with 1.3.2 and 1.6.0 + +It is expected that you will modify the fixed_tags, tag_mapping, and +boring_tags attributes of this script before running. You should read, +or at least skim, the code up until it says: + + DO NOT CHANGE AFTER THIS LINE. + +to accomodate your own data. +""" + +__author__ = "Christopher Schmidt <[email protected]>" +__version__ = "$Id$" + +# These tags are attached to all exterior ways. You can put any key/value pairs +# in this dictionary. + +fixed_tags = { + 'source': 'MassGIS OpenSpace (http://www.mass.gov/mgis/osp.htm)', + 'area': 'yes', + 'created_by': 'polyshp2osm' +} + +# Here are a number of functions: These functions define tag mappings. The API +# For these functions is that they are passed the attributes from a feature, +# and they return a list of two-tuples which match to key/value pairs. + +def access(data): + """Access restrictions.""" + keys = { + 'Y': 'yes', + 'N': 'private', + 'L': 'restricted' + } + if 'pub_access' in data: + if data['pub_access'] in keys: + return [('access', keys[data['pub_access']])] + return None + +def protection(data): + keys = { + 'P': 'perpetuity', + 'T': 'temporary', + 'L': 'limited', + } + if 'lev_prot' in data: + if data['lev_prot'] in keys: + return [('protected', keys[data['lev_prot']])] + return None + +def owner_type(data): + """See wiki:Key:ownership""" + keys = { + 'F': 'national', + 'S': 'state', + 'C': 'county', + 'M': 'municipal', + 'N': 'private_nonprofit', + 'P': 'private', + 'B': 'public_nonprofit', + 'L': 'land_trust', + 'G': 'conservation_rganization', + 'I': 'inholding', + } + if 'owner_type' in data: + if data['owner_type'] in keys: + return [['ownership', keys[data['owner_type']]]] + +def purpose(data): + """Based on a discussion on IRC""" + keys = { + 'R': [('leisure', 'recreation_ground')], + 'C': [('leisure', 'nature_reserve'), ('landuse', 'conservation')], + 'B': [('landuse','conservation'), ('leisure','recreation_ground')], + 'H': [('historical', 'yes')], + 'A': [('agricultural', 'yes'), ('landuse','farm')], + 'W': [('landuse', 'resevoir')], + 'S': [('scenic','yes')], + 'F': [('landuse','land')], + 'Q': [('landuse','conservation')], + 'U': [('water','yes')] + } + if 'prim_purp' in data: + if data['prim_purp'] in keys: + return keys[data['prim_purp']] + +def name_tags(data): + """This function returns two things: a 'pretty' name to use, and + may return a landuse of either 'cemetery' or 'forest' if the name + contains those words; based on evaluation the dataset in question.""" + tags = [] + name = data.get('site_name', None) + if not name: + return + name = name.title() + + if "cemetery" in name.lower(): + tags.append(['landuse', 'cemetery']) + elif "forest" in name.lower(): + tags.append(['landuse', 'forest']) + + tags.append(['name', name]) + return tags + +def cal_date(data): + """Return YYYY-MM-DD or YYYY formatted dates, based on + (m)m/(d)d/yyyy dates""" + date = data.get('cal_date_r', None) + if not date: return + try: + m, d, y = map(int, date.split("/")) + if m == 1 and d == 1: + return [['start_date', '%4i' % y]] + return [['start_date', '%04i-%02i-%02i' % (y, m, d)]] + except: + print "Invalid date: %s" % date + return None + +# The most important part of the code: define a set of key/value pairs +# to iterate over to generate keys. This is a list of two-tuples: first +# is a 'key', which is only used if the second value is a string. In +# that case, it is a map of lowercased fielnames to OSM tag names: so +# fee_owner maps to 'owner' in the OSM output. + +# if the latter is callable (has a __call__; is a function), then that +# method is called, passing in a dict of feature attributes with +# lowercased key names. Those functions can then return a list of +# two-tuples to be used as tags, or nothin' to skip the tags. + + +tag_mapping = [ + ('fee_owner', 'owner'), + ('cal_date', cal_date), + ('pub_access', access), + ('lev_prot', protection), + ('owner_type', owner_type), + ('prim_purp', purpose), + ('site_name', name_tags), +] + +# These tags are not exported, even with the source data; this should be +# used for tags which are usually calculated in a GIS. AREA and LEN are +# common. + +boring_tags = [ 'AREA', 'LEN', 'GIS_ACRES' ] + +# Uncomment the "DONT_RUN = False" line to get started. + +DONT_RUN = True +#DONT_RUN = False + +# =========== DO NOT CHANGE AFTER THIS LINE. =========================== +# Below here is regular code, part of the file. This is not designed to +# be modified by users. +# ====================================================================== + +import sys + +try: + try: + from osgeo import ogr + except ImportError: + import ogr +except ImportError: + if DONT_RUN: + print __doc__ + sys.exit(2) + print "OGR Python Bindings not installed. Fix that, please." + sys.exit(1) + +def close_file(): + """ Internal. Close an open file.""" + global open_file + if not open_file.closed: + open_file.write("</osm>") + open_file.close() + +def start_new_file(): + """ Internal. Open a new file, closing existing file if neccesary.""" + global open_file, file_counter + file_counter += 1 + if open_file: + close_file() + open_file = open("%s.%s.osm" % (file_name, file_counter), "w") + print >>open_file, "<osm version='0.5'>" + +def clean_attr(val): + """Internal. Hacky way to make attribute XML safe.""" + val = str(val) + val = val.replace("&", "&amp;").replace("'", "&quot;").replace("<", "&lt;").replace(">", "&gt;").strip() + return val + +def add_ring_nodes(ring): + """Internal. Write the first ring nodes.""" + global open_file, id_counter + ids = [] + if range(ring.GetPointCount() - 1) == 0 or ring.GetPointCount() == 0: + print >>sys.stderr, "Degenerate ring." + return + for count in range(ring.GetPointCount()-1): + ids.append(id_counter) + print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count + id_counter += 1 + return ids + +def add_ring_way(ring): + """Internal. write out the 'holes' in a polygon.""" + global open_file, id_counter + ids = [] + for count in range(ring.GetPointCount()-1): + ids.append(id_counter) + print >>open_file, "<node id='-%s' lon='%s' lat='%s' />" % (id_counter, ring.GetX(count), ring.GetY(count)) #print count + id_counter += 1 + if len(ids) == 0: + return None + print >>open_file, "<way id='-%s'>" % id_counter + way_id = id_counter + id_counter += 1 + for i in ids: + print >>open_file, "<nd ref='-%s' />" % i + print >>open_file, "<nd ref='-%s' />" % ids[0] + print >>open_file, "</way>" + + return way_id + +open_file = None + +file_name = None + +id_counter = 1 + +file_counter = 0 +counter = 0 + +def run(filename, slice_count=1, obj_count=50000, output_location=None): + """Run the converter. Requires open_file, file_name, id_counter, + file_counter, counter to be defined in global space; not really a very good + singleton.""" + global id_counter, file_counter, counter, file_name, open_file + + if output_location: + file_name = output_location + + ds = ogr.Open(filename) + l = ds.GetLayer(0) + + max_objs_per_file = obj_count + + extent = l.GetExtent() + slice_width = (extent[1] - extent[0]) / slice_count + + seen = {} + for i in range(slice_count): + + l.ResetReading() + l.SetSpatialFilterRect(extent[0] + slice_width * i, extent[2], extent[0] + (slice_width * (i + 1)), extent[3]) + + start_new_file() + f = l.GetNextFeature() + + obj_counter = 0 + last_obj_split = 0 + + while f: + start_id_counter = id_counter + if f.GetFID() in seen: + f = l.GetNextFeature() + continue + seen[f.GetFID()] = True + + if (obj_counter - last_obj_split) > max_objs_per_file: + print "Splitting file with %s objs" % (obj_counter - last_obj_split) + start_new_file() + last_obj_split = obj_counter + + ways = [] + + geom = f.GetGeometryRef() + ring = geom.GetGeometryRef(0) + ids = add_ring_nodes(ring) + if not ids or len(ids) == 0: + f = l.GetNextFeature() + continue + print >>open_file, "<way id='-%s'>" % id_counter + ways.append(id_counter) + id_counter += 1 + for i in ids: + print >>open_file, "<nd ref='-%s' />" % i + print >>open_file, "<nd ref='-%s' />" % ids[0] + field_count = f.GetFieldCount() + fields = {} + for field in range(field_count): + value = f.GetFieldAsString(field) + name = f.GetFieldDefnRef(field).GetName() + if name and value and name not in boring_tags: + print >>open_file, "<tag k='massgis:%s' v='%s' />" % (name, clean_attr(value)) + fields[name.lower()] = value + tags={} + for tag_name, map_value in tag_mapping: + if hasattr(map_value, '__call__'): + tag_values = map_value(fields) + if tag_values: + for tag in tag_values: + tags[tag[0]] = tag[1] + + else: + if tag_name in fields: + tags[map_value] = fields[tag_name].title() + for key, value in tags.items(): + if key and value: + print >>open_file, "<tag k='%s' v='%s' />" % (key, clean_attr(value)) + + for name, value in fixed_tags.items(): + print >>open_file, "<tag k='%s' v='%s' />" % (name, clean_attr(value)) + print >>open_file, "</way>" + if geom.GetGeometryCount() > 1: + for i in range(1, geom.GetGeometryCount()): + ways.append(add_ring_way(geom.GetGeometryRef(i))) + print >>open_file, "<relation id='-%s'><tag k='type' v='multipolygon' />" % id_counter + id_counter += 1 + print >>open_file, '<member type="way" ref="-%s" role="outer" />' % ways[0] + for way in ways[1:]: + print >>open_file, '<member type="way" ref="-%s" role="inner" />' % way + print >>open_file, "</relation>" + + counter += 1 + f = l.GetNextFeature() + obj_counter += (id_counter - start_id_counter) + + close_file() + +if __name__ == "__main__": + if DONT_RUN: + print __doc__ + sys.exit(2) + + from optparse import OptionParser + + parse = OptionParser(usage="%s [args] filename.shp") + parse.add_option("-s", "--slice-count", dest="slice_count", + help="Number of horizontal slices of data", default=1, + action="store", type="int") + parse.add_option("-o", "--obj-count", + dest="obj_count", + help="Target Maximum number of objects in a single .osm file", + default=50000, type="int") + parse.add_option("-l", "--output-location", + dest="output_location", help="base filepath for output files.", + default="poly_output") + (options, args) = parse.parse_args() + + kw = {} + for key in ('slice_count', 'obj_count', 'output_location'): + kw[key] = getattr(options, key) + + run(args[0], **kw)
openstreetmap/shp2osm
b97ef763e0e102116e180bfac6bfb36dc454a6ea
Shapefile to OSM converter
diff --git a/shp2osm.pl b/shp2osm.pl new file mode 100644 index 0000000..86f888f --- /dev/null +++ b/shp2osm.pl @@ -0,0 +1,167 @@ +# Copyright (c) 2006 Gabriel Ebner <[email protected]> +# updated in 2008 by Tobias Wendorff <[email protected]> +# HTML-Entities based on ideas of Hermann Schwärzler +# Gauß-Krüger implementation based on gauss.pl by Andreas Achtzehn +# version 1.3 (17. September 2008) + +use Geo::ShapeFile; +use HTML::Entities qw(encode_entities_numeric); +use Math::Trig; + +if(@ARGV == 0) { + print "usage:\n"; + print "with transformation from GK to WGS84: 'shp2osm.pl shapefile GK'\n"; + print "without transformation: 'shp2osm.pl shapefile'"; + exit; +} + +print <<'END'; +<?xml version='1.0'?> +<osm version='0.5' generator='shp2osm.pl'> +END + +#BEGIN { our %default_tags = ( natural => 'water', source => 'SWDB' ); } +BEGIN { our %default_tags = ( ); } + +my $file = @ARGV[0]; +$file =~ s/\.shp$//; +my $shpf = Geo::ShapeFile->new($file); +proc_shpf($shpf); + +{ + BEGIN { our $i = -1; } + + sub tags_out { + my ($tags) = @_; + my %tags = $tags ? %$tags : (); + #$tags{'created_by'} ||= 'shp2osm.pl'; + delete $tags{'_deleted'} unless $tags{'_deleted'}; + while ( my ( $k, $v ) = each %tags ) { + my $key = encode_entities_numeric($k); + my $val = encode_entities_numeric($v); + print ' <tag k="'. $key .'" v="'. $val ."\"/>\n" if $val; + } + } + + sub node_out { + my ( $lon, $lat, $tags ) = @_; + my $id = $i--; + if(@ARGV[1] eq 'GK') { + my ($wgs84lon, $wgs84lat) = gk2geo($lon, $lat); + print " <node id='$id' visible='true' lat='$wgs84lat' lon='$wgs84lon' />\n"; + } else { + print " <node id='$id' visible='true' lat='$lat' lon='$lon' />\n"; + } + $id; + } + + sub seg_out { + my $id = $i+1; + $id; + } + + sub way_out { + my ( $segs, $tags ) = @_; + my $id = $i--; + print " <way id='$id' visible='true'>\n"; + print " <nd ref='$_' />\n" for @$segs; + tags_out $tags; + print " </way>\n"; + $id; + } +} + + +print <<'END'; +</osm> +END + +sub polyline_out { + my ( $pts, $tags, $connect_last_seg ) = @_; + + my ( $first_node, $last_node, @segs ); + for my $pt (@$pts) { + my $node = node_out @$pt; + push @segs, seg_out $last_node, $node; + $last_node = $node; + $first_node ||= $last_node; + } + push @segs, seg_out $last_node, $first_node + if $first_node && $connect_last_seg; + way_out \@segs, $tags; +} + +sub proc_obj { + my ( $shp, $dbf, $type ) = @_; + my $tags = { %default_tags, %$dbf }; + my $is_polygon = $type % 10 == 5; + for ( 1 .. $shp->num_parts ) { + polyline_out [ map( [ $_->X(), $_->Y() ], $shp->get_part($_) ) ], $tags, + $is_polygon; + } + } + +sub proc_shpf { + my ($shpf) = @_; + my $type = $shpf->shape_type; + for ( 1 .. $shpf->shapes() ) { + my $shp = $shpf->get_shp_record($_); + my %dbf = $shpf->get_dbf_record($_); + proc_obj $shp, \%dbf, $type; + } +} + +sub gk2geo { + my $sr = $_[0]; + my $sx = $_[1]; + + my $bm = int($sr/1000000); + my $y = $sr-($bm*1000000+500000); + my $si = $sx/111120.6196; + my $px = $si+0.143885358*sin(2*$si*0.017453292)+0.00021079*sin(4*$si*0.017453292)+0.000000423*sin(6*$si*0.017453292); + my $t = (sin($px*0.017453292))/(cos($px*0.017453292)); + my $v = sqrt(1+0.006719219*cos($px*0.017453292)*cos($px*0.017453292)); + my $ys = ($y*$v)/6398786.85; + my $lat = $px-$ys*$ys*57.29577*$t*$v*$v*(0.5-$ys*$ys*(4.97-3*$t*$t)/24); + my $dl = $ys*57.29577/cos($px*0.017453292) * (1-$ys*$ys/6*($v*$v+2*$t*$t-$ys*$ys*(0.6+1.1*$t*$t)*(0.6+1.1*$t*$t))); + my $lon = $bm*3+$dl; + + my $potsd_a = 6377397.155; + my $wgs84_a = 6378137.0; + my $potsd_f = 1/299.152812838; + my $wgs84_f = 1/298.257223563; + + my $potsd_es = 2*$potsd_f - $potsd_f*$potsd_f; + + my $potsd_dx = 606.0; + my $potsd_dy = 23.0; + my $potsd_dz = 413.0; + my $pi = 3.141592654; + my $latr = $lat/180*$pi; + my $lonr = $lon/180*$pi; + + my $sa = sin($latr); + my $ca = cos($latr); + my $so = sin($lonr); + my $co = cos($lonr); + + my $bda = 1-$potsd_f; + + my $delta_a = $wgs84_a - $potsd_a; + my $delta_f = $wgs84_f - $potsd_f; + + my $rn = $potsd_a / sqrt(1-$potsd_es*sin($latr)*sin($latr)); + my $rm = $potsd_a * ((1-$potsd_es)/sqrt(1-$potsd_es*sin($latr)*sin($latr)*1-$potsd_es*sin($latr)*sin($latr)*1-$potsd_es*sin($latr)*sin($latr))); + + my $ta = (-$potsd_dx*$sa*$co - $potsd_dy*$sa*$so)+$potsd_dz*$ca; + my $tb = $delta_a*(($rn*$potsd_es*$sa*$ca)/$potsd_a); + my $tc = $delta_f*($rm/$bda+$rn*$bda)*$sa*$ca; + my $dlat = ($ta+$tb+$tc)/$rm; + + my $dlon = (-$potsd_dx*$so + $potsd_dy*$co)/($rn*$ca); + + my $wgs84lat = ($latr + $dlat)*180/$pi; + my $wgs84lon = ($lonr + $dlon)*180/$pi; + + return( $wgs84lon, $wgs84lat); +} \ No newline at end of file
agilejoe/cruiseviewer
15367e3ea57fddc2cb38114d8cb14e79e5326f67
add loading text. change text color outside success or fail divs.
diff --git a/index.html b/index.html index 46a5dfd..f37504b 100644 --- a/index.html +++ b/index.html @@ -1,14 +1,14 @@ <html> <head> <meta http-equiv="refresh" content="60" > <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/cruiseviewer.js"></script> <link rel="stylesheet" type="text/css" href="stylesheets/cruiseviewer.css" /> </head> <body> - <div id="parentDiv"></div> + <div id="parentDiv">LOADING...</div> <div> <h3><a href="http://github.com/armmer/cruiseviewer" target="_blank">Cruise Viewer 0.1</a></h3> </div> </body> </html> diff --git a/js/cruiseviewer.js b/js/cruiseviewer.js index 4f73306..c0c1421 100644 --- a/js/cruiseviewer.js +++ b/js/cruiseviewer.js @@ -1,16 +1,16 @@ $(document).ready(function() { $.ajax({ type: "GET", url: "http://cruisecontrolrb.thoughtworks.com/XmlStatusReport.aspx", dataType: "html", success: function(xml) { - $("#parentdiv").empty() + $("#parentDiv").empty(); $(xml).find("Project").each(function() { var name = $(this).attr("name"); var buildStatus = $(this).attr("lastBuildStatus"); - $("<div class='"+buildStatus+"'>"+name+"</div>").hide().appendTo("#parentDiv").fadeIn(); + $("<div class='"+buildStatus+"'>"+name+"</div>").appendTo("#parentDiv"); }); } }); }); diff --git a/stylesheets/cruiseviewer.css b/stylesheets/cruiseviewer.css index 8ae33ca..a7d1050 100644 --- a/stylesheets/cruiseviewer.css +++ b/stylesheets/cruiseviewer.css @@ -1,47 +1,48 @@ html, body { margin: 0; padding: 0; } body { - font: 100% arial, verdana, sans-serif; - color: #000000; + font: 1em arial, verdana, sans-serif; + color: #ffffff; background: #000000; } h3 a { color: #ffffff; font-weight: normal; margin: 0; padding: 0; } #parentDiv{ font-size: 4em; font-weight: bold; display: block; } #parentDiv .Success { - + color: #000000; margin: 10px 0px 0px 10px; padding: 1em; background-color: #007200; display: inline-block; text-align: center; } #parentDiv .Failure { + color: #000000; margin: 10px 0px 0px 10px; padding: 1em; background-color: #ff0000; display: inline-block; text-align: center; }
agilejoe/cruiseviewer
7809667ab2ea578d4cc4995b7094363150302dab
add note that this only works in Safari browser, currently
diff --git a/README.textile b/README.textile index 8b00ea2..cd1c1cf 100644 --- a/README.textile +++ b/README.textile @@ -1,11 +1,13 @@ h1. CruiseViewer jQuery version of BigVisible Cruise +currently, only works in Safari browser. + <hr/> Authors: Jason Meridth "(armmer)":http://github.com/armmer Joe Ocampo "(joeocampo)":http://github.com/joeocampo
agilejoe/cruiseviewer
d1b7e1f8f3c91156f30477e9c96c2bc488978cd4
remove jfeed plugin, change success color to 007200
diff --git a/index.html b/index.html index cbdeae5..46a5dfd 100644 --- a/index.html +++ b/index.html @@ -1,15 +1,14 @@ <html> <head> <meta http-equiv="refresh" content="60" > <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> - <script type="text/javascript" src="js/plugins/jquery.jfeed.pack.js"></script> <script type="text/javascript" src="js/cruiseviewer.js"></script> <link rel="stylesheet" type="text/css" href="stylesheets/cruiseviewer.css" /> </head> <body> <div id="parentDiv"></div> <div> <h3><a href="http://github.com/armmer/cruiseviewer" target="_blank">Cruise Viewer 0.1</a></h3> </div> </body> </html> diff --git a/js/plugins/jquery.jfeed.pack.js b/js/plugins/jquery.jfeed.pack.js deleted file mode 100644 index 7a696c0..0000000 --- a/js/plugins/jquery.jfeed.pack.js +++ /dev/null @@ -1 +0,0 @@ -eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3.X=a(h){h=3.J({v:D,C:D,u:D},h);k(h.v){$.W({t:\'V\',v:h.v,C:h.C,U:\'4\',u:a(4){d f=j B(4);k(3.T(h.u))h.u(f)}})}};a B(4){k(4)2.K(4)};B.r={t:\'\',l:\'\',c:\'\',b:\'\',g:\'\',K:a(4){k(3(\'8\',4).y==1){2.t=\'x\';d s=j z(4)}H k(3(\'f\',4).y==1){2.t=\'S\';d s=j A(4)}k(s)3.J(2,s)}};a o(){};o.r={c:\'\',b:\'\',g:\'\',i:\'\',n:\'\'};a A(4){2.q(4)};A.r={q:a(4){d 8=3(\'f\',4).9(0);2.l=\'1.0\';2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').p(\'I\');2.g=3(8).5(\'R:e\').6();2.w=3(8).p(\'4:Q\');2.i=3(8).5(\'i:e\').6();2.m=j G();d f=2;3(\'P\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).p(\'I\');7.g=3(2).5(\'O\').9(0).6();7.i=3(2).5(\'i\').9(0).6();7.n=3(2).5(\'n\').9(0).6();f.m.E(7)})}};a z(4){2.q(4)};z.r={q:a(4){k(3(\'x\',4).y==0)2.l=\'1.0\';H 2.l=3(\'x\',4).9(0).p(\'l\');d 8=3(\'8\',4).9(0);2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').6();2.g=3(8).5(\'g:e\').6();2.w=3(8).5(\'w:e\').6();2.i=3(8).5(\'N:e\').6();2.m=j G();d f=2;3(\'7\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).6();7.g=3(2).5(\'g\').9(0).6();7.i=3(2).5(\'M\').9(0).6();7.n=3(2).5(\'L\').9(0).6();f.m.E(7)})}};',60,60,'||this|jQuery|xml|find|text|item|channel|eq|function|link|title|var|first|feed|description|options|updated|new|if|version|items|id|JFeedItem|attr|_parse|prototype|feedClass|type|success|url|language|rss|length|JRss|JAtom|JFeed|data|null|push|each|Array|else|href|extend|parse|guid|pubDate|lastBuildDate|content|entry|lang|subtitle|atom|isFunction|dataType|GET|ajax|getFeed'.split('|'))) diff --git a/stylesheets/cruiseviewer.css b/stylesheets/cruiseviewer.css index 141deab..8ae33ca 100644 --- a/stylesheets/cruiseviewer.css +++ b/stylesheets/cruiseviewer.css @@ -1,47 +1,47 @@ html, body { margin: 0; padding: 0; } body { font: 100% arial, verdana, sans-serif; color: #000000; background: #000000; } h3 a { color: #ffffff; font-weight: normal; margin: 0; padding: 0; } #parentDiv{ font-size: 4em; font-weight: bold; display: block; } #parentDiv .Success { margin: 10px 0px 0px 10px; padding: 1em; - background-color: #00ff00; + background-color: #007200; display: inline-block; text-align: center; } #parentDiv .Failure { margin: 10px 0px 0px 10px; padding: 1em; background-color: #ff0000; display: inline-block; text-align: center; }
agilejoe/cruiseviewer
2a7baf260ae4eb85abaf486a8d7347118d25c8d2
fix readme, separate project blocks
diff --git a/README.textile b/README.textile index 5aa8536..8b00ea2 100644 --- a/README.textile +++ b/README.textile @@ -1,12 +1,11 @@ h1. CruiseViewer jQuery version of BigVisible Cruise - -== <hr/> == +<hr/> Authors: -Jason Meridth "armmer":http://github.com/armmer +Jason Meridth "(armmer)":http://github.com/armmer -Joe Ocampo "joeocampo":http://github.com/joeocampo +Joe Ocampo "(joeocampo)":http://github.com/joeocampo diff --git a/stylesheets/cruiseviewer.css b/stylesheets/cruiseviewer.css index 9ec776e..141deab 100644 --- a/stylesheets/cruiseviewer.css +++ b/stylesheets/cruiseviewer.css @@ -1,46 +1,47 @@ html, body { margin: 0; padding: 0; } + body { font: 100% arial, verdana, sans-serif; color: #000000; background: #000000; } h3 a { - font-color: #ffffff; + color: #ffffff; font-weight: normal; margin: 0; padding: 0; } #parentDiv{ font-size: 4em; font-weight: bold; display: block; } #parentDiv .Success { - margin: 10px 0px; + margin: 10px 0px 0px 10px; padding: 1em; background-color: #00ff00; display: inline-block; text-align: center; } #parentDiv .Failure { - margin: 10px 0px; + margin: 10px 0px 0px 10px; padding: 1em; background-color: #ff0000; display: inline-block; text-align: center; }
agilejoe/cruiseviewer
5bc4ab3af5db1a133e4c125bbd3b9bd185a8f0f3
add to the README
diff --git a/README.rdoc b/README.rdoc index e44c8aa..189411f 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,3 +1,12 @@ = CruiseViewer jQuery version of BigVisible Cruise + + +==<hr/>== + +Authors: + +Jason Meridth "armmer":http://github.com/armmer + +Joe Ocampo "joeocampo":http://github.com/joeocampo
agilejoe/cruiseviewer
643b4c93cd51c320a6de77eb9f0425b145281f40
parse XmlStatusReport.aspx and display successful and failed builds
diff --git a/index.html b/index.html index be3aa0a..cbdeae5 100644 --- a/index.html +++ b/index.html @@ -1,23 +1,15 @@ <html> - <head> + <head> + <meta http-equiv="refresh" content="60" > <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/plugins/jquery.jfeed.pack.js"></script> - <script type="text/javascript"> - $(document).ready(function() { - $.getFeed({ - url: 'https:/yoururl.com/projects/project_name.rss', - success: function(feed) { - $.each(feed.items, function(n, val){ - if(n == 1) break; - result = val.title.indexOf("success") > 0 ? "SUCCESS":"FAILURE"; - alert(result); - }); - } - }); - }); - </script> - </head> + <script type="text/javascript" src="js/cruiseviewer.js"></script> + <link rel="stylesheet" type="text/css" href="stylesheets/cruiseviewer.css" /> +</head> <body> - <!-- we will add our HTML content here --> + <div id="parentDiv"></div> + <div> + <h3><a href="http://github.com/armmer/cruiseviewer" target="_blank">Cruise Viewer 0.1</a></h3> + </div> </body> </html> diff --git a/js/cruiseviewer.js b/js/cruiseviewer.js new file mode 100644 index 0000000..4f73306 --- /dev/null +++ b/js/cruiseviewer.js @@ -0,0 +1,16 @@ +$(document).ready(function() { + $.ajax({ + type: "GET", + url: "http://cruisecontrolrb.thoughtworks.com/XmlStatusReport.aspx", + dataType: "html", + success: function(xml) { + $("#parentdiv").empty() + $(xml).find("Project").each(function() + { + var name = $(this).attr("name"); + var buildStatus = $(this).attr("lastBuildStatus"); + $("<div class='"+buildStatus+"'>"+name+"</div>").hide().appendTo("#parentDiv").fadeIn(); + }); + } + }); +}); diff --git a/margins.html b/margins.html new file mode 100644 index 0000000..cc179cb --- /dev/null +++ b/margins.html @@ -0,0 +1,17 @@ +<html> + <head> + <link rel="stylesheet" type="text/css" href="stylesheets/cruiseviewer.css" /> +</head> +<body> + <div id="parentDiv"> + <div class='Success'>QBack</div> + <div class='Success'>iBack</div> + <div class='Success'>Mortgage Administrator</div> + <div class='Failure'>Property Manager</div> + <div class='Success'>QBack</div> + <div class='Success'>iBack</div> + <div class='Success'>Mortgage Administrator</div> + <div class='Failure'>Property Manager</div> + </div> +</body> +</html> \ No newline at end of file diff --git a/stylesheets/cruiseviewer.css b/stylesheets/cruiseviewer.css new file mode 100644 index 0000000..9ec776e --- /dev/null +++ b/stylesheets/cruiseviewer.css @@ -0,0 +1,46 @@ +html, body +{ + margin: 0; + padding: 0; +} +body +{ + font: 100% arial, verdana, sans-serif; + color: #000000; + background: #000000; +} + +h3 a +{ + font-color: #ffffff; + font-weight: normal; + margin: 0; + padding: 0; +} + +#parentDiv{ + font-size: 4em; + font-weight: bold; + display: block; +} + +#parentDiv .Success +{ + + margin: 10px 0px; + padding: 1em; + background-color: #00ff00; + display: inline-block; + text-align: center; +} + +#parentDiv .Failure +{ + margin: 10px 0px; + padding: 1em; + background-color: #ff0000; + display: inline-block; + text-align: center; +} + +
agilejoe/cruiseviewer
1796b926f5d122074c4488bd5952c764324916e1
stable commit reading the status of a remote rss feed
diff --git a/index.html b/index.html new file mode 100644 index 0000000..be3aa0a --- /dev/null +++ b/index.html @@ -0,0 +1,23 @@ +<html> + <head> + <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> + <script type="text/javascript" src="js/plugins/jquery.jfeed.pack.js"></script> + <script type="text/javascript"> + $(document).ready(function() { + $.getFeed({ + url: 'https:/yoururl.com/projects/project_name.rss', + success: function(feed) { + $.each(feed.items, function(n, val){ + if(n == 1) break; + result = val.title.indexOf("success") > 0 ? "SUCCESS":"FAILURE"; + alert(result); + }); + } + }); + }); + </script> + </head> +<body> + <!-- we will add our HTML content here --> +</body> +</html> diff --git a/js/jquery-1.3.2.min.js b/js/jquery-1.3.2.min.js new file mode 100644 index 0000000..b1ae21d --- /dev/null +++ b/js/jquery-1.3.2.min.js @@ -0,0 +1,19 @@ +/* + * jQuery JavaScript Library v1.3.2 + * http://jquery.com/ + * + * Copyright (c) 2009 John Resig + * Dual licensed under the MIT and GPL licenses. + * http://docs.jquery.com/License + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ +(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); +/* + * Sizzle CSS Selector Engine - v0.9.3 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/js/plugins/jquery.jfeed.pack.js b/js/plugins/jquery.jfeed.pack.js new file mode 100644 index 0000000..7a696c0 --- /dev/null +++ b/js/plugins/jquery.jfeed.pack.js @@ -0,0 +1 @@ +eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3.X=a(h){h=3.J({v:D,C:D,u:D},h);k(h.v){$.W({t:\'V\',v:h.v,C:h.C,U:\'4\',u:a(4){d f=j B(4);k(3.T(h.u))h.u(f)}})}};a B(4){k(4)2.K(4)};B.r={t:\'\',l:\'\',c:\'\',b:\'\',g:\'\',K:a(4){k(3(\'8\',4).y==1){2.t=\'x\';d s=j z(4)}H k(3(\'f\',4).y==1){2.t=\'S\';d s=j A(4)}k(s)3.J(2,s)}};a o(){};o.r={c:\'\',b:\'\',g:\'\',i:\'\',n:\'\'};a A(4){2.q(4)};A.r={q:a(4){d 8=3(\'f\',4).9(0);2.l=\'1.0\';2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').p(\'I\');2.g=3(8).5(\'R:e\').6();2.w=3(8).p(\'4:Q\');2.i=3(8).5(\'i:e\').6();2.m=j G();d f=2;3(\'P\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).p(\'I\');7.g=3(2).5(\'O\').9(0).6();7.i=3(2).5(\'i\').9(0).6();7.n=3(2).5(\'n\').9(0).6();f.m.E(7)})}};a z(4){2.q(4)};z.r={q:a(4){k(3(\'x\',4).y==0)2.l=\'1.0\';H 2.l=3(\'x\',4).9(0).p(\'l\');d 8=3(\'8\',4).9(0);2.c=3(8).5(\'c:e\').6();2.b=3(8).5(\'b:e\').6();2.g=3(8).5(\'g:e\').6();2.w=3(8).5(\'w:e\').6();2.i=3(8).5(\'N:e\').6();2.m=j G();d f=2;3(\'7\',4).F(a(){d 7=j o();7.c=3(2).5(\'c\').9(0).6();7.b=3(2).5(\'b\').9(0).6();7.g=3(2).5(\'g\').9(0).6();7.i=3(2).5(\'M\').9(0).6();7.n=3(2).5(\'L\').9(0).6();f.m.E(7)})}};',60,60,'||this|jQuery|xml|find|text|item|channel|eq|function|link|title|var|first|feed|description|options|updated|new|if|version|items|id|JFeedItem|attr|_parse|prototype|feedClass|type|success|url|language|rss|length|JRss|JAtom|JFeed|data|null|push|each|Array|else|href|extend|parse|guid|pubDate|lastBuildDate|content|entry|lang|subtitle|atom|isFunction|dataType|GET|ajax|getFeed'.split('|')))
mintchaos/mint_django_utils
6c984556961c3f51aa012765ca3ce4e80168313f
Getting a setup.py so I can play nice with pip. Whee!
diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..692057b --- /dev/null +++ b/setup.py @@ -0,0 +1,24 @@ +from distutils.core import setup + +setup( + name = "mint_django_utils", + version = "0.0.10", + url = 'http://github.com/mintchaos/mint_django_utils', + license = 'BSD', + description = "A collection of utility functions, template tags and miscellany that I use for my djangos. Might only be useful to me.", + author = 'Christian Metts', + author_email = '[email protected]', + packages = [ + 'mint_django_utils', + 'mint_django_utils.templatetags', + ], + classifiers = [ + 'Development Status :: 5 - Production/Stable', + 'Framework :: Django', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Internet :: WWW/HTTP', + ] +) \ No newline at end of file
mintchaos/mint_django_utils
f326fe223c78b8e9c798214a7515ccab93e7610a
Skipping over key errors to make it not blow up on empty fields.
diff --git a/utils.py b/utils.py index afb5faa..2dddf9b 100644 --- a/utils.py +++ b/utils.py @@ -1,20 +1,23 @@ from django import forms from django.forms.util import ErrorList def clean_unique_for_date(self, field, date_field='pub_date'): model = self.Meta.model if date_field in self.cleaned_data: - date = self.cleaned_data[date_field] - get_args = { field: self.cleaned_data[field], - "%s__year" % date_field: date.year, - "%s__month" % date_field: date.month, - "%s__day" % date_field: date.day } + try: + date = self.cleaned_data[date_field] + get_args = { field: self.cleaned_data[field], + "%s__year" % date_field: date.year, + "%s__month" % date_field: date.month, + "%s__day" % date_field: date.day } + except KeyError: + return self.cleaned_data try: obj = model.objects.get(**get_args) if obj.id != self.instance.id: msg = u"Please enter a different %s. The one you entered is already being used for %s" % (field, date.strftime("%Y-%m-%d")) self._errors[field] = ErrorList([msg]) del self.cleaned_data[field] except model.DoesNotExist: pass return self.cleaned_data
mintchaos/mint_django_utils
a5e6e56bf08bf6ae1ba1cecf53afc2bfad5346c7
Adding some tests and a comparison filter.
diff --git a/templatetags/comparison.py b/templatetags/comparison.py index ccd1b4b..3ea14f6 100644 --- a/templatetags/comparison.py +++ b/templatetags/comparison.py @@ -1,68 +1,100 @@ +import unittest from django.template import Library from django.template.defaultfilters import lower register = Library() @register.filter def gt(value, arg): "Returns a boolean of whether the value is greater than the argument" return value > int(arg) @register.filter def lt(value, arg): "Returns a boolean of whether the value is less than the argument" return value < int(arg) @register.filter def gte(value, arg): "Returns a boolean of whether the value is greater than or equal to the argument" return value >= int(arg) @register.filter def lte(value, arg): "Returns a boolean of whether the value is less than or equal to the argument" return value <= int(arg) @register.filter def length_gt(value, arg): "Returns a boolean of whether the value's length is greater than the argument" return len(value) > int(arg) @register.filter def length_lt(value, arg): "Returns a boolean of whether the value's length is less than the argument" return len(value) < int(arg) @register.filter def length_gte(value, arg): "Returns a boolean of whether the value's length is greater than or equal to the argument" return len(value) >= int(arg) @register.filter def length_lte(value, arg): "Returns a boolean of whether the value's length is less than or equal to the argument" return len(value) <= int(arg) @register.filter def is_content_type(obj, arg): ct = lower(obj._meta.object_name) return ct == arg @register.filter def is_equal(obj, arg): "Returns a boolean of whether the value is equal to the argument" return obj == arg @register.filter def round(obj): "Returns a number rounded." return round(obj) @register.filter def has(obj, arg): try: if arg in obj: return True except TypeError: pass - return False \ No newline at end of file + return False + [email protected] +def is_empty(value): + "Returns a boolean if the value passed has non whitespace" + if not value.strip(): + return True + else: + return False + +class ComparisonTestCase(unittest.TestCase): + + def test_is_empty_empty(self): + self.assertEqual(True, is_empty("")) + + def test_is_empty_nl(self): + self.assertEqual(True, is_empty("\n")) + + def test_is_empty_nls_and_spaces(self): + self.assertEqual(True, is_empty("\n \n ")) + + def test_is_empty_a_letter(self): + self.assertEqual(False, is_empty("\n s \n ")) + + def test_is_empty_less_letters(self): + self.assertEqual(False, is_empty("\ns")) + + def test_is_empty_string(self): + self.assertEqual(False, is_empty("s")) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file
mintchaos/mint_django_utils
ec2fcffa82afe2a4c74d39679f9c3adf488d4075
Corrected the line number in the module docs.
diff --git a/templatetags/urls.py b/templatetags/urls.py index 705f18e..c007060 100644 --- a/templatetags/urls.py +++ b/templatetags/urls.py @@ -1,110 +1,110 @@ """ -This is a hack to get around a defeciency in django's URL tag. Line 19 is the +This is a hack to get around a defeciency in django's URL tag. Line 25 is the only added line. """ from django.conf import settings from django.template import Node, NodeList, Template, Context, Variable from django.template import Library from django.utils.encoding import smart_str, smart_unicode register = Library() class URLNode(Node): def __init__(self, view_name, args, kwargs, asvar): self.view_name = view_name self.args = args self.kwargs = kwargs self.asvar = asvar def render(self, context): from django.core.urlresolvers import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] kwargs = dict([(smart_str(k,'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) kwargs = dict([(k,v) for k,v in kwargs.items() if v]) ## this is the only added line. # Try to look up the URL twice: once given the view name, and again # relative to what we guess is the "main" app. If they both fail, # re-raise the NoReverseMatch unless we're using the # {% url ... as var %} construct in which cause return nothing. url = '' try: url = reverse(self.view_name, args=args, kwargs=kwargs) except NoReverseMatch, e: if settings.SETTINGS_MODULE: project_name = settings.SETTINGS_MODULE.split('.')[0] try: url = reverse(project_name + '.' + self.view_name, args=args, kwargs=kwargs) except NoReverseMatch: if self.asvar is None: # Re-raise the original exception, not the one with # the path relative to the project. This makes a # better error message. raise e else: if self.asvar is None: raise e if self.asvar: context[self.asvar] = url return '' else: return url def url(parser, token): """ Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url path.to.some_view arg1,arg2,name1=value1 %} The first argument is a path to a view. It can be an absolute python path or just ``app_name.view_name`` without the project name if the view is located inside the project. Other arguments are comma-separated values that will be filled in place of positional and keyword arguments in the URL. All arguments for the URL should be present. For example if you have a view ``app_name.client`` taking client's id and the corresponding line in a URLconf looks like this:: ('^client/(\d+)/$', 'app_name.client') and this app's URLconf is included into the project's URLconf under some path:: ('^clients/', include('project_name.app_name.urls')) then in a template you can create a link for a certain client like this:: {% url app_name.client client.id %} The URL will look like ``/clients/client/123/``. """ bits = token.contents.split(' ') if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % bits[0]) viewname = bits[1] args = [] kwargs = {} asvar = None if len(bits) > 2: bits = iter(bits[2:]) for bit in bits: if bit == 'as': asvar = bits.next() break else: for arg in bit.split(","): if '=' in arg: k, v = arg.split('=', 1) k = k.strip() kwargs[k] = parser.compile_filter(v) elif arg: args.append(parser.compile_filter(arg)) return URLNode(viewname, args, kwargs, asvar) url = register.tag(url)
mintchaos/mint_django_utils
2e640bd153358b06874395e0c04b7b9ba76d1065
A simple docstring for load_templatetags()
diff --git a/templatetags/__init__.py b/templatetags/__init__.py index d19a908..092d155 100644 --- a/templatetags/__init__.py +++ b/templatetags/__init__.py @@ -1,29 +1,33 @@ # from http://www.djangosnippets.org/snippets/342/ by miracle2k def load_templatetags(): + """ + To use this put a `TEMPLATE_TAGS = ()` tuple in your settings.py and call + this function at some point. I put it in my urls.py. + """ from django.conf import settings from django.template import add_to_builtins # This is important: If the function is called early, and some of the custom # template tags use superclasses of django template tags, or otherwise cause # the following situation to happen, it is possible that circular imports # cause problems: # If any of those superclasses import django.template.loader (for example, # django.template.loader_tags does this), it will immediately try to register # some builtins, possibly including some of the superclasses the custom template # uses. This will then fail because the importing of the modules that contain # those classes is already in progress (but not yet complete), which means that # usually the module's register object does not yet exist. # In other words: # {custom-templatetag-module} -> # {django-templatetag-module} -> # django.template.loader -> # add_to_builtins(django-templatetag-module) # <-- django-templatetag-module.register does not yet exist # It is therefor imperative that django.template.loader gets imported *before* # any of the templatetags it registers. import django.template.loader try: for lib in settings.TEMPLATE_TAGS: add_to_builtins(lib) except AttributeError: pass \ No newline at end of file
mintchaos/mint_django_utils
6416de0440e2ca6246e3da8b7fc3a44a4196fd4e
Removed some commented out pdb
diff --git a/utils.py b/utils.py index f48dea7..afb5faa 100644 --- a/utils.py +++ b/utils.py @@ -1,21 +1,20 @@ from django import forms from django.forms.util import ErrorList def clean_unique_for_date(self, field, date_field='pub_date'): model = self.Meta.model if date_field in self.cleaned_data: date = self.cleaned_data[date_field] get_args = { field: self.cleaned_data[field], "%s__year" % date_field: date.year, "%s__month" % date_field: date.month, "%s__day" % date_field: date.day } - # import pdb; pdb.set_trace() try: obj = model.objects.get(**get_args) if obj.id != self.instance.id: msg = u"Please enter a different %s. The one you entered is already being used for %s" % (field, date.strftime("%Y-%m-%d")) self._errors[field] = ErrorList([msg]) del self.cleaned_data[field] except model.DoesNotExist: pass return self.cleaned_data
mintchaos/mint_django_utils
c2800a0ef24256c228a4cd67db8b313f832e1c33
Adding miracle2k's auto templatetag loader.
diff --git a/templatetags/__init__.py b/templatetags/__init__.py index e69de29..d19a908 100644 --- a/templatetags/__init__.py +++ b/templatetags/__init__.py @@ -0,0 +1,29 @@ +# from http://www.djangosnippets.org/snippets/342/ by miracle2k +def load_templatetags(): + from django.conf import settings + from django.template import add_to_builtins + # This is important: If the function is called early, and some of the custom + # template tags use superclasses of django template tags, or otherwise cause + # the following situation to happen, it is possible that circular imports + # cause problems: + # If any of those superclasses import django.template.loader (for example, + # django.template.loader_tags does this), it will immediately try to register + # some builtins, possibly including some of the superclasses the custom template + # uses. This will then fail because the importing of the modules that contain + # those classes is already in progress (but not yet complete), which means that + # usually the module's register object does not yet exist. + # In other words: + # {custom-templatetag-module} -> + # {django-templatetag-module} -> + # django.template.loader -> + # add_to_builtins(django-templatetag-module) + # <-- django-templatetag-module.register does not yet exist + # It is therefor imperative that django.template.loader gets imported *before* + # any of the templatetags it registers. + import django.template.loader + + try: + for lib in settings.TEMPLATE_TAGS: + add_to_builtins(lib) + except AttributeError: + pass \ No newline at end of file
mintchaos/mint_django_utils
0d9e64eff073e74ee5ce05875ee4e490e6c5cad2
Three cheers for forking django! :(
diff --git a/templatetags/urls.py b/templatetags/urls.py new file mode 100644 index 0000000..705f18e --- /dev/null +++ b/templatetags/urls.py @@ -0,0 +1,110 @@ +""" +This is a hack to get around a defeciency in django's URL tag. Line 19 is the +only added line. +""" + +from django.conf import settings +from django.template import Node, NodeList, Template, Context, Variable +from django.template import Library +from django.utils.encoding import smart_str, smart_unicode + +register = Library() + +class URLNode(Node): + def __init__(self, view_name, args, kwargs, asvar): + self.view_name = view_name + self.args = args + self.kwargs = kwargs + self.asvar = asvar + + def render(self, context): + from django.core.urlresolvers import reverse, NoReverseMatch + args = [arg.resolve(context) for arg in self.args] + kwargs = dict([(smart_str(k,'ascii'), v.resolve(context)) + for k, v in self.kwargs.items()]) + kwargs = dict([(k,v) for k,v in kwargs.items() if v]) ## this is the only added line. + # Try to look up the URL twice: once given the view name, and again + # relative to what we guess is the "main" app. If they both fail, + # re-raise the NoReverseMatch unless we're using the + # {% url ... as var %} construct in which cause return nothing. + url = '' + try: + url = reverse(self.view_name, args=args, kwargs=kwargs) + except NoReverseMatch, e: + if settings.SETTINGS_MODULE: + project_name = settings.SETTINGS_MODULE.split('.')[0] + try: + url = reverse(project_name + '.' + self.view_name, + args=args, kwargs=kwargs) + except NoReverseMatch: + if self.asvar is None: + # Re-raise the original exception, not the one with + # the path relative to the project. This makes a + # better error message. + raise e + else: + if self.asvar is None: + raise e + + if self.asvar: + context[self.asvar] = url + return '' + else: + return url + +def url(parser, token): + """ + Returns an absolute URL matching given view with its parameters. + + This is a way to define links that aren't tied to a particular URL + configuration:: + + {% url path.to.some_view arg1,arg2,name1=value1 %} + + The first argument is a path to a view. It can be an absolute python path + or just ``app_name.view_name`` without the project name if the view is + located inside the project. Other arguments are comma-separated values + that will be filled in place of positional and keyword arguments in the + URL. All arguments for the URL should be present. + + For example if you have a view ``app_name.client`` taking client's id and + the corresponding line in a URLconf looks like this:: + + ('^client/(\d+)/$', 'app_name.client') + + and this app's URLconf is included into the project's URLconf under some + path:: + + ('^clients/', include('project_name.app_name.urls')) + + then in a template you can create a link for a certain client like this:: + + {% url app_name.client client.id %} + + The URL will look like ``/clients/client/123/``. + """ + bits = token.contents.split(' ') + if len(bits) < 2: + raise TemplateSyntaxError("'%s' takes at least one argument" + " (path to a view)" % bits[0]) + viewname = bits[1] + args = [] + kwargs = {} + asvar = None + + if len(bits) > 2: + bits = iter(bits[2:]) + for bit in bits: + if bit == 'as': + asvar = bits.next() + break + else: + for arg in bit.split(","): + if '=' in arg: + k, v = arg.split('=', 1) + k = k.strip() + kwargs[k] = parser.compile_filter(v) + elif arg: + args.append(parser.compile_filter(arg)) + return URLNode(viewname, args, kwargs, asvar) +url = register.tag(url)
mintchaos/mint_django_utils
c0c14a1745c8d6a9c85fb7796acb94ff2d5f5cd1
A genericized clean helper to make up for unique_for_date not working yet. :-/
diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..f48dea7 --- /dev/null +++ b/utils.py @@ -0,0 +1,21 @@ +from django import forms +from django.forms.util import ErrorList + +def clean_unique_for_date(self, field, date_field='pub_date'): + model = self.Meta.model + if date_field in self.cleaned_data: + date = self.cleaned_data[date_field] + get_args = { field: self.cleaned_data[field], + "%s__year" % date_field: date.year, + "%s__month" % date_field: date.month, + "%s__day" % date_field: date.day } + # import pdb; pdb.set_trace() + try: + obj = model.objects.get(**get_args) + if obj.id != self.instance.id: + msg = u"Please enter a different %s. The one you entered is already being used for %s" % (field, date.strftime("%Y-%m-%d")) + self._errors[field] = ErrorList([msg]) + del self.cleaned_data[field] + except model.DoesNotExist: + pass + return self.cleaned_data
mintchaos/mint_django_utils
ce1adddf58f2e7bd245d52760c9699303ba90def
added a shortcuts.py
diff --git a/shortcuts.py b/shortcuts.py new file mode 100644 index 0000000..3d3591c --- /dev/null +++ b/shortcuts.py @@ -0,0 +1,6 @@ +from django.shortcuts import render_to_response as django_render_to_response +from django.template import RequestContext + +def render_to_response(req, *args, **kwargs): + kwargs['context_instance'] = RequestContext(req) + return django_render_to_response(*args, **kwargs) \ No newline at end of file
mintchaos/mint_django_utils
b6b2c5732f0713da4a2881f86ef6e6612c92c0d2
added attribution to capture as
diff --git a/templatetags/capture.py b/templatetags/capture.py index 24735da..4eee2d8 100644 --- a/templatetags/capture.py +++ b/templatetags/capture.py @@ -1,23 +1,25 @@ +# my personal "fork" of http://www.djangosnippets.org/snippets/545/ + from django import template register = template.Library() @register.tag(name='capture') def do_captureas(parser, token): try: tag_name, _as, varname = token.contents.split() except ValueError: raise template.TemplateSyntaxError("'capture' requires a variable name.") nodelist = parser.parse(('endcapture',)) parser.delete_first_token() return CaptureasNode(nodelist, varname) class CaptureasNode(template.Node): def __init__(self, nodelist, varname): self.nodelist = nodelist self.varname = varname def render(self, context): output = self.nodelist.render(context) context[self.varname] = output return ''
arian/DirectAdminApi
1a18151240e32b0497c36a044c3542402c1332a8
Add a demo for emails + improve some PHPDocs
diff --git a/Source/DA/Emails.php b/Source/DA/Emails.php index 50ce78b..6951cb7 100644 --- a/Source/DA/Emails.php +++ b/Source/DA/Emails.php @@ -1,133 +1,133 @@ <?php /** * http://www.directadmin.com/api.html#email */ include_once dirname(__FILE__) . '/Api.php'; class DA_Emails extends DA_Api { /** * * @param string $domain * @return array */ public function fetch($domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'list', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); if (!empty($row['list']) && is_array($row['list'])){ return $row['list']; } return array(); } /** * Get a list of the users and the quota and usage * @param string $domain * @return array for example array('user' => array(usage=>3412,quota=>123543)) */ public function fetchQuotas($domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'list', 'type' => 'quota', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); if (is_array($row)){ foreach ($row as &$item) parse_str($item, $item); if (empty($item) || !is_array($item) || !isset($item['quota'])){ $row = array(); } } else { $row = array(); } return $row; } /** * Get the quota and usage for a user * @param string $user * @param string $domain - * @return array for example array(usage=>3412,quota=>123543) + * @return array for example array(usage=>3412,quota=>123543), both are in bytes */ public function fetchUserQuota($user, $domain = null){ $quotas = $this->fetchQuotas($domain); return (isset($quotas[$user]) ? $quotas[$user] : array()); } /** * Create an Email Address * @param string $user * @param string $pass - * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, 1+ for number of Megabytes. + * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, > 0 for number of Megabytes. * @param string $domain - * @return bool + * @return bool returns true if the email address was created succesfully */ public function create($user, $pass, $quota = 0, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'create', 'domain' => $domain, 'quota' => $quota, 'user' => $user, 'passwd' => $pass )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain - * @return bool + * @return bool returns true if the email address was created succesfully */ public function modify($user, $pass = null, $quota = 0, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'passwd' => $pass, 'passwd2' => $pass, 'quota' => $quota )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } } diff --git a/demo/email.php b/demo/email.php new file mode 100644 index 0000000..344da02 --- /dev/null +++ b/demo/email.php @@ -0,0 +1,42 @@ +<?php + +echo '<pre>'; + +include '../Source/DA/Emails.php'; + +// Optional, you can pass these as arguments of the class constructor too +$socket = new HTTPSocket(); +$socket->connect('topdomain.nl', 2222); +$socket->set_login('user', 'pass'); + +DA_Api::$DEFAULT_SOCKET = $socket; +DA_Api::$DEFAULT_DOMAIN = 'domain.nl'; + +// new DA_Emails instance +$emails = new DA_Emails(); + +// displays the users +print_r($emails->fetch()); + +// creates a new user, should return true +var_dump($emails->create( + 'testing', + 'test_pass', + 20 +)); + +// fetches the data, quota and usage, of one user +print_r($emails->fetchUserQuota('testing')); + +// sets a new password and quota +var_dump($emails->modify( + 'testing', + 'new_test_pass', + 30 +)); + +// fetches all data, including quotas and usage +print_r($emails->fetchQuotas()); + +// deletes the test user, should be true +var_dump($emails->delete('testing'));
arian/DirectAdminApi
3a219ed0bd2c9248a85bf0f2988301d5719f5893
Fix a PHP Notice of an undefined index in HTTPSocket
diff --git a/Source/HTTPSocket.php b/Source/HTTPSocket.php index c340c2d..0540bcd 100644 --- a/Source/HTTPSocket.php +++ b/Source/HTTPSocket.php @@ -1,435 +1,435 @@ <?php /** * Socket communication class. * * Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need. * * Very, very basic usage: * $Socket = new HTTPSocket; * echo $Socket->get('http://user:[email protected]/somedir/some.file?query=string&this=that'); * * @author Phi1 'l0rdphi1' Stier <[email protected]> * @package HTTPSocket * @version 2.7 */ class HTTPSocket { var $version = '2.7'; /* all vars are private except $error, $query_cache, and $doFollowLocationHeader */ var $method = 'GET'; var $remote_host; var $remote_port; var $remote_uname; var $remote_passwd; var $result; var $result_header; var $result_body; var $result_status_code; var $lastTransferSpeed; var $bind_host; var $error = array(); var $warn = array(); var $query_cache = array(); var $doFollowLocationHeader = TRUE; var $redirectURL; var $extra_headers = array(); /** * Create server "connection". * */ function connect($host, $port = '' ) { if (!is_numeric($port)) { $port = 80; } $this->remote_host = $host; $this->remote_port = $port; } function bind( $ip = '' ) { if ( $ip == '' ) { $ip = $_SERVER['SERVER_ADDR']; } $this->bind_host = $ip; } /** * Change the method being used to communicate. * * @param string|null request method. supports GET, POST, and HEAD. default is GET */ function set_method( $method = 'GET' ) { $this->method = strtoupper($method); } /** * Specify a username and password. * * @param string|null username. defualt is null * @param string|null password. defualt is null */ function set_login( $uname = '', $passwd = '' ) { if ( strlen($uname) > 0 ) { $this->remote_uname = $uname; } if ( strlen($passwd) > 0 ) { $this->remote_passwd = $passwd; } } /** * Query the server * * @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too. * @param string|array query to pass to url * @param int if connection KB/s drops below value here, will drop connection */ function query( $request, $content = '', $doSpeedCheck = 0 ) { $this->error = $this->warn = array(); $this->result_status_code = NULL; // is our request a http:// ... ? if (preg_match('!^http://!i',$request)) { $location = parse_url($request); $this->connect($location['host'],$location['port']); $this->set_login($location['user'],$location['pass']); $request = $location['path']; $content = $location['query']; if ( strlen($request) < 1 ) { $request = '/'; } } $array_headers = array( 'User-Agent' => "HTTPSocket/$this->version", 'Host' => ( $this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port" ), 'Accept' => '*/*', 'Connection' => 'Close' ); foreach ( $this->extra_headers as $key => $value ) { $array_headers[$key] = $value; } $this->result = $this->result_header = $this->result_body = ''; // was content sent as an array? if so, turn it into a string if (is_array($content)) { $pairs = array(); foreach ( $content as $key => $value ) { $pairs[] = "$key=".urlencode($value); } $content = join('&',$pairs); unset($pairs); } $OK = TRUE; // instance connection if ($this->bind_host) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($socket,$this->bind_host); if (!@socket_connect($socket,$this->remote_host,$this->remote_port)) { $OK = FALSE; } } else { $socket = @fsockopen( $this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10 ); } if ( !$socket || !$OK ) { $this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port."; return 0; } // if we have a username and password, add the header if ( isset($this->remote_uname) && isset($this->remote_passwd) ) { $array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd"); } // for DA skins: if $this->remote_passwd is NULL, try to use the login key system if ( isset($this->remote_uname) && $this->remote_passwd == NULL ) { $array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}"; } // if method is POST, add content length & type headers if ( $this->method == 'POST' ) { $array_headers['Content-type'] = 'application/x-www-form-urlencoded'; $array_headers['Content-length'] = strlen($content); } // else method is GET or HEAD. we don't support anything else right now. else { if ($content) { $request .= "?$content"; } } // prepare query $query = "$this->method $request HTTP/1.0\r\n"; foreach ( $array_headers as $key => $value ) { $query .= "$key: $value\r\n"; } $query .= "\r\n"; // if POST we need to append our content if ( $this->method == 'POST' && $content ) { $query .= "$content\r\n\r\n"; } // query connection if ($this->bind_host) { socket_write($socket,$query); // now load results while ( $out = socket_read($socket,2048) ) { $this->result .= $out; } } else { fwrite( $socket, $query, strlen($query) ); // now load results $this->lastTransferSpeed = 0; $status = socket_get_status($socket); $startTime = time(); $length = 0; $prevSecond = 0; while ( !feof($socket) && !$status['timed_out'] ) { $chunk = fgets($socket,1024); $length += strlen($chunk); $this->result .= $chunk; $elapsedTime = time() - $startTime; if ( $elapsedTime > 0 ) { $this->lastTransferSpeed = ($length/1024)/$elapsedTime; } if ( $doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck ) { $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".( ($length/1024)/$elapsedTime )."), dropping connection..."; $this->result_status_code = 503; break; } } if ( $this->lastTransferSpeed == 0 ) { $this->lastTransferSpeed = $length/1024; } } list($this->result_header,$this->result_body) = preg_split("/\r\n\r\n/",$this->result,2); if ($this->bind_host) { socket_close($socket); } else { fclose($socket); } $this->query_cache[] = $query; $headers = $this->fetch_header(); // what return status did we get? if (!$this->result_status_code) { preg_match("#HTTP/1\.. (\d+)#",$headers[0],$matches); $this->result_status_code = $matches[1]; } // did we get the full file? if ( !empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body) ) { $this->result_status_code = 206; } // now, if we're being passed a location header, should we follow it? if ($this->doFollowLocationHeader) { - if ($headers['location']) + if (!empty($headers['location'])) { $this->redirectURL = $headers['location']; $this->query($headers['location']); } } } function getTransferSpeed() { return $this->lastTransferSpeed; } /** * The quick way to get a URL's content :) * * @param string URL * @param boolean return as array? (like PHP's file() command) * @return string result body */ function get($location, $asArray = FALSE ) { $this->query($location); if ( $this->get_status_code() == 200 ) { if ($asArray) { return preg_split("/\n/",$this->fetch_body()); } return $this->fetch_body(); } return FALSE; } /** * Returns the last status code. * 200 = OK; * 403 = FORBIDDEN; * etc. * * @return int status code */ function get_status_code() { return $this->result_status_code; } /** * Adds a header, sent with the next query. * * @param string header name * @param string header value */ function add_header($key,$value) { $this->extra_headers[$key] = $value; } /** * Clears any extra headers. * */ function clear_headers() { $this->extra_headers = array(); } /** * Return the result of a query. * * @return string result */ function fetch_result() { return $this->result; } /** * Return the header of result (stuff before body). * * @param string (optional) header to return * @return array result header */ function fetch_header( $header = '' ) { $array_headers = preg_split("/\r\n/",$this->result_header); $array_return = array( 0 => $array_headers[0] ); unset($array_headers[0]); foreach ( $array_headers as $pair ) { list($key,$value) = preg_split("/: /",$pair,2); $array_return[strtolower($key)] = $value; } if ( $header != '' ) { return $array_return[strtolower($header)]; } return $array_return; } /** * Return the body of result (stuff after header). * * @return string result body */ function fetch_body() { return $this->result_body; } /** * Return parsed body in array format. * * @return array result parsed */ function fetch_parsed_body() { parse_str($this->result_body,$x); return $x; } }
arian/DirectAdminApi
a2aebf77afc0b79a8bee61616af93249e884c135
Fix the DA_Emails::fetch method
diff --git a/Source/DA/Emails.php b/Source/DA/Emails.php index f3a9ace..50ce78b 100644 --- a/Source/DA/Emails.php +++ b/Source/DA/Emails.php @@ -1,138 +1,133 @@ <?php /** * http://www.directadmin.com/api.html#email */ include_once dirname(__FILE__) . '/Api.php'; class DA_Emails extends DA_Api { /** * * @param string $domain * @return array */ public function fetch($domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'list', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); - if (is_array($row)){ - foreach ($row as &$item) parse_str($item, $item); - if (empty($item) || !is_array($item) || !isset($item['quota'])){ - $row = array(); - } - } else { - $row = array(); + if (!empty($row['list']) && is_array($row['list'])){ + return $row['list']; } return array(); } /** * Get a list of the users and the quota and usage * @param string $domain * @return array for example array('user' => array(usage=>3412,quota=>123543)) */ public function fetchQuotas($domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'list', 'type' => 'quota', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); if (is_array($row)){ foreach ($row as &$item) parse_str($item, $item); if (empty($item) || !is_array($item) || !isset($item['quota'])){ $row = array(); } } else { $row = array(); } return $row; } /** * Get the quota and usage for a user * @param string $user * @param string $domain * @return array for example array(usage=>3412,quota=>123543) */ public function fetchUserQuota($user, $domain = null){ $quotas = $this->fetchQuotas($domain); return (isset($quotas[$user]) ? $quotas[$user] : array()); } /** * Create an Email Address * @param string $user * @param string $pass * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, 1+ for number of Megabytes. * @param string $domain * @return bool */ public function create($user, $pass, $quota = 0, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'create', 'domain' => $domain, 'quota' => $quota, 'user' => $user, 'passwd' => $pass )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain * @return bool */ public function modify($user, $pass = null, $quota = 0, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP', array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'passwd' => $pass, 'passwd2' => $pass, 'quota' => $quota )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user, $domain = null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user )); $ret = $this->sock->fetch_parsed_body(); return (isset($ret['error']) && $ret['error'] == 0); } }
arian/DirectAdminApi
ce7744146d16540079867643f7eddcb1d7f02014
Add the possibility to set the default Socket and Domain for every instance of DA_Api with static properties
diff --git a/Source/DA/Api.php b/Source/DA/Api.php index f713e1e..4ddf6f4 100644 --- a/Source/DA/Api.php +++ b/Source/DA/Api.php @@ -1,41 +1,61 @@ <?php include_once dirname(__FILE__) . '/../HTTPSocket.php'; abstract class DA_Api { /** * @var HTTPSocket */ protected $sock; /** * The default domain * @var string */ protected $domain; + /** + * an instance of HTTPSocket which can be set to default, so you don't have to pass this into every DA_Api instance + * @var HTTPSocket + */ + static public $DEFAULT_SOCKET; + + /** + * The default domain + * @var string + */ + static public $DEFAULT_DOMAIN; + /** * * @param HTTPSocket $sock * @return */ - public function __construct(HTTPSocket $sock, $domain = null){ - $this->sock = $sock; - $this->domain = $domain; + public function __construct($sock = null, $domain = null){ + + $this->sock = self::$DEFAULT_SOCKET; + if ($sock instanceof HTTPSocket) $this->sock = $sock; + if (!($this->sock instanceof HTTPSocket)){ + throw new DA_Exception('The socket is not an instance of HTTPSocket, set the first argument or the DA_Api::$DEFAULT_SOCKET variables'); + } + + $this->domain = self::$DEFAULT_DOMAIN; + if ($domain !== null) $this->domain = $domain; + } public function setDomain($domain){ $this->domain = $domain; } public function getDomain($domain = null){ if (!$domain) $domain = $this->domain; if (empty($domain)){ include_once dirname(__FILE__) . '/Exception.php'; throw new DA_Exception('No domain set, use the setDomain method to set one!'); } return $domain; } }
arian/DirectAdminApi
86eba6324c2862d332378924aaf1391f124fe079
Replace deprecated split for explode in HTTPSocket.php
diff --git a/Source/HTTPSocket.php b/Source/HTTPSocket.php index 86901af..1ae3bbc 100644 --- a/Source/HTTPSocket.php +++ b/Source/HTTPSocket.php @@ -1,435 +1,435 @@ <?php /** * Socket communication class. * * Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need. * * Very, very basic usage: * $Socket = new HTTPSocket; * echo $Socket->get('http://user:[email protected]/somedir/some.file?query=string&this=that'); * * @author Phi1 'l0rdphi1' Stier <[email protected]> * @package HTTPSocket * @version 2.6 */ class HTTPSocket { var $version = '2.6'; /* all vars are private except $error, $query_cache, and $doFollowLocationHeader */ var $method = 'GET'; var $remote_host; var $remote_port; var $remote_uname; var $remote_passwd; var $result; var $result_header; var $result_body; var $result_status_code; var $lastTransferSpeed; var $bind_host; var $error = array(); var $warn = array(); var $query_cache = array(); var $doFollowLocationHeader = TRUE; var $redirectURL; var $extra_headers = array(); /** * Create server "connection". * */ function connect($host, $port = '' ) { if (!is_numeric($port)) { $port = 80; } $this->remote_host = $host; $this->remote_port = $port; } function bind( $ip = '' ) { if ( $ip == '' ) { $ip = $_SERVER['SERVER_ADDR']; } $this->bind_host = $ip; } /** * Change the method being used to communicate. * * @param string|null request method. supports GET, POST, and HEAD. default is GET */ function set_method( $method = 'GET' ) { $this->method = strtoupper($method); } /** * Specify a username and password. * * @param string|null username. defualt is null * @param string|null password. defualt is null */ function set_login( $uname = '', $passwd = '' ) { if ( strlen($uname) > 0 ) { $this->remote_uname = $uname; } if ( strlen($passwd) > 0 ) { $this->remote_passwd = $passwd; } } /** * Query the server * * @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too. * @param string|array query to pass to url * @param int if connection KB/s drops below value here, will drop connection */ function query( $request, $content = '', $doSpeedCheck = 0 ) { $this->error = $this->warn = array(); $this->result_status_code = NULL; // is our request a http:// ... ? if (preg_match('!^http://!i',$request)) { $location = parse_url($request); $this->connect($location['host'],$location['port']); $this->set_login($location['user'],$location['pass']); $request = $location['path']; $content = $location['query']; if ( strlen($request) < 1 ) { $request = '/'; } } $array_headers = array( 'User-Agent' => "HTTPSocket/$this->version", 'Host' => ( $this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port" ), 'Accept' => '*/*', 'Connection' => 'Close' ); foreach ( $this->extra_headers as $key => $value ) { $array_headers[$key] = $value; } $this->result = $this->result_header = $this->result_body = ''; // was content sent as an array? if so, turn it into a string if (is_array($content)) { $pairs = array(); foreach ( $content as $key => $value ) { $pairs[] = "$key=".urlencode($value); } $content = join('&',$pairs); unset($pairs); } $OK = TRUE; // instance connection if ($this->bind_host) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($socket,$this->bind_host); if (!@socket_connect($socket,$this->remote_host,$this->remote_port)) { $OK = FALSE; } } else { $socket = @fsockopen( $this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10 ); } if ( !$socket || !$OK ) { $this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port."; return 0; } // if we have a username and password, add the header if ( isset($this->remote_uname) && isset($this->remote_passwd) ) { $array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd"); } // for DA skins: if $this->remote_passwd is NULL, try to use the login key system if ( isset($this->remote_uname) && $this->remote_passwd == NULL ) { $array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}"; } // if method is POST, add content length & type headers if ( $this->method == 'POST' ) { $array_headers['Content-type'] = 'application/x-www-form-urlencoded'; $array_headers['Content-length'] = strlen($content); } // else method is GET or HEAD. we don't support anything else right now. else { if ($content) { $request .= "?$content"; } } // prepare query $query = "$this->method $request HTTP/1.0\r\n"; foreach ( $array_headers as $key => $value ) { $query .= "$key: $value\r\n"; } $query .= "\r\n"; // if POST we need to append our content if ( $this->method == 'POST' && $content ) { $query .= "$content\r\n\r\n"; } // query connection if ($this->bind_host) { socket_write($socket,$query); // now load results while ( $out = socket_read($socket,2048) ) { $this->result .= $out; } } else { fwrite( $socket, $query, strlen($query) ); // now load results $this->lastTransferSpeed = 0; $status = socket_get_status($socket); $startTime = time(); $length = 0; $prevSecond = 0; while ( !feof($socket) && !$status['timed_out'] ) { $chunk = fgets($socket,1024); $length += strlen($chunk); $this->result .= $chunk; $elapsedTime = time() - $startTime; if ( $elapsedTime > 0 ) { $this->lastTransferSpeed = ($length/1024)/$elapsedTime; } if ( $doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck ) { $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".( ($length/1024)/$elapsedTime )."), dropping connection..."; $this->result_status_code = 503; break; } } if ( $this->lastTransferSpeed == 0 ) { $this->lastTransferSpeed = $length/1024; } } - list($this->result_header,$this->result_body) = split("\r\n\r\n",$this->result,2); + list($this->result_header,$this->result_body) = explode("\r\n\r\n",$this->result,2); if ($this->bind_host) { socket_close($socket); } else { fclose($socket); } $this->query_cache[] = $query; $headers = $this->fetch_header(); // what return status did we get? if (!$this->result_status_code) { preg_match("#HTTP/1\.. (\d+)#",$headers[0],$matches); $this->result_status_code = $matches[1]; } // did we get the full file? if ( !empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body) ) { $this->result_status_code = 206; } // now, if we're being passed a location header, should we follow it? if ($this->doFollowLocationHeader) { if (!empty($headers['location'])) { $this->redirectURL = $headers['location']; $this->query($headers['location']); } } } function getTransferSpeed() { return $this->lastTransferSpeed; } /** * The quick way to get a URL's content :) * * @param string URL * @param boolean return as array? (like PHP's file() command) * @return string result body */ function get($location, $asArray = FALSE ) { $this->query($location); if ( $this->get_status_code() == 200 ) { if ($asArray) { - return split("\n",$this->fetch_body()); + return explode("\n",$this->fetch_body()); } return $this->fetch_body(); } return FALSE; } /** * Returns the last status code. * 200 = OK; * 403 = FORBIDDEN; * etc. * * @return int status code */ function get_status_code() { return $this->result_status_code; } /** * Adds a header, sent with the next query. * * @param string header name * @param string header value */ function add_header($key,$value) { $this->extra_headers[$key] = $value; } /** * Clears any extra headers. * */ function clear_headers() { $this->extra_headers = array(); } /** * Return the result of a query. * * @return string result */ function fetch_result() { return $this->result; } /** * Return the header of result (stuff before body). * * @param string (optional) header to return * @return array result header */ function fetch_header( $header = '' ) { - $array_headers = split("\r\n",$this->result_header); + $array_headers = explode("\r\n",$this->result_header); $array_return = array( 0 => $array_headers[0] ); unset($array_headers[0]); foreach ( $array_headers as $pair ) { - list($key,$value) = split(": ",$pair,2); + list($key,$value) = explode(": ",$pair,2); $array_return[strtolower($key)] = $value; } if ( $header != '' ) { return $array_return[strtolower($header)]; } return $array_return; } /** * Return the body of result (stuff after header). * * @return string result body */ function fetch_body() { return $this->result_body; } /** * Return parsed body in array format. * * @return array result parsed */ function fetch_parsed_body() { parse_str($this->result_body,$x); return $x; } -} \ No newline at end of file +}
arian/DirectAdminApi
27ce1a4b89baa87ae06fb7778aad59728cf792a9
Fix exception path
diff --git a/Source/DA/Api.php b/Source/DA/Api.php index cfb73b3..41db684 100644 --- a/Source/DA/Api.php +++ b/Source/DA/Api.php @@ -1,41 +1,41 @@ <?php include_once 'HTTPSocket.php'; abstract class DA_API { /** * @var HTTPSocket */ protected $sock; /** * The default domain * @var string */ protected $domain; /** * * @param HTTPSocket $sock * @return */ public function __construct(HTTPSocket $sock,$domain=null){ $this->sock = $sock; $this->domain = $domain; } public function setDomain($domain){ $this->domain = $domain; } public function getDomain($domain=null){ $domain = $domain ? $domain : $this->domain; if(empty($domain)){ - include_once 'DA_Exception.php'; + include_once 'Exception.php'; throw new DA_Exception('No Domain is set!'); } return $domain; } }
arian/DirectAdminApi
c35d18b06026c76b715e378888d3385c05319be7
Fix fetchQuotas method
diff --git a/Source/DA/Api.php b/Source/DA/Api.php index bce3526..cfb73b3 100644 --- a/Source/DA/Api.php +++ b/Source/DA/Api.php @@ -1,42 +1,41 @@ <?php include_once 'HTTPSocket.php'; abstract class DA_API { - + /** * @var HTTPSocket */ protected $sock; - + /** * The default domain * @var string */ protected $domain; - + /** - * + * * @param HTTPSocket $sock - * @return + * @return */ public function __construct(HTTPSocket $sock,$domain=null){ $this->sock = $sock; $this->domain = $domain; } - + public function setDomain($domain){ $this->domain = $domain; } - + public function getDomain($domain=null){ $domain = $domain ? $domain : $this->domain; if(empty($domain)){ include_once 'DA_Exception.php'; throw new DA_Exception('No Domain is set!'); } return $domain; } - - + } diff --git a/Source/DA/Emails.php b/Source/DA/Emails.php index 5d31360..cbae3dc 100644 --- a/Source/DA/Emails.php +++ b/Source/DA/Emails.php @@ -1,140 +1,142 @@ <?php /** * http://www.directadmin.com/api.html#email */ include_once 'Api.php'; class DA_Emails extends DA_API { /** * * @param string $domain * @return array */ public function fetch($domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'list', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); if(is_array($row)){ foreach($row as &$item){ parse_str($item,$item); } if(empty($item) || !is_array($item) || !isset($item['quota'])){ $row = array(); } }else{ $row = array(); } return array(); } /** * Get a list of the users and the quota and usage * @param string $domain * @return array for example array('user' => array(usage=>3412,quota=>123543)) */ public function fetchQuotas($domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'list', 'type' => 'quota', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); - - if(isset($row['error']) && isset($row['text'])){ - include_once 'DA_Exception.php'; - throw new DA_Exception($row['text'].' - '.$row['details']); + if(is_array($row)){ + foreach($row as &$item){ + parse_str($item,$item); + } + if(empty($item) || !is_array($item) || !isset($item['quota'])){ + $row = array(); + } + }else{ + $row = array(); } - foreach($row as &$item){ - parse_str($item,$item); - } return $row; } /** * Get the quota and usage for a user * @param string $user * @param string $domain * @return array for example array(usage=>3412,quota=>123543) */ public function fetchUserQuota($user,$domain=null){ $quotas = $this->fetchQuotas($domain); return isset($quotas[$user]) ? $quotas[$user] : array(); } /** * Create an Email Address * @param string $user * @param string $pass * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, 1+ for number of Megabytes. * @param string $domain * @return bool */ public function create($user,$pass,$quota=0,$domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'create', 'domain' => $domain, 'quota' => $quota, 'user' => $user, 'passwd' => $pass )); $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain * @return bool */ public function modify($user,$pass=null,$quota=0,$domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'passwd' => $pass, 'passwd2' => $pass, 'quota' => $quota )); $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user,$domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_POP',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user )); $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } }
arian/DirectAdminApi
1d58484837de78361babed9da7e0d0b2aa8b2772
Restructure and verify that the data is correct
diff --git a/Source/DA_API.php b/Source/DA/Api.php similarity index 100% rename from Source/DA_API.php rename to Source/DA/Api.php diff --git a/Source/DA_Autoresponders.php b/Source/DA/Autoresponders.php similarity index 91% rename from Source/DA_Autoresponders.php rename to Source/DA/Autoresponders.php index e3239ca..0ef24da 100644 --- a/Source/DA_Autoresponders.php +++ b/Source/DA/Autoresponders.php @@ -1,109 +1,116 @@ <?php /** * http://www.directadmin.com/api.html#email * http://www.directadmin.com/features.php?id=348 */ +include_once 'Api.php'; + class DA_Autoresponders extends DA_API { - + /** * Fetch all the Autoresponders * @param string $domain * @return array array(array('user' => 'destination email')) */ public function fetch($domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( 'domain' => $domain )); - return $this->sock->fetch_parsed_body(); + $rows = $this->sock->fetch_parsed_body(); + $keys = array_keys($rows); + if(isset($keys[1]) && $keys[1] == '#95API'){ + $rows = array(); + } + return $rows; } - + /** * Fetch the destination url of a forwarder * @param string $user * @param string $domain - * @return string + * @return string */ public function fetchUser($user,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER_MODIFY',array( 'domain' => $domain, 'user' => $user - )); + )); return $this->sock->fetch_parsed_body(); } - + /** * Create a forwarder * @param string $user * @param string $email * @param string $domain * @return bool */ public function create($user,$msg,$email=null,$domain=null){ $domain = $this->getDomain($domain); - + $data = array( 'action' => 'create', 'domain' => $domain, 'user' => $user, 'text' => $msg, 'cc' => empty($email) ? 'OFF' : 'ON', 'email' => $email, 'create' => 'Create' ); $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',$data); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain * @return bool */ public function modify($user,$msg,$email,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'text' => $msg, 'cc' => empty($email) ? 'OFF' : 'ON', 'email' => $email, 'create' => 'Create' )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user, 'select0' => $user )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + } diff --git a/Source/DA_Emails.php b/Source/DA/Emails.php similarity index 88% rename from Source/DA_Emails.php rename to Source/DA/Emails.php index c65f13b..5d31360 100644 --- a/Source/DA_Emails.php +++ b/Source/DA/Emails.php @@ -1,136 +1,140 @@ <?php /** * http://www.directadmin.com/api.html#email */ -include_once 'DA_API.php'; +include_once 'Api.php'; class DA_Emails extends DA_API { - + /** - * + * * @param string $domain * @return array */ public function fetch($domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_POP',array( 'action' => 'list', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); - - if(isset($row['list']) && is_array($row['list'])){ - return $row['list']; - }elseif(isset($row['error']) && isset($row['text'])){ - include_once 'DA_Exception.php'; - throw new DA_Exception($row['text'].' - '.$row['details']); + + if(is_array($row)){ + foreach($row as &$item){ + parse_str($item,$item); + } + if(empty($item) || !is_array($item) || !isset($item['quota'])){ + $row = array(); + } + }else{ + $row = array(); } return array(); } - + /** * Get a list of the users and the quota and usage * @param string $domain * @return array for example array('user' => array(usage=>3412,quota=>123543)) */ public function fetchQuotas($domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_POP',array( 'action' => 'list', 'type' => 'quota', 'domain' => $domain )); $row = $this->sock->fetch_parsed_body(); if(isset($row['error']) && isset($row['text'])){ include_once 'DA_Exception.php'; throw new DA_Exception($row['text'].' - '.$row['details']); } foreach($row as &$item){ parse_str($item,$item); - } + } return $row; } - + /** * Get the quota and usage for a user * @param string $user * @param string $domain * @return array for example array(usage=>3412,quota=>123543) */ - public function fetchUserQuota($user,$domain=null){ + public function fetchUserQuota($user,$domain=null){ $quotas = $this->fetchQuotas($domain); return isset($quotas[$user]) ? $quotas[$user] : array(); } /** * Create an Email Address * @param string $user * @param string $pass * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, 1+ for number of Megabytes. * @param string $domain * @return bool */ public function create($user,$pass,$quota=0,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_POP',array( 'action' => 'create', 'domain' => $domain, 'quota' => $quota, 'user' => $user, 'passwd' => $pass )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain * @return bool */ public function modify($user,$pass=null,$quota=0,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_POP',array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'passwd' => $pass, 'passwd2' => $pass, 'quota' => $quota )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_POP',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + } diff --git a/Source/DA_Exception.php b/Source/DA/Exception.php similarity index 100% rename from Source/DA_Exception.php rename to Source/DA/Exception.php diff --git a/Source/DA_Forwarders.php b/Source/DA/Forwarders.php similarity index 90% rename from Source/DA_Forwarders.php rename to Source/DA/Forwarders.php index c1707ed..2beef6b 100644 --- a/Source/DA_Forwarders.php +++ b/Source/DA/Forwarders.php @@ -1,97 +1,104 @@ <?php /** * http://www.directadmin.com/api.html#email */ +include_once 'Api.php'; + class DA_Forwarders extends DA_API { - + /** * Fetch all the forwarders * @param string $domain * @return array array(array('user' => 'destination email')) */ public function fetch($domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( 'action' => 'list', 'domain' => $domain )); - return $this->sock->fetch_parsed_body(); + $rows = $this->sock->fetch_parsed_body(); + $keys = array_keys($rows); + if(isset($keys[1]) && $keys[1] == '#95API'){ + $rows = array(); + } + return $rows; } - + /** * Fetch the destination url of a forwarder * @param string $user * @param string $domain - * @return string + * @return string */ public function fetchUser($user,$domain=null){ $users = $this->fetch($domain); return isset($users[$user]) ? $users[$user] : null; } - + /** * Create a forwarder * @param string $user * @param string $email * @param string $domain * @return bool */ public function create($user,$email,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( 'action' => 'create', 'domain' => $domain, 'user' => $user, 'email' => $email, )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Set the password of an emailaddress * @param string $user * @param string $pass * @param string $domain * @return bool */ public function modify($user,$email,$domain=null){ $domain = $this->getDomain($domain); $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( 'action' => 'modify', 'domain' => $domain, 'user' => $user, 'email' => $email, )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + /** * Delete an user * @param string $user * @param string $domain * @return bool */ public function delete($user,$domain=null){ $domain = $this->getDomain($domain); - + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( 'action' => 'delete', 'domain' => $domain, 'user' => $user, 'select0' => $user )); - + $ret = $this->sock->fetch_parsed_body(); return isset($ret['error']) && $ret['error'] == 0; } - + } diff --git a/demo/example.php b/demo/example.php index d282c5b..acb4557 100644 --- a/demo/example.php +++ b/demo/example.php @@ -1,85 +1,85 @@ <?php echo '<pre>'; include_once '../Source/HTTPSocket.php'; $sock = new HTTPSocket(); $sock->connect('domain.nl',2222); $sock->set_login('DirectAdminUsername','DirectAdminPassword'); -include_once '../Source/DA_Emails.php'; +include_once '../Source/DA/Emails.php'; $emails = new DA_Emails($sock,'domain.com'); try { // Fetch a list of users (before the @ sign) or pop emails print_r($emails->fetch()); - + // Fetch a list of users and their usage and quota print_r($emails->fetchQuotas()); - + // Fetch the quota and usage for a single user print_r($emails->fetchUserQuota('username')); - + // Create a user email => username - password - quota (MiB) var_dump($emails->create('username','pass',50)); - + // Modify a user email => username - password - quota (MiB) var_dump($emails->modify('username')); - + // Delete a user email var_dump($emails->delete('username')); - + }catch(DA_Exception $e){ echo $e->getMessage(); } -include_once '../Source/DA_Forwarders.php'; +include_once '../Source/DA/Forwarders.php'; $fwd = new DA_Forwarders($sock); $fwd->setDomain('refox.nl'); try { // Fetch a list of users and their forward emails print_r($fwd->fetch()); /* ( [user1] => [email protected] [other] => [email protected] [user3] => [email protected] ) - */ - + */ + // Fetch forward email address of an user print_r($fwd->fetchUser('username')); - + // Create a forward email => username - forward email var_dump($fwd->create('username','[email protected]')); - + // Modify a forward email => username - forward email var_dump($fwd->modify('username','[email protected]')); - + // Delete a forward email var_dump($fwd->delete('username')); - + }catch(DA_Exception $e){ echo $e->getMessage(); } // Auto Responders works much the same -include_once '../Source/DA_Autoresponders.php'; +include_once '../Source/DA/Autoresponders.php'; $resp = new DA_Autoresponders($sock,'mydomain.com'); try { print_r($resp->fetch()); print_r($resp->fetchUser('username')); - + var_dump($resp->create('username','respond message','[email protected]')); - + var_dump($resp->modify('username','Hi there, i will reply you soon!')); - + var_dump($resp->delete('username')); - + }catch(DA_Exception $e){ echo $e->getMessage(); }
arian/DirectAdminApi
089395462412a3221525b33bb2c0b9ef6a76f345
Change the README.md a little
diff --git a/README.md b/README.md index f808245..dd57a33 100644 --- a/README.md +++ b/README.md @@ -1,85 +1,86 @@ PHP Direct Admin API ==================== This is a set of classes to communicate with Direct Admin (DA) via the Direct Admin API to configurate some things in for your webserver without login in to Direct Admin itself. With this library you can control your webserver in your own environmet, for example your very own CMS. This library is far from complete and it currently has only support for: 1. POP Email addresses 2. Email Forwarders 3. Email Auto Responders It would be great to add more features to create a simple to use PHP implementation of the Direct Admin API -==== How to use ==== +How to use +========= See demo/example.php for more examples. You can browse the source code as well and try things out for the right usage. Connect ------- First we have to connect to Direct admin trough a HTTP Socket include_once 'HTTPSocket.php'; $sock = new HTTPSocket(); $sock->connect('domain.nl',2222); $sock->set_login('DirectAdminUsername','DirectAdminPassword'); You have to fill your own DA username, password and domain. This is the domain you to to if you want to go to DA: www.domain.com:2222. The username and password are the username and password you fill in the form at www.domain.com:2222 Fetch ----- Then we want to fetch some data. For example the POP3 Email list include_once 'DA_Emails.php'; $emails = new DA_Emails($sock,'domain.com'); try { $list = $emails->fetch(); }catch(DA_Exception $e){ echo $e->getMessage(); } First, we have to set a domain. Most of the times this is the same domain we have connected to. Secondly we create a try-catch blog. This is because the classes can throw DA_Exceptions. Finally we fetch the list of emails with $emails->fetch() and assign it to $list. This is pretty most the same for other classes like DA_Forwarders and DA_Autoresponders Create and Modify ----------------- If we use the same setup as above with the fetch method, the only thing we have to change is this: $emails->create('user','password'); Modify goes the same way $emails->modify('user','password'); Delete ------ $emails->delete('username'); \ No newline at end of file
arian/DirectAdminApi
47931653a356e2e4db1ce78cb24b4ab007508489
Change the README.md header
diff --git a/README.md b/README.md index 1601276..f808245 100644 --- a/README.md +++ b/README.md @@ -1,84 +1,85 @@ -==== PHP Direct Admin API ==== +PHP Direct Admin API +==================== This is a set of classes to communicate with Direct Admin (DA) via the Direct Admin API to configurate some things in for your webserver without login in to Direct Admin itself. With this library you can control your webserver in your own environmet, for example your very own CMS. This library is far from complete and it currently has only support for: 1. POP Email addresses 2. Email Forwarders 3. Email Auto Responders It would be great to add more features to create a simple to use PHP implementation of the Direct Admin API ==== How to use ==== See demo/example.php for more examples. You can browse the source code as well and try things out for the right usage. Connect ------- First we have to connect to Direct admin trough a HTTP Socket include_once 'HTTPSocket.php'; $sock = new HTTPSocket(); $sock->connect('domain.nl',2222); $sock->set_login('DirectAdminUsername','DirectAdminPassword'); You have to fill your own DA username, password and domain. This is the domain you to to if you want to go to DA: www.domain.com:2222. The username and password are the username and password you fill in the form at www.domain.com:2222 Fetch ----- Then we want to fetch some data. For example the POP3 Email list include_once 'DA_Emails.php'; $emails = new DA_Emails($sock,'domain.com'); try { $list = $emails->fetch(); }catch(DA_Exception $e){ echo $e->getMessage(); } First, we have to set a domain. Most of the times this is the same domain we have connected to. Secondly we create a try-catch blog. This is because the classes can throw DA_Exceptions. Finally we fetch the list of emails with $emails->fetch() and assign it to $list. This is pretty most the same for other classes like DA_Forwarders and DA_Autoresponders Create and Modify ----------------- If we use the same setup as above with the fetch method, the only thing we have to change is this: $emails->create('user','password'); Modify goes the same way $emails->modify('user','password'); Delete ------ $emails->delete('username'); \ No newline at end of file
arian/DirectAdminApi
c4b6e6210255d07afa2d5b1f515cc2f1769ae911
fist commit
diff --git a/README.md b/README.md new file mode 100644 index 0000000..1601276 --- /dev/null +++ b/README.md @@ -0,0 +1,84 @@ +==== PHP Direct Admin API ==== + +This is a set of classes to communicate with Direct Admin (DA) +via the Direct Admin API to configurate some things in +for your webserver without login in to Direct Admin itself. + +With this library you can control your webserver in your own +environmet, for example your very own CMS. + +This library is far from complete and it currently has only support +for: +1. POP Email addresses +2. Email Forwarders +3. Email Auto Responders + +It would be great to add more features to create a simple to use PHP +implementation of the Direct Admin API + +==== How to use ==== + +See demo/example.php for more examples. +You can browse the source code as well and try things out for the right +usage. + +Connect +------- + +First we have to connect to Direct admin trough a HTTP Socket + + include_once 'HTTPSocket.php'; + + $sock = new HTTPSocket(); + $sock->connect('domain.nl',2222); + $sock->set_login('DirectAdminUsername','DirectAdminPassword'); + +You have to fill your own DA username, password and domain. This is the +domain you to to if you want to go to DA: www.domain.com:2222. +The username and password are the username and password you fill in the +form at www.domain.com:2222 + +Fetch +----- + +Then we want to fetch some data. For example the POP3 Email list + + include_once 'DA_Emails.php'; + + $emails = new DA_Emails($sock,'domain.com'); + + try { + $list = $emails->fetch(); + }catch(DA_Exception $e){ + echo $e->getMessage(); + } + +First, we have to set a domain. Most of the times this is the same domain +we have connected to. + +Secondly we create a try-catch blog. This is because the classes can throw +DA_Exceptions. + +Finally we fetch the list of emails with $emails->fetch() and assign it to $list. + +This is pretty most the same for other classes like DA_Forwarders and DA_Autoresponders + +Create and Modify +----------------- + +If we use the same setup as above with the fetch method, the only thing we +have to change is this: + + $emails->create('user','password'); + +Modify goes the same way + + $emails->modify('user','password'); + +Delete +------ + + $emails->delete('username'); + + + \ No newline at end of file diff --git a/Source/DA_API.php b/Source/DA_API.php new file mode 100644 index 0000000..bce3526 --- /dev/null +++ b/Source/DA_API.php @@ -0,0 +1,42 @@ +<?php + +include_once 'HTTPSocket.php'; + +abstract class DA_API { + + /** + * @var HTTPSocket + */ + protected $sock; + + /** + * The default domain + * @var string + */ + protected $domain; + + /** + * + * @param HTTPSocket $sock + * @return + */ + public function __construct(HTTPSocket $sock,$domain=null){ + $this->sock = $sock; + $this->domain = $domain; + } + + public function setDomain($domain){ + $this->domain = $domain; + } + + public function getDomain($domain=null){ + $domain = $domain ? $domain : $this->domain; + if(empty($domain)){ + include_once 'DA_Exception.php'; + throw new DA_Exception('No Domain is set!'); + } + return $domain; + } + + +} diff --git a/Source/DA_Autoresponders.php b/Source/DA_Autoresponders.php new file mode 100644 index 0000000..e3239ca --- /dev/null +++ b/Source/DA_Autoresponders.php @@ -0,0 +1,109 @@ +<?php + +/** + * http://www.directadmin.com/api.html#email + * http://www.directadmin.com/features.php?id=348 + */ + +class DA_Autoresponders extends DA_API { + + /** + * Fetch all the Autoresponders + * @param string $domain + * @return array array(array('user' => 'destination email')) + */ + public function fetch($domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( + 'domain' => $domain + )); + return $this->sock->fetch_parsed_body(); + } + + /** + * Fetch the destination url of a forwarder + * @param string $user + * @param string $domain + * @return string + */ + public function fetchUser($user,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER_MODIFY',array( + 'domain' => $domain, + 'user' => $user + )); + return $this->sock->fetch_parsed_body(); + } + + /** + * Create a forwarder + * @param string $user + * @param string $email + * @param string $domain + * @return bool + */ + public function create($user,$msg,$email=null,$domain=null){ + $domain = $this->getDomain($domain); + + $data = array( + 'action' => 'create', + 'domain' => $domain, + 'user' => $user, + 'text' => $msg, + 'cc' => empty($email) ? 'OFF' : 'ON', + 'email' => $email, + 'create' => 'Create' + ); + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',$data); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Set the password of an emailaddress + * @param string $user + * @param string $pass + * @param string $domain + * @return bool + */ + public function modify($user,$msg,$email,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( + 'action' => 'modify', + 'domain' => $domain, + 'user' => $user, + 'text' => $msg, + 'cc' => empty($email) ? 'OFF' : 'ON', + 'email' => $email, + 'create' => 'Create' + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Delete an user + * @param string $user + * @param string $domain + * @return bool + */ + public function delete($user,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_AUTORESPONDER',array( + 'action' => 'delete', + 'domain' => $domain, + 'user' => $user, + 'select0' => $user + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + +} diff --git a/Source/DA_Emails.php b/Source/DA_Emails.php new file mode 100644 index 0000000..c65f13b --- /dev/null +++ b/Source/DA_Emails.php @@ -0,0 +1,136 @@ +<?php + +/** + * http://www.directadmin.com/api.html#email + */ + +include_once 'DA_API.php'; + +class DA_Emails extends DA_API { + + /** + * + * @param string $domain + * @return array + */ + public function fetch($domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_POP',array( + 'action' => 'list', + 'domain' => $domain + )); + $row = $this->sock->fetch_parsed_body(); + + if(isset($row['list']) && is_array($row['list'])){ + return $row['list']; + }elseif(isset($row['error']) && isset($row['text'])){ + include_once 'DA_Exception.php'; + throw new DA_Exception($row['text'].' - '.$row['details']); + } + return array(); + } + + /** + * Get a list of the users and the quota and usage + * @param string $domain + * @return array for example array('user' => array(usage=>3412,quota=>123543)) + */ + public function fetchQuotas($domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_POP',array( + 'action' => 'list', + 'type' => 'quota', + 'domain' => $domain + )); + $row = $this->sock->fetch_parsed_body(); + + if(isset($row['error']) && isset($row['text'])){ + include_once 'DA_Exception.php'; + throw new DA_Exception($row['text'].' - '.$row['details']); + } + + foreach($row as &$item){ + parse_str($item,$item); + } + return $row; + } + + /** + * Get the quota and usage for a user + * @param string $user + * @param string $domain + * @return array for example array(usage=>3412,quota=>123543) + */ + public function fetchUserQuota($user,$domain=null){ + $quotas = $this->fetchQuotas($domain); + return isset($quotas[$user]) ? $quotas[$user] : array(); + } + + /** + * Create an Email Address + * @param string $user + * @param string $pass + * @param int $quota [optional] Integer in Megabytes. Zero for unlimited, 1+ for number of Megabytes. + * @param string $domain + * @return bool + */ + public function create($user,$pass,$quota=0,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_POP',array( + 'action' => 'create', + 'domain' => $domain, + 'quota' => $quota, + 'user' => $user, + 'passwd' => $pass + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Set the password of an emailaddress + * @param string $user + * @param string $pass + * @param string $domain + * @return bool + */ + public function modify($user,$pass=null,$quota=0,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_POP',array( + 'action' => 'modify', + 'domain' => $domain, + 'user' => $user, + 'passwd' => $pass, + 'passwd2' => $pass, + 'quota' => $quota + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Delete an user + * @param string $user + * @param string $domain + * @return bool + */ + public function delete($user,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_POP',array( + 'action' => 'delete', + 'domain' => $domain, + 'user' => $user + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + +} diff --git a/Source/DA_Exception.php b/Source/DA_Exception.php new file mode 100644 index 0000000..9b3b4f5 --- /dev/null +++ b/Source/DA_Exception.php @@ -0,0 +1,3 @@ +<?php + +class DA_Exception extends Exception {} diff --git a/Source/DA_Forwarders.php b/Source/DA_Forwarders.php new file mode 100644 index 0000000..c1707ed --- /dev/null +++ b/Source/DA_Forwarders.php @@ -0,0 +1,97 @@ +<?php + +/** + * http://www.directadmin.com/api.html#email + */ + +class DA_Forwarders extends DA_API { + + /** + * Fetch all the forwarders + * @param string $domain + * @return array array(array('user' => 'destination email')) + */ + public function fetch($domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( + 'action' => 'list', + 'domain' => $domain + )); + return $this->sock->fetch_parsed_body(); + } + + /** + * Fetch the destination url of a forwarder + * @param string $user + * @param string $domain + * @return string + */ + public function fetchUser($user,$domain=null){ + $users = $this->fetch($domain); + return isset($users[$user]) ? $users[$user] : null; + } + + /** + * Create a forwarder + * @param string $user + * @param string $email + * @param string $domain + * @return bool + */ + public function create($user,$email,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( + 'action' => 'create', + 'domain' => $domain, + 'user' => $user, + 'email' => $email, + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Set the password of an emailaddress + * @param string $user + * @param string $pass + * @param string $domain + * @return bool + */ + public function modify($user,$email,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( + 'action' => 'modify', + 'domain' => $domain, + 'user' => $user, + 'email' => $email, + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + + /** + * Delete an user + * @param string $user + * @param string $domain + * @return bool + */ + public function delete($user,$domain=null){ + $domain = $this->getDomain($domain); + + $this->sock->query('/CMD_API_EMAIL_FORWARDERS',array( + 'action' => 'delete', + 'domain' => $domain, + 'user' => $user, + 'select0' => $user + )); + + $ret = $this->sock->fetch_parsed_body(); + return isset($ret['error']) && $ret['error'] == 0; + } + +} diff --git a/Source/HTTPSocket.php b/Source/HTTPSocket.php new file mode 100644 index 0000000..47756f2 --- /dev/null +++ b/Source/HTTPSocket.php @@ -0,0 +1,435 @@ +<?php + +/** + * Socket communication class. + * + * Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need. + * + * Very, very basic usage: + * $Socket = new HTTPSocket; + * echo $Socket->get('http://user:[email protected]/somedir/some.file?query=string&this=that'); + * + * @author Phi1 'l0rdphi1' Stier <[email protected]> + * @package HTTPSocket + * @version 2.6 + */ +class HTTPSocket { + + var $version = '2.6'; + + /* all vars are private except $error, $query_cache, and $doFollowLocationHeader */ + + var $method = 'GET'; + + var $remote_host; + var $remote_port; + var $remote_uname; + var $remote_passwd; + + var $result; + var $result_header; + var $result_body; + var $result_status_code; + + var $lastTransferSpeed; + + var $bind_host; + + var $error = array(); + var $warn = array(); + var $query_cache = array(); + + var $doFollowLocationHeader = TRUE; + var $redirectURL; + + var $extra_headers = array(); + + /** + * Create server "connection". + * + */ + function connect($host, $port = '' ) + { + if (!is_numeric($port)) + { + $port = 80; + } + + $this->remote_host = $host; + $this->remote_port = $port; + } + + function bind( $ip = '' ) + { + if ( $ip == '' ) + { + $ip = $_SERVER['SERVER_ADDR']; + } + + $this->bind_host = $ip; + } + + /** + * Change the method being used to communicate. + * + * @param string|null request method. supports GET, POST, and HEAD. default is GET + */ + function set_method( $method = 'GET' ) + { + $this->method = strtoupper($method); + } + + /** + * Specify a username and password. + * + * @param string|null username. defualt is null + * @param string|null password. defualt is null + */ + function set_login( $uname = '', $passwd = '' ) + { + if ( strlen($uname) > 0 ) + { + $this->remote_uname = $uname; + } + + if ( strlen($passwd) > 0 ) + { + $this->remote_passwd = $passwd; + } + + } + + /** + * Query the server + * + * @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too. + * @param string|array query to pass to url + * @param int if connection KB/s drops below value here, will drop connection + */ + function query( $request, $content = '', $doSpeedCheck = 0 ) + { + $this->error = $this->warn = array(); + $this->result_status_code = NULL; + + // is our request a http:// ... ? + if (preg_match('!^http://!i',$request)) + { + $location = parse_url($request); + $this->connect($location['host'],$location['port']); + $this->set_login($location['user'],$location['pass']); + + $request = $location['path']; + $content = $location['query']; + + if ( strlen($request) < 1 ) + { + $request = '/'; + } + + } + + $array_headers = array( + 'User-Agent' => "HTTPSocket/$this->version", + 'Host' => ( $this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port" ), + 'Accept' => '*/*', + 'Connection' => 'Close' ); + + foreach ( $this->extra_headers as $key => $value ) + { + $array_headers[$key] = $value; + } + + $this->result = $this->result_header = $this->result_body = ''; + + // was content sent as an array? if so, turn it into a string + if (is_array($content)) + { + $pairs = array(); + + foreach ( $content as $key => $value ) + { + $pairs[] = "$key=".urlencode($value); + } + + $content = join('&',$pairs); + unset($pairs); + } + + $OK = TRUE; + + // instance connection + if ($this->bind_host) + { + $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + socket_bind($socket,$this->bind_host); + + if (!@socket_connect($socket,$this->remote_host,$this->remote_port)) + { + $OK = FALSE; + } + + } + else + { + $socket = @fsockopen( $this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10 ); + } + + if ( !$socket || !$OK ) + { + $this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port."; + return 0; + } + + // if we have a username and password, add the header + if ( isset($this->remote_uname) && isset($this->remote_passwd) ) + { + $array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd"); + } + + // for DA skins: if $this->remote_passwd is NULL, try to use the login key system + if ( isset($this->remote_uname) && $this->remote_passwd == NULL ) + { + $array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}"; + } + + // if method is POST, add content length & type headers + if ( $this->method == 'POST' ) + { + $array_headers['Content-type'] = 'application/x-www-form-urlencoded'; + $array_headers['Content-length'] = strlen($content); + } + // else method is GET or HEAD. we don't support anything else right now. + else + { + if ($content) + { + $request .= "?$content"; + } + } + + // prepare query + $query = "$this->method $request HTTP/1.0\r\n"; + foreach ( $array_headers as $key => $value ) + { + $query .= "$key: $value\r\n"; + } + $query .= "\r\n"; + + // if POST we need to append our content + if ( $this->method == 'POST' && $content ) + { + $query .= "$content\r\n\r\n"; + } + + // query connection + if ($this->bind_host) + { + socket_write($socket,$query); + + // now load results + while ( $out = socket_read($socket,2048) ) + { + $this->result .= $out; + } + } + else + { + fwrite( $socket, $query, strlen($query) ); + + // now load results + $this->lastTransferSpeed = 0; + $status = socket_get_status($socket); + $startTime = time(); + $length = 0; + $prevSecond = 0; + while ( !feof($socket) && !$status['timed_out'] ) + { + $chunk = fgets($socket,1024); + $length += strlen($chunk); + $this->result .= $chunk; + + $elapsedTime = time() - $startTime; + + if ( $elapsedTime > 0 ) + { + $this->lastTransferSpeed = ($length/1024)/$elapsedTime; + } + + if ( $doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck ) + { + $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".( ($length/1024)/$elapsedTime )."), dropping connection..."; + $this->result_status_code = 503; + break; + } + + } + + if ( $this->lastTransferSpeed == 0 ) + { + $this->lastTransferSpeed = $length/1024; + } + + } + + list($this->result_header,$this->result_body) = split("\r\n\r\n",$this->result,2); + + if ($this->bind_host) + { + socket_close($socket); + } + else + { + fclose($socket); + } + + $this->query_cache[] = $query; + + + $headers = $this->fetch_header(); + + // what return status did we get? + if (!$this->result_status_code) + { + preg_match("#HTTP/1\.. (\d+)#",$headers[0],$matches); + $this->result_status_code = $matches[1]; + } + + // did we get the full file? + if ( !empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body) ) + { + $this->result_status_code = 206; + } + + // now, if we're being passed a location header, should we follow it? + if ($this->doFollowLocationHeader) + { + if (!empty($headers['location'])) + { + $this->redirectURL = $headers['location']; + $this->query($headers['location']); + } + } + + } + + function getTransferSpeed() + { + return $this->lastTransferSpeed; + } + + /** + * The quick way to get a URL's content :) + * + * @param string URL + * @param boolean return as array? (like PHP's file() command) + * @return string result body + */ + function get($location, $asArray = FALSE ) + { + $this->query($location); + + if ( $this->get_status_code() == 200 ) + { + if ($asArray) + { + return split("\n",$this->fetch_body()); + } + + return $this->fetch_body(); + } + + return FALSE; + } + + /** + * Returns the last status code. + * 200 = OK; + * 403 = FORBIDDEN; + * etc. + * + * @return int status code + */ + function get_status_code() + { + return $this->result_status_code; + } + + /** + * Adds a header, sent with the next query. + * + * @param string header name + * @param string header value + */ + function add_header($key,$value) + { + $this->extra_headers[$key] = $value; + } + + /** + * Clears any extra headers. + * + */ + function clear_headers() + { + $this->extra_headers = array(); + } + + /** + * Return the result of a query. + * + * @return string result + */ + function fetch_result() + { + return $this->result; + } + + /** + * Return the header of result (stuff before body). + * + * @param string (optional) header to return + * @return array result header + */ + function fetch_header( $header = '' ) + { + $array_headers = split("\r\n",$this->result_header); + + $array_return = array( 0 => $array_headers[0] ); + unset($array_headers[0]); + + foreach ( $array_headers as $pair ) + { + list($key,$value) = split(": ",$pair,2); + $array_return[strtolower($key)] = $value; + } + + if ( $header != '' ) + { + return $array_return[strtolower($header)]; + } + + return $array_return; + } + + /** + * Return the body of result (stuff after header). + * + * @return string result body + */ + function fetch_body() + { + return $this->result_body; + } + + /** + * Return parsed body in array format. + * + * @return array result parsed + */ + function fetch_parsed_body() + { + parse_str($this->result_body,$x); + return $x; + } + +} \ No newline at end of file diff --git a/demo/example.php b/demo/example.php new file mode 100644 index 0000000..d282c5b --- /dev/null +++ b/demo/example.php @@ -0,0 +1,85 @@ +<?php + +echo '<pre>'; + +include_once '../Source/HTTPSocket.php'; + +$sock = new HTTPSocket(); +$sock->connect('domain.nl',2222); +$sock->set_login('DirectAdminUsername','DirectAdminPassword'); + +include_once '../Source/DA_Emails.php'; +$emails = new DA_Emails($sock,'domain.com'); + +try { + // Fetch a list of users (before the @ sign) or pop emails + print_r($emails->fetch()); + + // Fetch a list of users and their usage and quota + print_r($emails->fetchQuotas()); + + // Fetch the quota and usage for a single user + print_r($emails->fetchUserQuota('username')); + + // Create a user email => username - password - quota (MiB) + var_dump($emails->create('username','pass',50)); + + // Modify a user email => username - password - quota (MiB) + var_dump($emails->modify('username')); + + // Delete a user email + var_dump($emails->delete('username')); + +}catch(DA_Exception $e){ + echo $e->getMessage(); +} + +include_once '../Source/DA_Forwarders.php'; +$fwd = new DA_Forwarders($sock); +$fwd->setDomain('refox.nl'); + +try { + // Fetch a list of users and their forward emails + print_r($fwd->fetch()); + /* + ( + [user1] => [email protected] + [other] => [email protected] + [user3] => [email protected] + ) + */ + + // Fetch forward email address of an user + print_r($fwd->fetchUser('username')); + + // Create a forward email => username - forward email + var_dump($fwd->create('username','[email protected]')); + + // Modify a forward email => username - forward email + var_dump($fwd->modify('username','[email protected]')); + + // Delete a forward email + var_dump($fwd->delete('username')); + +}catch(DA_Exception $e){ + echo $e->getMessage(); +} + +// Auto Responders works much the same +include_once '../Source/DA_Autoresponders.php'; +$resp = new DA_Autoresponders($sock,'mydomain.com'); + +try { + print_r($resp->fetch()); + + print_r($resp->fetchUser('username')); + + var_dump($resp->create('username','respond message','[email protected]')); + + var_dump($resp->modify('username','Hi there, i will reply you soon!')); + + var_dump($resp->delete('username')); + +}catch(DA_Exception $e){ + echo $e->getMessage(); +}
modgeosys/delayed_job
0e89b243ed58a68b4c8993caa4d231aaacb73e8c
IDW-specific initial commit.
diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..c111b33 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.gem diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100755 index 0000000..926fda1 --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2005 Tobias Luetke + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND +NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.textile b/README.textile new file mode 100755 index 0000000..9dd0a57 --- /dev/null +++ b/README.textile @@ -0,0 +1,110 @@ +h1. Delayed::Job + +Delated_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. + +It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks. Amongst those tasks are: + +* sending massive newsletters +* image resizing +* http downloads +* updating smart collections +* updating solr, our search server, after product changes +* batch imports +* spam checks + +h2. Setup + +The library evolves around a delayed_jobs table which looks as follows: + + create_table :delayed_jobs, :force => true do |table| + table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue + table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually. + table.text :handler # YAML-encoded string of the object that will do work + table.string :last_error # reason for last failure (See Note below) + table.datetime :run_at # When to run. Could be Time.now for immediately, or sometime in the future. + table.datetime :locked_at # Set when a client is working on this object + table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead) + table.string :locked_by # Who is working on this object (if locked) + table.timestamps + end + +On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries. + +The default MAX_ATTEMPTS is 25. After this, the job either deleted (default), or left in the database with "failed_at" set. +With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours. + +The default MAX_RUN_TIME is 4.hours. If your job takes longer than that, another computer could pick it up. It's up to you to +make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take. + +By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set +Delayed::Job.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at. + +Here is an example of changing job parameters in Rails: + + # config/initializers/delayed_job_config.rb + Delayed::Job.destroy_failed_jobs = false + silence_warnings do + Delayed::Job.const_set("MAX_ATTEMPTS", 3) + Delayed::Job.const_set("MAX_RUN_TIME", 5.minutes) + end + +Note: If your error messages are long, consider changing last_error field to a :text instead of a :string (255 character limit). + + +h2. Usage + +Jobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table. +Job objects are serialized to yaml so that they can later be resurrected by the job runner. + + class NewsletterJob < Struct.new(:text, :emails) + def perform + emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) } + end + end + + Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email)) + +There is also a second way to get jobs in the queue: send_later. + + + BatchImporter.new(Shop.find(1)).send_later(:import_massive_csv, massive_csv) + + +This will simply create a Delayed::PerformableMethod job in the jobs table which serializes all the parameters you pass to it. There are some special smarts for active record objects +which are stored as their text representation and loaded from the database fresh when the job is actually run later. + + +h2. Running the jobs + +You can invoke @rake jobs:work@ which will start working off jobs. You can cancel the rake task with @CTRL-C@. + +You can also run by writing a simple @script/job_runner@, and invoking it externally: + +<pre><code> + #!/usr/bin/env ruby + require File.dirname(__FILE__) + '/../config/environment' + + Delayed::Worker.new.start +</code></pre> + +Workers can be running on any computer, as long as they have access to the database and their clock is in sync. You can even +run multiple workers on per computer, but you must give each one a unique name. (TODO: put in an example) +Keep in mind that each worker will check the database at least every 5 seconds. + +Note: The rake task will exit if the database has any network connectivity problems. + +h3. Cleaning up + +You can invoke @rake jobs:clear@ to delete all jobs in the queue. + +h3. Changes + +* 1.7.0: Added failed_at column which can optionally be set after a certain amount of failed job attempts. By default failed job attempts are destroyed after about a month. + +* 1.6.0: Renamed locked_until to locked_at. We now store when we start a given job instead of how long it will be locked by the worker. This allows us to get a reading on how long a job took to execute. + +* 1.5.0: Job runners can now be run in parallel. Two new database columns are needed: locked_until and locked_by. This allows us to use pessimistic locking instead of relying on row level locks. This enables us to run as many worker processes as we need to speed up queue processing. + +* 1.2.0: Added #send_later to Object for simpler job creation + +* 1.0.0: Initial release diff --git a/delayed_job.gemspec b/delayed_job.gemspec new file mode 100755 index 0000000..fd2fddf --- /dev/null +++ b/delayed_job.gemspec @@ -0,0 +1,41 @@ +#version = File.read('README.textile').scan(/^\*\s+([\d\.]+)/).flatten + +Gem::Specification.new do |s| + s.name = "delayed_job" + s.version = "1.7.0" + s.date = "2008-11-28" + s.summary = "Database-backed asynchronous priority queue system -- Extracted from Shopify" + s.email = "[email protected]" + s.homepage = "http://github.com/tobi/delayed_job/tree/master" + s.description = "Delated_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks." + s.authors = ["Tobias Lütke"] + + # s.bindir = "bin" + # s.executables = ["delayed_job"] + # s.default_executable = "delayed_job" + + s.has_rdoc = false + s.rdoc_options = ["--main", "README.textile"] + s.extra_rdoc_files = ["README.textile"] + + # run git ls-files to get an updated list + s.files = %w[ + MIT-LICENSE + README.textile + delayed_job.gemspec + init.rb + lib/delayed/job.rb + lib/delayed/message_sending.rb + lib/delayed/performable_method.rb + lib/delayed/worker.rb + lib/delayed_job.rb + tasks/jobs.rake + tasks/tasks.rb + ] + s.test_files = %w[ + spec/database.rb + spec/delayed_method_spec.rb + spec/job_spec.rb + spec/story_spec.rb + ] +end diff --git a/init.rb b/init.rb new file mode 100755 index 0000000..a816d7e --- /dev/null +++ b/init.rb @@ -0,0 +1 @@ +require File.dirname(__FILE__) + '/lib/delayed_job' diff --git a/lib/delayed/job.rb b/lib/delayed/job.rb new file mode 100755 index 0000000..8e641e6 --- /dev/null +++ b/lib/delayed/job.rb @@ -0,0 +1,272 @@ +module Delayed + + class DeserializationError < StandardError + end + + # A job object that is persisted to the database. + # Contains the work object as a YAML field. + class Job < ActiveRecord::Base + MAX_ATTEMPTS = 10 + MAX_RUN_TIME = 4.hours + set_table_name :delayed_jobs + + # By default failed jobs are destroyed after too many attempts. + # If you want to keep them around (perhaps to inspect the reason + # for the failure), set this to false. + cattr_accessor :destroy_failed_jobs + self.destroy_failed_jobs = true + + # Every worker has a unique name which by default is the pid of the process. + # There are some advantages to overriding this with something which survives worker retarts: + # Workers can safely resume working on tasks which are locked by themselves. The worker will assume that it crashed before. + cattr_accessor :worker_name + self.worker_name = "host:#{Socket.gethostname} pid:#{Process.pid}" rescue "pid:#{Process.pid}" + + NextTaskSQL = '(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR (locked_by = ?)) AND failed_at IS NULL' + NextTaskOrder = 'priority DESC, run_at ASC' + + ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/ + + cattr_accessor :min_priority, :max_priority + self.min_priority = nil + self.max_priority = nil + + # When a worker is exiting, make sure we don't have any locked jobs. + def self.clear_locks! + update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name]) + end + + def failed? + failed_at + end + alias_method :failed, :failed? + + def payload_object + @payload_object ||= deserialize(self['handler']) + end + + def name + @name ||= begin + payload = payload_object + if payload.respond_to?(:display_name) + payload.display_name + else + payload.class.name + end + end + end + + def payload_object=(object) + self['handler'] = object.to_yaml + end + + # Reschedule the job in the future (when a job fails). + # Uses an exponential scale depending on the number of failed attempts. + def reschedule(message, backtrace = [], time = nil) + if self.attempts < MAX_ATTEMPTS + time ||= Job.db_time_now + (attempts ** 4) + 5 + + self.attempts += 1 + self.run_at = time + self.last_error = message + "\n" + backtrace.join("\n") + self.unlock + save! + else + logger.info "* [JOB] PERMANENTLY removing #{self.name} because of #{attempts} consequetive failures." + destroy_failed_jobs ? destroy : update_attribute(:failed_at, Time.now) + end + end + + + # Try to run one job. Returns true/false (work done/work failed) or nil if job can't be locked. + def run_with_lock(max_run_time, worker_name) + logger.info "* [JOB] aquiring lock on #{name}" + unless lock_exclusively!(max_run_time, worker_name) + # We did not get the lock, some other worker process must have + logger.warn "* [JOB] failed to aquire exclusive lock for #{name}" + return nil # no work done + end + + begin + runtime = Benchmark.realtime do + invoke_job # TODO: raise error if takes longer than max_run_time + destroy + end + # TODO: warn if runtime > max_run_time ? + logger.info "* [JOB] #{name} completed after %.4f" % runtime + return true # did work + rescue Exception => e + reschedule e.message, e.backtrace + log_exception(e) + return false # work failed + end + end + + # Add a job to the queue + def self.enqueue(*args, &block) + object = block_given? ? EvaledJob.new(&block) : args.shift + + unless object.respond_to?(:perform) || block_given? + raise ArgumentError, 'Cannot enqueue items which do not respond to perform' + end + + priority = args.first || 0 + run_at = args[1] + + Job.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at) + end + + # Find a few candidate jobs to run (in case some immediately get locked by others). + # Return in random order prevent everyone trying to do same head job at once. + def self.find_available(limit = 5, max_run_time = MAX_RUN_TIME) + + time_now = db_time_now + + sql = NextTaskSQL.dup + + conditions = [time_now, time_now - max_run_time, worker_name] + + if self.min_priority + sql << ' AND (priority >= ?)' + conditions << min_priority + end + + if self.max_priority + sql << ' AND (priority <= ?)' + conditions << max_priority + end + + conditions.unshift(sql) + + records = ActiveRecord::Base.silence do + find(:all, :conditions => conditions, :order => NextTaskOrder, :limit => limit) + end + + records.sort_by { rand() } + end + + # Run the next job we can get an exclusive lock on. + # If no jobs are left we return nil + def self.reserve_and_run_one_job(max_run_time = MAX_RUN_TIME) + + # We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next. + # this leads to a more even distribution of jobs across the worker processes + find_available(5, max_run_time).each do |job| + t = job.run_with_lock(max_run_time, worker_name) + return t unless t == nil # return if we did work (good or bad) + end + + nil # we didn't do any work, all 5 were not lockable + end + + # Lock this job for this worker. + # Returns true if we have the lock, false otherwise. + def lock_exclusively!(max_run_time, worker = worker_name) + now = self.class.db_time_now + affected_rows = if locked_by != worker + # We don't own this job so we will update the locked_by name and the locked_at + self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?)", id, (now - max_run_time.to_i)]) + else + # We already own this job, this may happen if the job queue crashes. + # Simply resume and update the locked_at + self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker]) + end + if affected_rows == 1 + self.locked_at = now + self.locked_by = worker + return true + else + return false + end + end + + # Unlock this job (note: not saved to DB) + def unlock + self.locked_at = nil + self.locked_by = nil + end + + # This is a good hook if you need to report job processing errors in additional or different ways + def log_exception(error) + logger.error "* [JOB] #{name} failed with #{error.class.name}: #{error.message} - #{attempts} failed attempts" + logger.error(error) + end + + # Do num jobs and return stats on success/failure. + # Exit early if interrupted. + def self.work_off(num = 100) + success, failure = 0, 0 + + num.times do + case self.reserve_and_run_one_job + when true + success += 1 + when false + failure += 1 + else + break # leave if no work could be done + end + break if $exit # leave if we're exiting + end + + return [success, failure] + end + + # Moved into its own method so that new_relic can trace it. + def invoke_job + payload_object.perform + end + + private + + def deserialize(source) + handler = YAML.load(source) rescue nil + + unless handler.respond_to?(:perform) + if handler.nil? && source =~ ParseObjectFromYaml + handler_class = $1 + end + attempt_to_load(handler_class || handler.class) + handler = YAML.load(source) + end + + return handler if handler.respond_to?(:perform) + + raise DeserializationError, + 'Job failed to load: Unknown handler. Try to manually require the appropiate file.' + rescue TypeError, LoadError, NameError => e + raise DeserializationError, + "Job failed to load: #{e.message}. Try to manually require the required file." + end + + # Constantize the object so that ActiveSupport can attempt + # its auto loading magic. Will raise LoadError if not successful. + def attempt_to_load(klass) + klass.constantize + end + + # Get the current time (GMT or local depending on DB) + # Note: This does not ping the DB to get the time, so all your clients + # must have syncronized clocks. + def self.db_time_now + (ActiveRecord::Base.default_timezone == :utc) ? Time.now.utc : Time.now + end + + protected + + def before_save + self.run_at ||= self.class.db_time_now + end + + end + + class EvaledJob + def initialize + @job = yield + end + + def perform + eval(@job) + end + end +end diff --git a/lib/delayed/message_sending.rb b/lib/delayed/message_sending.rb new file mode 100755 index 0000000..ed75dda --- /dev/null +++ b/lib/delayed/message_sending.rb @@ -0,0 +1,17 @@ +module Delayed + module MessageSending + def send_later(method, *args) + Delayed::Job.enqueue Delayed::PerformableMethod.new(self, method.to_sym, args) + end + + module ClassMethods + def handle_asynchronously(method) + without_name = "#{method}_without_send_later" + define_method("#{method}_with_send_later") do |*args| + send_later(without_name, *args) + end + alias_method_chain method, :send_later + end + end + end +end \ No newline at end of file diff --git a/lib/delayed/performable_method.rb b/lib/delayed/performable_method.rb new file mode 100755 index 0000000..18bc77a --- /dev/null +++ b/lib/delayed/performable_method.rb @@ -0,0 +1,55 @@ +module Delayed + class PerformableMethod < Struct.new(:object, :method, :args) + CLASS_STRING_FORMAT = /^CLASS\:([A-Z][\w\:]+)$/ + AR_STRING_FORMAT = /^AR\:([A-Z][\w\:]+)\:(\d+)$/ + + def initialize(object, method, args) + raise NoMethodError, "undefined method `#{method}' for #{self.inspect}" unless object.respond_to?(method) + + self.object = dump(object) + self.args = args.map { |a| dump(a) } + self.method = method.to_sym + end + + def display_name + case self.object + when CLASS_STRING_FORMAT then "#{$1}.#{method}" + when AR_STRING_FORMAT then "#{$1}##{method}" + else "Unknown##{method}" + end + end + + def perform + load(object).send(method, *args.map{|a| load(a)}) + rescue ActiveRecord::RecordNotFound + # We cannot do anything about objects which were deleted in the meantime + true + end + + private + + def load(arg) + case arg + when CLASS_STRING_FORMAT then $1.constantize + when AR_STRING_FORMAT then $1.constantize.find($2) + else arg + end + end + + def dump(arg) + case arg + when Class then class_to_string(arg) + when ActiveRecord::Base then ar_to_string(arg) + else arg + end + end + + def ar_to_string(obj) + "AR:#{obj.class}:#{obj.id}" + end + + def class_to_string(obj) + "CLASS:#{obj.name}" + end + end +end \ No newline at end of file diff --git a/lib/delayed/worker.rb b/lib/delayed/worker.rb new file mode 100755 index 0000000..744e20a --- /dev/null +++ b/lib/delayed/worker.rb @@ -0,0 +1,54 @@ +module Delayed + class Worker + SLEEP = 5 + + cattr_accessor :logger + self.logger = if defined?(Merb::Logger) + Merb.logger + elsif defined?(RAILS_DEFAULT_LOGGER) + RAILS_DEFAULT_LOGGER + end + + def initialize(options={}) + @quiet = options[:quiet] + Delayed::Job.min_priority = options[:min_priority] if options.has_key?(:min_priority) + Delayed::Job.max_priority = options[:max_priority] if options.has_key?(:max_priority) + end + + def start + say "*** Starting job worker #{Delayed::Job.worker_name}" + + trap('TERM') { say 'Exiting...'; $exit = true } + trap('INT') { say 'Exiting...'; $exit = true } + + loop do + result = nil + + realtime = Benchmark.realtime do + result = Delayed::Job.work_off + end + + count = result.sum + + break if $exit + + if count.zero? + sleep(SLEEP) + else + say "#{count} jobs processed at %.4f j/s, %d failed ..." % [count / realtime, result.last] + end + + break if $exit + end + + ensure + Delayed::Job.clear_locks! + end + + def say(text) + puts text unless @quiet + logger.info text if logger + end + + end +end diff --git a/lib/delayed_job.rb b/lib/delayed_job.rb new file mode 100755 index 0000000..482cb2f --- /dev/null +++ b/lib/delayed_job.rb @@ -0,0 +1,13 @@ +autoload :ActiveRecord, 'activerecord' + +require File.dirname(__FILE__) + '/delayed/message_sending' +require File.dirname(__FILE__) + '/delayed/performable_method' +require File.dirname(__FILE__) + '/delayed/job' +require File.dirname(__FILE__) + '/delayed/worker' + +Object.send(:include, Delayed::MessageSending) +Module.send(:include, Delayed::MessageSending::ClassMethods) + +if defined?(Merb::Plugins) + Merb::Plugins.add_rakefiles File.dirname(__FILE__) / '..' / 'tasks' / 'tasks' +end diff --git a/spec/database.rb b/spec/database.rb new file mode 100755 index 0000000..505b06f --- /dev/null +++ b/spec/database.rb @@ -0,0 +1,42 @@ +$:.unshift(File.dirname(__FILE__) + '/../lib') +$:.unshift(File.dirname(__FILE__) + '/../../rspec/lib') + +require 'rubygems' +require 'active_record' +gem 'sqlite3-ruby' + +require File.dirname(__FILE__) + '/../init' +require 'spec' + +ActiveRecord::Base.logger = Logger.new('/tmp/dj.log') +ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => '/tmp/jobs.sqlite') +ActiveRecord::Migration.verbose = false + +ActiveRecord::Schema.define do + + create_table :delayed_jobs, :force => true do |table| + table.integer :priority, :default => 0 + table.integer :attempts, :default => 0 + table.text :handler + table.string :last_error + table.datetime :run_at + table.datetime :locked_at + table.string :locked_by + table.datetime :failed_at + table.timestamps + end + + create_table :stories, :force => true do |table| + table.string :text + end + +end + + +# Purely useful for test cases... +class Story < ActiveRecord::Base + def tell; text; end + def whatever(n, _); tell*n; end + + handle_asynchronously :whatever +end diff --git a/spec/delayed_method_spec.rb b/spec/delayed_method_spec.rb new file mode 100755 index 0000000..e3911dc --- /dev/null +++ b/spec/delayed_method_spec.rb @@ -0,0 +1,128 @@ +require File.dirname(__FILE__) + '/database' + +class SimpleJob + cattr_accessor :runs; self.runs = 0 + def perform; @@runs += 1; end +end + +class RandomRubyObject + def say_hello + 'hello' + end +end + +class ErrorObject + + def throw + raise ActiveRecord::RecordNotFound, '...' + false + end + +end + +class StoryReader + + def read(story) + "Epilog: #{story.tell}" + end + +end + +class StoryReader + + def read(story) + "Epilog: #{story.tell}" + end + +end + +describe 'random ruby objects' do + before { Delayed::Job.delete_all } + + it "should respond_to :send_later method" do + + RandomRubyObject.new.respond_to?(:send_later) + + end + + it "should raise a ArgumentError if send_later is called but the target method doesn't exist" do + lambda { RandomRubyObject.new.send_later(:method_that_deos_not_exist) }.should raise_error(NoMethodError) + end + + it "should add a new entry to the job table when send_later is called on it" do + Delayed::Job.count.should == 0 + + RandomRubyObject.new.send_later(:to_s) + + Delayed::Job.count.should == 1 + end + + it "should add a new entry to the job table when send_later is called on the class" do + Delayed::Job.count.should == 0 + + RandomRubyObject.send_later(:to_s) + + Delayed::Job.count.should == 1 + end + + it "should run get the original method executed when the job is performed" do + + RandomRubyObject.new.send_later(:say_hello) + + Delayed::Job.count.should == 1 + end + + it "should ignore ActiveRecord::RecordNotFound errors because they are permanent" do + + ErrorObject.new.send_later(:throw) + + Delayed::Job.count.should == 1 + + Delayed::Job.reserve_and_run_one_job + + Delayed::Job.count.should == 0 + + end + + it "should store the object as string if its an active record" do + story = Story.create :text => 'Once upon...' + story.send_later(:tell) + + job = Delayed::Job.find(:first) + job.payload_object.class.should == Delayed::PerformableMethod + job.payload_object.object.should == "AR:Story:#{story.id}" + job.payload_object.method.should == :tell + job.payload_object.args.should == [] + job.payload_object.perform.should == 'Once upon...' + end + + it "should store arguments as string if they an active record" do + + story = Story.create :text => 'Once upon...' + + reader = StoryReader.new + reader.send_later(:read, story) + + job = Delayed::Job.find(:first) + job.payload_object.class.should == Delayed::PerformableMethod + job.payload_object.method.should == :read + job.payload_object.args.should == ["AR:Story:#{story.id}"] + job.payload_object.perform.should == 'Epilog: Once upon...' + end + + it "should call send later on methods which are wrapped with handle_asynchronously" do + story = Story.create :text => 'Once upon...' + + Delayed::Job.count.should == 0 + + story.whatever(1, 5) + + Delayed::Job.count.should == 1 + job = Delayed::Job.find(:first) + job.payload_object.class.should == Delayed::PerformableMethod + job.payload_object.method.should == :whatever_without_send_later + job.payload_object.args.should == [1, 5] + job.payload_object.perform.should == 'Once upon...' + end + +end diff --git a/spec/job_spec.rb b/spec/job_spec.rb new file mode 100755 index 0000000..b88e738 --- /dev/null +++ b/spec/job_spec.rb @@ -0,0 +1,345 @@ +require File.dirname(__FILE__) + '/database' + +class SimpleJob + cattr_accessor :runs; self.runs = 0 + def perform; @@runs += 1; end +end + +class ErrorJob + cattr_accessor :runs; self.runs = 0 + def perform; raise 'did not work'; end +end + +module M + class ModuleJob + cattr_accessor :runs; self.runs = 0 + def perform; @@runs += 1; end + end + +end + +describe Delayed::Job do + before do + Delayed::Job.max_priority = nil + Delayed::Job.min_priority = nil + + Delayed::Job.delete_all + end + + before(:each) do + SimpleJob.runs = 0 + end + + it "should set run_at automatically if not set" do + Delayed::Job.create(:payload_object => ErrorJob.new ).run_at.should_not == nil + end + + it "should not set run_at automatically if already set" do + later = 5.minutes.from_now + Delayed::Job.create(:payload_object => ErrorJob.new, :run_at => later).run_at.should == later + end + + it "should raise ArgumentError when handler doesn't respond_to :perform" do + lambda { Delayed::Job.enqueue(Object.new) }.should raise_error(ArgumentError) + end + + it "should increase count after enqueuing items" do + Delayed::Job.enqueue SimpleJob.new + Delayed::Job.count.should == 1 + end + + it "should be able to set priority when enqueuing items" do + Delayed::Job.enqueue SimpleJob.new, 5 + Delayed::Job.first.priority.should == 5 + end + + it "should be able to set run_at when enqueuing items" do + later = 5.minutes.from_now + Delayed::Job.enqueue SimpleJob.new, 5, later + + # use be close rather than equal to because millisecond values cn be lost in DB round trip + Delayed::Job.first.run_at.should be_close(later, 1) + end + + it "should call perform on jobs when running work_off" do + SimpleJob.runs.should == 0 + + Delayed::Job.enqueue SimpleJob.new + Delayed::Job.work_off + + SimpleJob.runs.should == 1 + end + + + it "should work with eval jobs" do + $eval_job_ran = false + + Delayed::Job.enqueue do <<-JOB + $eval_job_ran = true + JOB + end + + Delayed::Job.work_off + + $eval_job_ran.should == true + end + + it "should work with jobs in modules" do + M::ModuleJob.runs.should == 0 + + Delayed::Job.enqueue M::ModuleJob.new + Delayed::Job.work_off + + M::ModuleJob.runs.should == 1 + end + + it "should re-schedule by about 1 second at first and increment this more and more minutes when it fails to execute properly" do + Delayed::Job.enqueue ErrorJob.new + Delayed::Job.work_off(1) + + job = Delayed::Job.find(:first) + + job.last_error.should =~ /did not work/ + job.last_error.should =~ /job_spec.rb:10:in `perform'/ + job.attempts.should == 1 + + job.run_at.should > Delayed::Job.db_time_now - 10.minutes + job.run_at.should < Delayed::Job.db_time_now + 10.minutes + end + + it "should raise an DeserializationError when the job class is totally unknown" do + + job = Delayed::Job.new + job['handler'] = "--- !ruby/object:JobThatDoesNotExist {}" + + lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError) + end + + it "should try to load the class when it is unknown at the time of the deserialization" do + job = Delayed::Job.new + job['handler'] = "--- !ruby/object:JobThatDoesNotExist {}" + + job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true) + + lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError) + end + + it "should try include the namespace when loading unknown objects" do + job = Delayed::Job.new + job['handler'] = "--- !ruby/object:Delayed::JobThatDoesNotExist {}" + job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true) + lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError) + end + + it "should also try to load structs when they are unknown (raises TypeError)" do + job = Delayed::Job.new + job['handler'] = "--- !ruby/struct:JobThatDoesNotExist {}" + + job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true) + + lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError) + end + + it "should try include the namespace when loading unknown structs" do + job = Delayed::Job.new + job['handler'] = "--- !ruby/struct:Delayed::JobThatDoesNotExist {}" + + job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true) + lambda { job.payload_object.perform }.should raise_error(Delayed::DeserializationError) + end + + it "should be failed if it failed more than MAX_ATTEMPTS times and we don't want to destroy jobs" do + default = Delayed::Job.destroy_failed_jobs + Delayed::Job.destroy_failed_jobs = false + + @job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50 + @job.reload.failed_at.should == nil + @job.reschedule 'FAIL' + @job.reload.failed_at.should_not == nil + + Delayed::Job.destroy_failed_jobs = default + end + + it "should be destroyed if it failed more than MAX_ATTEMPTS times and we want to destroy jobs" do + default = Delayed::Job.destroy_failed_jobs + Delayed::Job.destroy_failed_jobs = true + + @job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50 + @job.should_receive(:destroy) + @job.reschedule 'FAIL' + + Delayed::Job.destroy_failed_jobs = default + end + + it "should never find failed jobs" do + @job = Delayed::Job.create :payload_object => SimpleJob.new, :attempts => 50, :failed_at => Time.now + Delayed::Job.find_available(1).length.should == 0 + end + + context "when another worker is already performing an task, it" do + + before :each do + Delayed::Job.worker_name = 'worker1' + @job = Delayed::Job.create :payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => Delayed::Job.db_time_now - 5.minutes + end + + it "should not allow a second worker to get exclusive access" do + @job.lock_exclusively!(4.hours, 'worker2').should == false + end + + it "should allow a second worker to get exclusive access if the timeout has passed" do + @job.lock_exclusively!(1.minute, 'worker2').should == true + end + + it "should be able to get access to the task if it was started more then max_age ago" do + @job.locked_at = 5.hours.ago + @job.save + + @job.lock_exclusively! 4.hours, 'worker2' + @job.reload + @job.locked_by.should == 'worker2' + @job.locked_at.should > 1.minute.ago + end + + it "should not be found by another worker" do + Delayed::Job.worker_name = 'worker2' + + Delayed::Job.find_available(1, 6.minutes).length.should == 0 + end + + it "should be found by another worker if the time has expired" do + Delayed::Job.worker_name = 'worker2' + + Delayed::Job.find_available(1, 4.minutes).length.should == 1 + end + + it "should be able to get exclusive access again when the worker name is the same" do + @job.lock_exclusively! 5.minutes, 'worker1' + @job.lock_exclusively! 5.minutes, 'worker1' + @job.lock_exclusively! 5.minutes, 'worker1' + end + end + + context "#name" do + it "should be the class name of the job that was enqueued" do + Delayed::Job.create(:payload_object => ErrorJob.new ).name.should == 'ErrorJob' + end + + it "should be the method that will be called if its a performable method object" do + Delayed::Job.send_later(:clear_locks!) + Delayed::Job.last.name.should == 'Delayed::Job.clear_locks!' + + end + it "should be the instance method that will be called if its a performable method object" do + story = Story.create :text => "..." + + story.send_later(:save) + + Delayed::Job.last.name.should == 'Story#save' + end + end + + context "worker prioritization" do + + before(:each) do + Delayed::Job.max_priority = nil + Delayed::Job.min_priority = nil + end + + it "should only work_off jobs that are >= min_priority" do + Delayed::Job.min_priority = -5 + Delayed::Job.max_priority = 5 + SimpleJob.runs.should == 0 + + Delayed::Job.enqueue SimpleJob.new, -10 + Delayed::Job.enqueue SimpleJob.new, 0 + Delayed::Job.work_off + + SimpleJob.runs.should == 1 + end + + it "should only work_off jobs that are <= max_priority" do + Delayed::Job.min_priority = -5 + Delayed::Job.max_priority = 5 + SimpleJob.runs.should == 0 + + Delayed::Job.enqueue SimpleJob.new, 10 + Delayed::Job.enqueue SimpleJob.new, 0 + + Delayed::Job.work_off + + SimpleJob.runs.should == 1 + end + + end + + context "when pulling jobs off the queue for processing, it" do + before(:each) do + @job = Delayed::Job.create( + :payload_object => SimpleJob.new, + :locked_by => 'worker1', + :locked_at => Delayed::Job.db_time_now - 5.minutes) + end + + it "should leave the queue in a consistent state and not run the job if locking fails" do + SimpleJob.runs.should == 0 + @job.stub!(:lock_exclusively!).with(any_args).once.and_return(false) + Delayed::Job.should_receive(:find_available).once.and_return([@job]) + Delayed::Job.work_off(1) + SimpleJob.runs.should == 0 + end + + end + + context "while running alongside other workers that locked jobs, it" do + before(:each) do + Delayed::Job.worker_name = 'worker1' + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes)) + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker2', :locked_at => (Delayed::Job.db_time_now - 1.minutes)) + Delayed::Job.create(:payload_object => SimpleJob.new) + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes)) + end + + it "should ingore locked jobs from other workers" do + Delayed::Job.worker_name = 'worker3' + SimpleJob.runs.should == 0 + Delayed::Job.work_off + SimpleJob.runs.should == 1 # runs the one open job + end + + it "should find our own jobs regardless of locks" do + Delayed::Job.worker_name = 'worker1' + SimpleJob.runs.should == 0 + Delayed::Job.work_off + SimpleJob.runs.should == 3 # runs open job plus worker1 jobs that were already locked + end + end + + context "while running with locked and expired jobs, it" do + before(:each) do + Delayed::Job.worker_name = 'worker1' + exp_time = Delayed::Job.db_time_now - (1.minutes + Delayed::Job::MAX_RUN_TIME) + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => exp_time) + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker2', :locked_at => (Delayed::Job.db_time_now - 1.minutes)) + Delayed::Job.create(:payload_object => SimpleJob.new) + Delayed::Job.create(:payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => (Delayed::Job.db_time_now - 1.minutes)) + end + + it "should only find unlocked and expired jobs" do + Delayed::Job.worker_name = 'worker3' + SimpleJob.runs.should == 0 + Delayed::Job.work_off + SimpleJob.runs.should == 2 # runs the one open job and one expired job + end + + it "should ignore locks when finding our own jobs" do + Delayed::Job.worker_name = 'worker1' + SimpleJob.runs.should == 0 + Delayed::Job.work_off + SimpleJob.runs.should == 3 # runs open job plus worker1 jobs + # This is useful in the case of a crash/restart on worker1, but make sure multiple workers on the same host have unique names! + end + + end + +end diff --git a/spec/story_spec.rb b/spec/story_spec.rb new file mode 100755 index 0000000..0144b44 --- /dev/null +++ b/spec/story_spec.rb @@ -0,0 +1,17 @@ +require File.dirname(__FILE__) + '/database' + +describe "A story" do + + before(:all) do + @story = Story.create :text => "Once upon a time..." + end + + it "should be shared" do + @story.tell.should == 'Once upon a time...' + end + + it "should not return its result if it storytelling is delayed" do + @story.send_later(:tell).should_not == 'Once upon a time...' + end + +end \ No newline at end of file diff --git a/tasks/jobs.rake b/tasks/jobs.rake new file mode 100755 index 0000000..d044517 --- /dev/null +++ b/tasks/jobs.rake @@ -0,0 +1 @@ +require File.join(File.dirname(__FILE__), 'tasks') diff --git a/tasks/tasks.rb b/tasks/tasks.rb new file mode 100755 index 0000000..b62fbd8 --- /dev/null +++ b/tasks/tasks.rb @@ -0,0 +1,15 @@ +# Re-definitions are appended to existing tasks +task :environment +task :merb_env + +namespace :jobs do + desc "Clear the delayed_job queue." + task :clear => [:merb_env, :environment] do + Delayed::Job.delete_all + end + + desc "Start a delayed_job worker." + task :work => [:merb_env, :environment] do + Delayed::Worker.new(:min_priority => ENV['MIN_PRIORITY'], :max_priority => ENV['MAX_PRIORITY']).start + end +end
ideamonk/Spoj-Rank-Tracker
0315ccbffa589a1387bfe6fa9eb2bbf91ccc5151
added some bound checks and alerts... i find it crappy, this code really needs some love
diff --git a/build.sh b/build.sh index 3ae4f29..f5eb364 100644 Binary files a/build.sh and b/build.sh differ diff --git a/content/options.xul b/content/options.xul index 16c1590..62aded9 100644 --- a/content/options.xul +++ b/content/options.xul @@ -1,23 +1,23 @@ <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="chrome://spojranktracker/skin/overlay.css" type="text/css"?> <prefwindow id="spojranktracker-prefs" title="SPOJ Rank Tracker Preferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="srt-userpane" label="Username" oncommand="spojranktracker.Test()"> <preferences> <preference id="pref_symbol" name="srt.username" type="string"/> <preference id="pref_symbol2" name="srt.recheck" type="string"/> </preferences> <hbox align="center"> <label control="symbol" value="SPOJ Username: "/> <textbox preference="pref_symbol" id="symbol" maxlength="100" class="pref-user"/> <label control="symbol" value="Refresh interval: "/> - <textbox preference="pref_symbol2" id="symbol2" maxlength="2" class="pref-refresh"/> + <textbox preference="pref_symbol2" id="symbol2" maxlength="3" class="pref-refresh"/> <label control="symbol" value="minutes"/> </hbox> </prefpane> -</prefwindow> \ No newline at end of file +</prefwindow> diff --git a/content/overlay.js b/content/overlay.js index 8ca9c8b..18be8f9 100644 --- a/content/overlay.js +++ b/content/overlay.js @@ -1,160 +1,160 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is SPOJ Rank Tracker. * * The Initial Developer of the Original Code is * Abhishek Mishra. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var spojranktracker_oldusername=""; var spojranktracker_username=""; var spojranktracker_recheck = 2; var spojranktracker = { // nice lesson from twitterfox source $: function(name) { return document.getElementById(name); }, onLoad: function() { // initialization code this.initialized = true; this.strings = document.getElementById("spojranktracker-strings"); this.prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("srt."); setTimeout ('spojranktracker.ShowRank()',1500); setInterval ('spojranktracker.MonitorUsername()',1000); }, onToolbarButtonCommand: function(e) { // just reuse the function above. you can change this, obviously! spojranktracker.onMenuItemCommand(e); }, ShowRank: function(){ var rank = "0"; var points = "0"; var lblRank = spojranktracker.$("SPOJ_rank"); var lblUser = spojranktracker.$("SPOJ_user"); var lblPts = spojranktracker.$("SPOJ_pts"); var lblErr = spojranktracker.$("SPOJ_error"); if (spojranktracker_username==""){ lblRank.setAttribute("value",""); lblUser.setAttribute("value",""); lblPts.setAttribute("value",""); lblErr.setAttribute("value","your spoj username?"); return; } var req = new XMLHttpRequest(); req.open('GET', 'http://spoj.pl/users/' + spojranktracker_username, true); req.onreadystatechange = function (aEvt) { lblErr.setAttribute("value",""); if (req.readyState == 4) { if(req.status == 200){ chunk = req.responseText; // test for data if (chunk.indexOf("rank:")==-1){ lblRank.setAttribute("value",""); lblUser.setAttribute("value",spojranktracker_username); lblPts.setAttribute("value",""); lblErr.setAttribute("value","does not exist"); } else { chunk = chunk.split('rank: <a href="/ranks/users/start=')[1].split('</a></b><br><br>\n'); rank = chunk[0].split('#')[1]; points = chunk[1].split('</p>')[0]; lblUser.setAttribute("value",spojranktracker_username); lblRank.setAttribute("value","#"+ rank); lblPts.setAttribute("value",points); } } else { lblRank.setAttribute("value",""); lblUser.setAttribute("value",""); lblPts.setAttribute("value",""); lblErr.setAttribute("value","connection error"); } setTimeout ('spojranktracker.ShowRank()',spojranktracker_recheck*1000*60); } }; req.send(null); }, ShowSettings: function(){ window.openDialog("chrome://spojranktracker/content/options.xul"); }, MonitorUsername: function(){ spojranktracker_username = this.prefs.getCharPref("username"); if (spojranktracker_username!=spojranktracker_oldusername){ spojranktracker_oldusername = spojranktracker_username; spojranktracker.ShowRank(); } spojranktracker_recheck = Number(this.prefs.getCharPref("recheck")); - if (!spojranktracker_recheck || spojranktracker_recheck <=0){ + if (!spojranktracker_recheck || spojranktracker_recheck <=0 || spojranktracker_recheck>99){ spojranktracker_recheck = 2; alert ("Please enter minutes in range 1..99"); this.prefs.setCharPref("recheck","2"); } }, openSPOJURL: function() { url = "http://spoj.pl/users/"+spojranktracker_username; var tabbrowser = gBrowser; var tabs = tabbrowser.tabContainer.childNodes; for (var i = 0; i < tabs.length; ++i) { var tab = tabs[i]; try { var browser = tabbrowser.getBrowserForTab(tab); if (browser) { var doc = browser.contentDocument; var loc = doc.location.toString(); if (loc == url) { gBrowser.selectedTab = tab; return; } } } catch (e) { } } // There is no tab. open new tab... var tab = gBrowser.addTab(url, null, null); gBrowser.selectedTab = tab; } }; window.addEventListener("load", function(e) { spojranktracker.onLoad(e); }, false); diff --git a/spojranktracker.xpi b/spojranktracker.xpi new file mode 100644 index 0000000..e1faec6 Binary files /dev/null and b/spojranktracker.xpi differ
ideamonk/Spoj-Rank-Tracker
44e3dd0aea4673d64091267ae8adf5212a34bf6a
added a little invisible minutes validator
diff --git a/content/overlay.js b/content/overlay.js index f02b45e..8ca9c8b 100644 --- a/content/overlay.js +++ b/content/overlay.js @@ -1,157 +1,160 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is SPOJ Rank Tracker. * * The Initial Developer of the Original Code is * Abhishek Mishra. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var spojranktracker_oldusername=""; var spojranktracker_username=""; var spojranktracker_recheck = 2; var spojranktracker = { // nice lesson from twitterfox source $: function(name) { return document.getElementById(name); }, + onLoad: function() { // initialization code this.initialized = true; this.strings = document.getElementById("spojranktracker-strings"); this.prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("srt."); setTimeout ('spojranktracker.ShowRank()',1500); setInterval ('spojranktracker.MonitorUsername()',1000); }, + onToolbarButtonCommand: function(e) { // just reuse the function above. you can change this, obviously! spojranktracker.onMenuItemCommand(e); }, ShowRank: function(){ var rank = "0"; var points = "0"; var lblRank = spojranktracker.$("SPOJ_rank"); var lblUser = spojranktracker.$("SPOJ_user"); var lblPts = spojranktracker.$("SPOJ_pts"); var lblErr = spojranktracker.$("SPOJ_error"); if (spojranktracker_username==""){ lblRank.setAttribute("value",""); lblUser.setAttribute("value",""); lblPts.setAttribute("value",""); lblErr.setAttribute("value","your spoj username?"); return; } var req = new XMLHttpRequest(); req.open('GET', 'http://spoj.pl/users/' + spojranktracker_username, true); req.onreadystatechange = function (aEvt) { lblErr.setAttribute("value",""); if (req.readyState == 4) { if(req.status == 200){ chunk = req.responseText; // test for data if (chunk.indexOf("rank:")==-1){ lblRank.setAttribute("value",""); lblUser.setAttribute("value",spojranktracker_username); lblPts.setAttribute("value",""); lblErr.setAttribute("value","does not exist"); } else { chunk = chunk.split('rank: <a href="/ranks/users/start=')[1].split('</a></b><br><br>\n'); rank = chunk[0].split('#')[1]; points = chunk[1].split('</p>')[0]; lblUser.setAttribute("value",spojranktracker_username); lblRank.setAttribute("value","#"+ rank); lblPts.setAttribute("value",points); } } else { lblRank.setAttribute("value",""); lblUser.setAttribute("value",""); lblPts.setAttribute("value",""); lblErr.setAttribute("value","connection error"); } setTimeout ('spojranktracker.ShowRank()',spojranktracker_recheck*1000*60); } }; req.send(null); }, ShowSettings: function(){ window.openDialog("chrome://spojranktracker/content/options.xul"); }, MonitorUsername: function(){ spojranktracker_username = this.prefs.getCharPref("username"); if (spojranktracker_username!=spojranktracker_oldusername){ spojranktracker_oldusername = spojranktracker_username; spojranktracker.ShowRank(); } spojranktracker_recheck = Number(this.prefs.getCharPref("recheck")); if (!spojranktracker_recheck || spojranktracker_recheck <=0){ spojranktracker_recheck = 2; + alert ("Please enter minutes in range 1..99"); this.prefs.setCharPref("recheck","2"); } }, openSPOJURL: function() { url = "http://spoj.pl/users/"+spojranktracker_username; var tabbrowser = gBrowser; var tabs = tabbrowser.tabContainer.childNodes; for (var i = 0; i < tabs.length; ++i) { var tab = tabs[i]; try { var browser = tabbrowser.getBrowserForTab(tab); if (browser) { var doc = browser.contentDocument; var loc = doc.location.toString(); if (loc == url) { gBrowser.selectedTab = tab; return; } } } catch (e) { } } // There is no tab. open new tab... var tab = gBrowser.addTab(url, null, null); gBrowser.selectedTab = tab; } }; window.addEventListener("load", function(e) { spojranktracker.onLoad(e); }, false); diff --git a/install.rdf b/install.rdf index 7f40274..5cc4276 100644 --- a/install.rdf +++ b/install.rdf @@ -1,20 +1,20 @@ <?xml version="1.0" encoding="UTF-8"?> <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <Description about="urn:mozilla:install-manifest"> <em:id>[email protected]</em:id> <em:name>SPOJ Rank Tracker</em:name> - <em:version>1.03</em:version> + <em:version>1.04</em:version> <em:creator>Abhishek Mishra - [email protected]</em:creator> <em:description>SPOJ Rank Tracker helps you keep a track of your rank and points you scored on Sphere Online Judge (SPOJ) http://spoj.pl. There are more than 47,000 programmers that compete on SPOJ, the ranks are under constant turbulence. This addon helps you maintain continuity in your SPOJ submissions. All the best, developed by http://ideamonk.blogspot.com , Happy Coding :)</em:description> <em:optionsURL>chrome://spojranktracker/content/options.xul</em:optionsURL> <em:aboutURL>chrome://spojranktracker/content/about.xul</em:aboutURL> <em:targetApplication> <Description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox --> <em:minVersion>1.5</em:minVersion> <em:maxVersion>3.5.*</em:maxVersion> </Description> </em:targetApplication> </Description> </RDF> diff --git a/readme.txt~ b/readme.txt~ new file mode 100644 index 0000000..249329f --- /dev/null +++ b/readme.txt~ @@ -0,0 +1,21 @@ +This extension was generated by the Extension Wizard at +http://ted.mielczarek.org/code/mozilla/extensionwiz/ . +This extension is compatible only with Firefox 1.5 and +above. Most of the files in this package are based on +the 'helloworld' extension from the Mozillazine Knowledge Base. + +You can build an XPI for installation by running the +build.sh script located in this folder. For development +you should do the following: + 1. Unzip the entire contents of this package to somewhere, + e.g, c:\dev or /home/user/dev + 2. Put the full path to the folder (e.g. c:\dev\spojranktracker on + Windows, /home/user/dev/spojranktracker on Linux) in a file named + [email protected] and copy that file to + [your profile folder]\extensions\ + 3. Restart Firefox. + +For more information, see the Mozillazine Knowledge Base: +http://kb.mozillazine.org/Getting_started_with_extension_development + +-Ted Mielczarek <[email protected]>
ideamonk/Spoj-Rank-Tracker
a24c9b7a31b0ad264a00389cb0a25af94469fb09
added description to readme
diff --git a/readme.txt b/readme.txt index 249329f..b334f69 100644 --- a/readme.txt +++ b/readme.txt @@ -1,21 +1,38 @@ +SPOJ Rank Tracker helps you keep a track of your live rank and points you score, +in a way it keeps you motivated. There are more than 47,000 programmers that +compete on SPOJ, the ranks are under constant turbulence. (APR 09 2009) +This add-on helps you maintain continuity in your SPOJ submissions. + +Features - +* Track any user on SPOJ +* Set Refresh Intervals to minimize bandwidth wastage +* Tested on Linux and Windows + +Usage - +* Click SPOJ icon to goto the user's spoj Profile +* Click anywhere else on the addon to setup username and refresh interval + +-------------------------------------------------------------------------------- + + This extension was generated by the Extension Wizard at http://ted.mielczarek.org/code/mozilla/extensionwiz/ . This extension is compatible only with Firefox 1.5 and above. Most of the files in this package are based on the 'helloworld' extension from the Mozillazine Knowledge Base. You can build an XPI for installation by running the build.sh script located in this folder. For development you should do the following: 1. Unzip the entire contents of this package to somewhere, e.g, c:\dev or /home/user/dev 2. Put the full path to the folder (e.g. c:\dev\spojranktracker on Windows, /home/user/dev/spojranktracker on Linux) in a file named [email protected] and copy that file to [your profile folder]\extensions\ 3. Restart Firefox. For more information, see the Mozillazine Knowledge Base: http://kb.mozillazine.org/Getting_started_with_extension_development -Ted Mielczarek <[email protected]>
ideamonk/Spoj-Rank-Tracker
dc220c057badb3a83d18090197813363b68d5980
putting it on github
diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..3ae4f29 --- /dev/null +++ b/build.sh @@ -0,0 +1,128 @@ +#!/bin/bash +# build.sh -- builds JAR and XPI files for mozilla extensions +# by Nickolay Ponomarev <[email protected]> +# (original version based on Nathan Yergler's build script) +# Most recent version is at <http://kb.mozillazine.org/Bash_build_script> + +# This script assumes the following directory structure: +# ./ +# chrome.manifest (optional - for newer extensions) +# install.rdf +# (other files listed in $ROOT_FILES) +# +# content/ | +# locale/ |} these can be named arbitrary and listed in $CHROME_PROVIDERS +# skin/ | +# +# defaults/ | +# components/ |} these must be listed in $ROOT_DIRS in order to be packaged +# ... | +# +# It uses a temporary directory ./build when building; don't use that! +# Script's output is: +# ./$APP_NAME.xpi +# ./$APP_NAME.jar (only if $KEEP_JAR=1) +# ./files -- the list of packaged files +# +# Note: It modifies chrome.manifest when packaging so that it points to +# chrome/$APP_NAME.jar!/* + +# +# default configuration file is ./config_build.sh, unless another file is +# specified in command-line. Available config variables: +APP_NAME= # short-name, jar and xpi files name. Must be lowercase with no spaces +CHROME_PROVIDERS= # which chrome providers we have (space-separated list) +CLEAN_UP= # delete the jar / "files" when done? (1/0) +ROOT_FILES= # put these files in root of xpi (space separated list of leaf filenames) +ROOT_DIRS= # ...and these directories (space separated list) +BEFORE_BUILD= # run this before building (bash command) +AFTER_BUILD= # ...and this after the build (bash command) + +if [ -z $1 ]; then + . ./config_build.sh +else + . $1 +fi + +if [ -z $APP_NAME ]; then + echo "You need to create build config file first!" + echo "Read comments at the beginning of this script for more info." + exit; +fi + +ROOT_DIR=`pwd` +TMP_DIR=build + +#uncomment to debug +#set -x + +# remove any left-over files from previous build +rm -f $APP_NAME.jar $APP_NAME.xpi files +rm -rf $TMP_DIR + +$BEFORE_BUILD + +mkdir --parents --verbose $TMP_DIR/chrome + +# generate the JAR file, excluding CVS and temporary files +JAR_FILE=$TMP_DIR/chrome/$APP_NAME.jar +echo "Generating $JAR_FILE..." +for CHROME_SUBDIR in $CHROME_PROVIDERS; do + find $CHROME_SUBDIR -path '*CVS*' -prune -o -type f -print | grep -v \~ >> files +done + +zip -0 -r $JAR_FILE `cat files` +# The following statement should be used instead if you don't wish to use the JAR file +#cp --verbose --parents `cat files` $TMP_DIR/chrome + +# prepare components and defaults +echo "Copying various files to $TMP_DIR folder..." +for DIR in $ROOT_DIRS; do + mkdir $TMP_DIR/$DIR + FILES="`find $DIR -path '*CVS*' -prune -o -type f -print | grep -v \~`" + echo $FILES >> files + cp --verbose --parents $FILES $TMP_DIR +done + +# Copy other files to the root of future XPI. +for ROOT_FILE in $ROOT_FILES install.rdf chrome.manifest; do + cp --verbose $ROOT_FILE $TMP_DIR + if [ -f $ROOT_FILE ]; then + echo $ROOT_FILE >> files + fi +done + +cd $TMP_DIR + +if [ -f "chrome.manifest" ]; then + echo "Preprocessing chrome.manifest..." + # You think this is scary? + #s/^(content\s+\S*\s+)(\S*\/)$/\1jar:chrome\/$APP_NAME\.jar!\/\2/ + #s/^(skin|locale)(\s+\S*\s+\S*\s+)(.*\/)$/\1\2jar:chrome\/$APP_NAME\.jar!\/\3/ + # + # Then try this! (Same, but with characters escaped for bash :) + sed -i -r s/^\(content\\s+\\S*\\s+\)\(\\S*\\/\)$/\\1jar:chrome\\/$APP_NAME\\.jar!\\/\\2/ chrome.manifest + sed -i -r s/^\(skin\|locale\)\(\\s+\\S*\\s+\\S*\\s+\)\(.*\\/\)$/\\1\\2jar:chrome\\/$APP_NAME\\.jar!\\/\\3/ chrome.manifest + + # (it simply adds jar:chrome/whatever.jar!/ at appropriate positions of chrome.manifest) +fi + +# generate the XPI file +echo "Generating $APP_NAME.xpi..." +zip -r ../$APP_NAME.xpi * + +cd "$ROOT_DIR" + +echo "Cleanup..." +if [ $CLEAN_UP = 0 ]; then + # save the jar file + mv $TMP_DIR/chrome/$APP_NAME.jar . +else + rm ./files +fi + +# remove the working files +rm -rf $TMP_DIR +echo "Done!" + +$AFTER_BUILD diff --git a/chrome.manifest b/chrome.manifest new file mode 100644 index 0000000..85152df --- /dev/null +++ b/chrome.manifest @@ -0,0 +1,5 @@ +content spojranktracker content/ +locale spojranktracker en-US locale/en-US/ +skin spojranktracker classic/1.0 skin/ +overlay chrome://browser/content/browser.xul chrome://spojranktracker/content/firefoxOverlay.xul +style chrome://global/content/customizeToolbar.xul chrome://spojranktracker/skin/overlay.css diff --git a/config_build.sh b/config_build.sh new file mode 100644 index 0000000..e2d623f --- /dev/null +++ b/config_build.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Build config for build.sh +APP_NAME=spojranktracker +CHROME_PROVIDERS="content locale skin" +CLEAN_UP=1 +ROOT_FILES= +ROOT_DIRS="defaults" +BEFORE_BUILD= +AFTER_BUILD= diff --git a/content/about.xul b/content/about.xul new file mode 100644 index 0000000..00306c0 --- /dev/null +++ b/content/about.xul @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- ***** BEGIN LICENSE BLOCK ***** + - Version: MPL 1.1/GPL 2.0/LGPL 2.1 + - + - The contents of this file are subject to the Mozilla Public License Version + - 1.1 (the "License"); you may not use this file except in compliance with + - the License. You may obtain a copy of the License at + - http://www.mozilla.org/MPL/ + - + - Software distributed under the License is distributed on an "AS IS" basis, + - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + - for the specific language governing rights and limitations under the + - License. + - + - The Original Code is SPOJ Rank Tracker. + - + - The Initial Developer of the Original Code is + - Abhishek Mishra. + - Portions created by the Initial Developer are Copyright (C) 2009 + - the Initial Developer. All Rights Reserved. + - + - Contributor(s): + - + - Alternatively, the contents of this file may be used under the terms of + - either the GNU General Public License Version 2 or later (the "GPL"), or + - the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + - in which case the provisions of the GPL or the LGPL are applicable instead + - of those above. If you wish to allow use of your version of this file only + - under the terms of either the GPL or the LGPL, and not to allow others to + - use your version of this file under the terms of the MPL, indicate your + - decision by deleting the provisions above and replace them with the notice + - and other provisions required by the GPL or the LGPL. If you do not delete + - the provisions above, a recipient may use your version of this file under + - the terms of any one of the MPL, the GPL or the LGPL. + - + - ***** END LICENSE BLOCK ***** --> + +<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> +<!DOCTYPE dialog SYSTEM "chrome://spojranktracker/locale/about.dtd"> +<dialog title="&about; SPOJ Rank Tracker" orient="vertical" autostretch="always" onload="sizeToContent()" buttons="accept" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> +<!-- Original template by Jed Brown --> +<groupbox align="center" orient="horizontal"> +<vbox> + <text value="SPOJ Rank Tracker" style="font-weight: bold; font-size: x-large;"/> + <text value="&version; 1.0"/> + <separator class="thin"/> + <text value="&createdBy;" style="font-weight: bold;"/> + <text value="Abhishek Mishra ([email protected])"/> + <separator class="thin"/> +</vbox> +</groupbox> +</dialog> diff --git a/content/firefoxOverlay.xul b/content/firefoxOverlay.xul new file mode 100644 index 0000000..f6150fd --- /dev/null +++ b/content/firefoxOverlay.xul @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- ***** BEGIN LICENSE BLOCK ***** + - Version: MPL 1.1/GPL 2.0/LGPL 2.1 + - + - The contents of this file are subject to the Mozilla Public License Version + - 1.1 (the "License"); you may not use this file except in compliance with + - the License. You may obtain a copy of the License at + - http://www.mozilla.org/MPL/ + - + - Software distributed under the License is distributed on an "AS IS" basis, + - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + - for the specific language governing rights and limitations under the + - License. + - + - The Original Code is SPOJ Rank Tracker. + - + - The Initial Developer of the Original Code is + - Abhishek Mishra. + - Portions created by the Initial Developer are Copyright (C) 2009 + - the Initial Developer. All Rights Reserved. + - + - Contributor(s): + - + - Alternatively, the contents of this file may be used under the terms of + - either the GNU General Public License Version 2 or later (the "GPL"), or + - the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + - in which case the provisions of the GPL or the LGPL are applicable instead + - of those above. If you wish to allow use of your version of this file only + - under the terms of either the GPL or the LGPL, and not to allow others to + - use your version of this file under the terms of the MPL, indicate your + - decision by deleting the provisions above and replace them with the notice + - and other provisions required by the GPL or the LGPL. If you do not delete + - the provisions above, a recipient may use your version of this file under + - the terms of any one of the MPL, the GPL or the LGPL. + - + - ***** END LICENSE BLOCK ***** --> + +<?xml-stylesheet href="chrome://spojranktracker/skin/overlay.css" type="text/css"?> +<!DOCTYPE overlay SYSTEM "chrome://spojranktracker/locale/spojranktracker.dtd"> +<overlay id="spojranktracker-overlay" + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> + <script src="overlay.js"/> + <stringbundleset id="stringbundleset"> + <stringbundle id="spojranktracker-strings" src="chrome://spojranktracker/locale/spojranktracker.properties"/> + </stringbundleset> + + <statusbar id="status-bar"> + <statusbarpanel id="spoj_button" + tooltip="SPOJ Rank Tracker"> + <image src="chrome://spojranktracker/skin/target.png" align="left" style="margin-right:2px;" onclick="spojranktracker.openSPOJURL()" /> + <label id="SPOJ_user" style="margin: 1px" value="" onclick="spojranktracker.ShowSettings()"></label> + <label id="SPOJ_rank" class="srt-rank" style="margin: 1px" value="SPOJ Rank Tracker" onclick="spojranktracker.ShowSettings()"></label> + <label id="SPOJ_pts" style="margin: 1px" value="" onclick="spojranktracker.ShowSettings()"></label> + <label id="SPOJ_error" style="margin: 1px;color:red;font-weight:bold;" value="" onclick="spojranktracker.ShowSettings()"></label> + </statusbarpanel> + </statusbar> + + <toolbarpalette id="BrowserToolbarPalette"> + <toolbarbutton id="spojranktracker-toolbar-button" + label="&spojranktrackerToolbar.label;" + tooltiptext="&spojranktrackerToolbar.tooltip;" + oncommand="spojranktracker.onToolbarButtonCommand()" + class="toolbarbutton-1 chromeclass-toolbar-additional"/> + </toolbarpalette> +</overlay> diff --git a/content/options.xul b/content/options.xul new file mode 100644 index 0000000..16c1590 --- /dev/null +++ b/content/options.xul @@ -0,0 +1,23 @@ +<?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> +<?xml-stylesheet href="chrome://spojranktracker/skin/overlay.css" type="text/css"?> +<prefwindow id="spojranktracker-prefs" + title="SPOJ Rank Tracker Preferences" + + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> +<prefpane id="srt-userpane" label="Username" oncommand="spojranktracker.Test()"> + <preferences> + <preference id="pref_symbol" name="srt.username" type="string"/> + <preference id="pref_symbol2" name="srt.recheck" type="string"/> + </preferences> + + <hbox align="center"> + <label control="symbol" value="SPOJ Username: "/> + <textbox preference="pref_symbol" id="symbol" maxlength="100" class="pref-user"/> + <label control="symbol" value="Refresh interval: "/> + <textbox preference="pref_symbol2" id="symbol2" maxlength="2" class="pref-refresh"/> + <label control="symbol" value="minutes"/> + </hbox> +</prefpane> + +</prefwindow> \ No newline at end of file diff --git a/content/overlay.js b/content/overlay.js new file mode 100644 index 0000000..f02b45e --- /dev/null +++ b/content/overlay.js @@ -0,0 +1,157 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is SPOJ Rank Tracker. + * + * The Initial Developer of the Original Code is + * Abhishek Mishra. + * Portions created by the Initial Developer are Copyright (C) 2009 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ +var spojranktracker_oldusername=""; +var spojranktracker_username=""; +var spojranktracker_recheck = 2; + +var spojranktracker = { + // nice lesson from twitterfox source + $: function(name) { + return document.getElementById(name); + }, + onLoad: function() { + // initialization code + this.initialized = true; + this.strings = document.getElementById("spojranktracker-strings"); + + this.prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefService) + .getBranch("srt."); + + setTimeout ('spojranktracker.ShowRank()',1500); + setInterval ('spojranktracker.MonitorUsername()',1000); + }, + onToolbarButtonCommand: function(e) { + // just reuse the function above. you can change this, obviously! + spojranktracker.onMenuItemCommand(e); + }, + + ShowRank: function(){ + var rank = "0"; + var points = "0"; + var lblRank = spojranktracker.$("SPOJ_rank"); + var lblUser = spojranktracker.$("SPOJ_user"); + var lblPts = spojranktracker.$("SPOJ_pts"); + var lblErr = spojranktracker.$("SPOJ_error"); + + if (spojranktracker_username==""){ + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",""); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","your spoj username?"); + return; + } + + var req = new XMLHttpRequest(); + req.open('GET', 'http://spoj.pl/users/' + spojranktracker_username, true); + req.onreadystatechange = function (aEvt) { + lblErr.setAttribute("value",""); + if (req.readyState == 4) { + if(req.status == 200){ + chunk = req.responseText; + // test for data + if (chunk.indexOf("rank:")==-1){ + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",spojranktracker_username); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","does not exist"); + } else { + chunk = chunk.split('rank: <a href="/ranks/users/start=')[1].split('</a></b><br><br>\n'); + rank = chunk[0].split('#')[1]; + points = chunk[1].split('</p>')[0]; + lblUser.setAttribute("value",spojranktracker_username); + lblRank.setAttribute("value","#"+ rank); + lblPts.setAttribute("value",points); + } + } else { + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",""); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","connection error"); + } + + setTimeout ('spojranktracker.ShowRank()',spojranktracker_recheck*1000*60); + } + }; + req.send(null); + }, + + ShowSettings: function(){ + window.openDialog("chrome://spojranktracker/content/options.xul"); + }, + + MonitorUsername: function(){ + spojranktracker_username = this.prefs.getCharPref("username"); + if (spojranktracker_username!=spojranktracker_oldusername){ + spojranktracker_oldusername = spojranktracker_username; + spojranktracker.ShowRank(); + } + + spojranktracker_recheck = Number(this.prefs.getCharPref("recheck")); + if (!spojranktracker_recheck || spojranktracker_recheck <=0){ + spojranktracker_recheck = 2; + this.prefs.setCharPref("recheck","2"); + } + }, + + openSPOJURL: function() { + url = "http://spoj.pl/users/"+spojranktracker_username; + var tabbrowser = gBrowser; + var tabs = tabbrowser.tabContainer.childNodes; + for (var i = 0; i < tabs.length; ++i) { + var tab = tabs[i]; + try { + var browser = tabbrowser.getBrowserForTab(tab); + if (browser) { + var doc = browser.contentDocument; + var loc = doc.location.toString(); + if (loc == url) { + gBrowser.selectedTab = tab; + return; + } + } + } + catch (e) { + } + } + + // There is no tab. open new tab... + var tab = gBrowser.addTab(url, null, null); + gBrowser.selectedTab = tab; + } +}; +window.addEventListener("load", function(e) { spojranktracker.onLoad(e); }, false); + diff --git a/content/overlay.js~ b/content/overlay.js~ new file mode 100644 index 0000000..851839a --- /dev/null +++ b/content/overlay.js~ @@ -0,0 +1,157 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is SPOJ Rank Tracker. + * + * The Initial Developer of the Original Code is + * Abhishek Mishra. + * Portions created by the Initial Developer are Copyright (C) 2009 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ +var oldusername=""; +var username=""; +var recheck = 2; + +var spojranktracker = { + // nice lesson from twitterfox source + $: function(name) { + return document.getElementById(name); + }, + onLoad: function() { + // initialization code + this.initialized = true; + this.strings = document.getElementById("spojranktracker-strings"); + + this.prefs = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefService) + .getBranch("srt."); + + setTimeout ('spojranktracker.ShowRank()',1500); + setInterval ('spojranktracker.MonitorUsername()',1000); + }, + onToolbarButtonCommand: function(e) { + // just reuse the function above. you can change this, obviously! + spojranktracker.onMenuItemCommand(e); + }, + + ShowRank: function(){ + var rank = "0"; + var points = "0"; + var lblRank = spojranktracker.$("SPOJ_rank"); + var lblUser = spojranktracker.$("SPOJ_user"); + var lblPts = spojranktracker.$("SPOJ_pts"); + var lblErr = spojranktracker.$("SPOJ_error"); + + if (username==""){ + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",""); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","your spoj username?"); + return; + } + + var req = new XMLHttpRequest(); + req.open('GET', 'http://spoj.pl/users/' + username, true); + req.onreadystatechange = function (aEvt) { + lblErr.setAttribute("value",""); + if (req.readyState == 4) { + if(req.status == 200){ + chunk = req.responseText; + // test for data + if (chunk.indexOf("rank:")==-1){ + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",username); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","does not exist"); + } else { + chunk = chunk.split('rank: <a href="/ranks/users/start=')[1].split('</a></b><br><br>\n'); + rank = chunk[0].split('#')[1]; + points = chunk[1].split('</p>')[0]; + lblUser.setAttribute("value",username); + lblRank.setAttribute("value","#"+ rank); + lblPts.setAttribute("value",points); + } + } else { + lblRank.setAttribute("value",""); + lblUser.setAttribute("value",""); + lblPts.setAttribute("value",""); + lblErr.setAttribute("value","connection error"); + } + + setTimeout ('spojranktracker.ShowRank()',recheck*1000*60); + } + }; + req.send(null); + }, + + ShowSettings: function(){ + window.openDialog("chrome://spojranktracker/content/options.xul"); + }, + + MonitorUsername: function(){ + username = this.prefs.getCharPref("username"); + if (username!=oldusername){ + oldusername = username; + spojranktracker.ShowRank(); + } + + recheck = Number(this.prefs.getCharPref("recheck")); + if (!recheck || recheck <=0){ + recheck = 2; + this.prefs.setCharPref("recheck","2"); + } + }, + + openSPOJURL: function() { + url = "http://spoj.pl/users/"+username; + var tabbrowser = gBrowser; + var tabs = tabbrowser.tabContainer.childNodes; + for (var i = 0; i < tabs.length; ++i) { + var tab = tabs[i]; + try { + var browser = tabbrowser.getBrowserForTab(tab); + if (browser) { + var doc = browser.contentDocument; + var loc = doc.location.toString(); + if (loc == url) { + gBrowser.selectedTab = tab; + return; + } + } + } + catch (e) { + } + } + + // There is no tab. open new tab... + var tab = gBrowser.addTab(url, null, null); + gBrowser.selectedTab = tab; + } +}; +window.addEventListener("load", function(e) { spojranktracker.onLoad(e); }, false); + diff --git a/defaults/preferences/spojranktracker.js b/defaults/preferences/spojranktracker.js new file mode 100644 index 0000000..02ca9e1 --- /dev/null +++ b/defaults/preferences/spojranktracker.js @@ -0,0 +1,4 @@ +// See http://kb.mozillazine.org/Localize_extension_descriptions +pref("[email protected]", "chrome://spojranktracker/locale/spojranktracker.properties"); +pref("srt.username", ""); +pref("srt.recheck", "2"); diff --git a/install.rdf b/install.rdf new file mode 100644 index 0000000..7f40274 --- /dev/null +++ b/install.rdf @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:em="http://www.mozilla.org/2004/em-rdf#"> + <Description about="urn:mozilla:install-manifest"> + <em:id>[email protected]</em:id> + <em:name>SPOJ Rank Tracker</em:name> + <em:version>1.03</em:version> + <em:creator>Abhishek Mishra - [email protected]</em:creator> + <em:description>SPOJ Rank Tracker helps you keep a track of your rank and points you scored on Sphere Online Judge (SPOJ) http://spoj.pl. There are more than 47,000 programmers that compete on SPOJ, the ranks are under constant turbulence. This addon helps you maintain continuity in your SPOJ submissions. All the best, developed by http://ideamonk.blogspot.com , Happy Coding :)</em:description> + <em:optionsURL>chrome://spojranktracker/content/options.xul</em:optionsURL> + <em:aboutURL>chrome://spojranktracker/content/about.xul</em:aboutURL> + <em:targetApplication> + <Description> + <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox --> + <em:minVersion>1.5</em:minVersion> + <em:maxVersion>3.5.*</em:maxVersion> + </Description> + </em:targetApplication> + </Description> +</RDF> diff --git a/locale/en-US/about.dtd b/locale/en-US/about.dtd new file mode 100644 index 0000000..137134d --- /dev/null +++ b/locale/en-US/about.dtd @@ -0,0 +1,4 @@ +<!ENTITY about "About"> +<!ENTITY version "Version: 1.0"> +<!ENTITY createdBy "Created By: Abhishek Mishra"> +<!ENTITY homepage "Home Page: http://ideamonk.blogspot.com"> diff --git a/locale/en-US/spojranktracker.dtd b/locale/en-US/spojranktracker.dtd new file mode 100644 index 0000000..b72ea58 --- /dev/null +++ b/locale/en-US/spojranktracker.dtd @@ -0,0 +1,3 @@ +<!ENTITY spojranktracker.label "Your localized menuitem"> +<!ENTITY spojranktrackerToolbar.label "Your Toolbar Button"> +<!ENTITY spojranktrackerToolbar.tooltip "This is your toolbar button!"> diff --git a/locale/en-US/spojranktracker.properties b/locale/en-US/spojranktracker.properties new file mode 100644 index 0000000..b3ea427 --- /dev/null +++ b/locale/en-US/spojranktracker.properties @@ -0,0 +1,2 @@ +prefMessage=Int Pref Value: %d +extensions.spojranktracker.description=SPOJ Rank Tracker helps you keep a track of your rank and points you scored on Sphere Online Judge (SPOJ) http://spoj.pl. There are more than 47,000 programmers that compete on SPOJ, the ranks are under constant turbulence. This addon helps you maintain continuity in your SPOJ submissions. All the best, developed by http://ideamonk.blogspot.com diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..249329f --- /dev/null +++ b/readme.txt @@ -0,0 +1,21 @@ +This extension was generated by the Extension Wizard at +http://ted.mielczarek.org/code/mozilla/extensionwiz/ . +This extension is compatible only with Firefox 1.5 and +above. Most of the files in this package are based on +the 'helloworld' extension from the Mozillazine Knowledge Base. + +You can build an XPI for installation by running the +build.sh script located in this folder. For development +you should do the following: + 1. Unzip the entire contents of this package to somewhere, + e.g, c:\dev or /home/user/dev + 2. Put the full path to the folder (e.g. c:\dev\spojranktracker on + Windows, /home/user/dev/spojranktracker on Linux) in a file named + [email protected] and copy that file to + [your profile folder]\extensions\ + 3. Restart Firefox. + +For more information, see the Mozillazine Knowledge Base: +http://kb.mozillazine.org/Getting_started_with_extension_development + +-Ted Mielczarek <[email protected]> diff --git a/skin/Thumbs.db b/skin/Thumbs.db new file mode 100644 index 0000000..f62cf04 Binary files /dev/null and b/skin/Thumbs.db differ diff --git a/skin/overlay.css b/skin/overlay.css new file mode 100644 index 0000000..edea479 --- /dev/null +++ b/skin/overlay.css @@ -0,0 +1,34 @@ +/* This is just an example. You shouldn't do this. */ +/* +#spojranktracker-hello +{ + color: red ! important; +} +#spojranktracker-toolbar-button +{ + list-style-image: url("chrome://spojranktracker/skin/toolbar-button.png"); + -moz-image-region: rect(0px 24px 24px 0px); +} +#spojranktracker-toolbar-button:hover +{ + -moz-image-region: rect(24px 24px 48px 0px); +} +[iconsize="small"] #spojranktracker-toolbar-button +{ + -moz-image-region: rect( 0px 40px 16px 24px); +} +[iconsize="small"] #spojranktracker-toolbar-button:hover +{ + -moz-image-region: rect(24px 40px 40px 24px); +} +*/ +.srt-rank{ + color:green; + font-weight:bold; +} +.pref-refresh{ + width:30px; +} +.pref-user{ + width:100px; +} \ No newline at end of file diff --git a/skin/target.png b/skin/target.png new file mode 100644 index 0000000..82b14ad Binary files /dev/null and b/skin/target.png differ
timoxley/Components
c11a818ed8ff64a664a7fd3a4748aecba8a21e67
Renamed packages, cleaned up function names and comments
diff --git a/src/au/com/origo/utilities/Utils.as b/src/au/com/origo/utilities/Utils.as deleted file mode 100644 index d6b6ed5..0000000 --- a/src/au/com/origo/utilities/Utils.as +++ /dev/null @@ -1,97 +0,0 @@ -package au.com.origo.utilities -{ - public class Utils - { - import flash.utils.getQualifiedClassName; - - - - - public function Utils() - { - - } - - /** - * Returns the name of the class without its package name from any passed in object - * @param object Object to get the class name from - */ - static public function getClassName(object:*):String { - var qualifiedName:String = getQualifiedClassName(object); - return qualifiedNameToClassName(qualifiedName); - } - - static public function qualifiedNameToClassName(qualifiedName:String):String { - var parts:Array = qualifiedName.split('::'); - if (parts.length == 2) { - // Handle package.path::Class - return parts[1]; - } else if (parts.length == 1) { - // Handle top level packages - // String, Number etc - return parts[0]; - } else { - // parts.length > 2 means we have a malformed package/class name - throw new Error("Malformed package::class name: " + qualifiedName); - } - } - - /** - * Takes a string name and adds a numeric suffix one larger than any existing numeric suffix. - * If no suffix, adds _2 to name. - * Note it doesn't add _1 because this is confusing: - * we naturally start counting from 1: - * <pre> - * - * Object - * Object_1 <- Confusing. Is this the first object? No, the other one is. hmm - * VS. - * Object - * Object_2 <- More clear. Ahh... it's the second object with this name. - * </pre> - * - * Additionally, this is the same method as other apps doing this, - * which I guess is argument enough. - * - * @param name String to append the numeric suffix to - * @return name with its incremented suffix - * - * <pre><code> - * Util.incrementNameNumber("name") // name_2 - * Util.incrementNameNumber("name_1") // name_2 - * Util.incrementNameNumber("name_10") // name_11 - * Util.incrementNameNumber("name20") // name21 - * Util.incrementNameNumber("name0") // name1 - * <code></pre> - */ - static public function incrementNameNumber(name:String):String { - var nameResult:String = name; - var findLastDigit:RegExp = new RegExp("([\\d]+)$"); - var lastDigitsMatches:Array = name.match(findLastDigit); - - if (!lastDigitsMatches) { - // No match - nameResult = name + "_2"; - } else if (lastDigitsMatches.length == 2) { - //Found trailing digits - //(for some reason length == 2 when it correctly identifies - // a match :/ ) - - //strip off trailing digits - nameResult = name.replace(findLastDigit, ""); - - //Convert string to integer - var index:uint = parseInt(lastDigitsMatches[0]); - - //Append incremented digit to result - nameResult = nameResult + (index + 1); - } else { - //Something wrong with regex - throw new Error("The regular expression " + findLastDigit + - " is incorrect. Found " + lastDigitsMatches.length + " 'final' digits.") - } - return nameResult; - } - - } -} \ No newline at end of file diff --git a/src/au/com/origo/components/Console.as b/src/com/timoxley/components/Console.as similarity index 83% rename from src/au/com/origo/components/Console.as rename to src/com/timoxley/components/Console.as index 201a091..9364778 100644 --- a/src/au/com/origo/components/Console.as +++ b/src/com/timoxley/components/Console.as @@ -1,63 +1,63 @@ -package au.com.origo.components { +package com.timoxley.components { - import au.com.origo.components.interfaces.IMessageBoard; - import au.com.origo.components.skins.ConsoleSkin; + import com.timoxley.components.interfaces.IMessageBoard; + import com.timoxley.components.skins.ConsoleSkin; import flash.events.Event; import flash.events.MouseEvent; import mx.logging.ILogger; import mx.logging.Log; import spark.components.Button; import spark.components.RichText; import spark.components.SkinnableContainer; public class Console extends SkinnableContainer implements IMessageBoard { public static const DEFAULT_CATEGORY:String = "DefaultConsoleLoggerCategory"; [SkinPart(required="true")] public var textSpace:RichText; [Bindable] public var text:String = ""; [SkinPart(required="true")] public var clearBtn:Button; public function Console() { super(); - setStyle("skinClass", au.com.origo.components.skins.ConsoleSkin); + setStyle("skinClass", com.timoxley.components.skins.ConsoleSkin); this.addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event):void { var consoleTarget:ConsoleTarget = new ConsoleTarget(); consoleTarget.messageTarget = this; Log.addTarget(consoleTarget); clearBtn.addEventListener(MouseEvent.CLICK, handleClick); } public static function getLogger(category:String = null):ILogger { if (category) { return Log.getLogger(category); } else { return Log.getLogger(DEFAULT_CATEGORY); } } public function postMessage(message:String):void { text = message + "\n" + text; } public function clear():void { text = ""; } private function handleClick(event:MouseEvent):void{ clear(); } } } diff --git a/src/au/com/origo/components/ConsoleTarget.as b/src/com/timoxley/components/ConsoleTarget.as similarity index 88% rename from src/au/com/origo/components/ConsoleTarget.as rename to src/com/timoxley/components/ConsoleTarget.as index 134861d..1631ad8 100644 --- a/src/au/com/origo/components/ConsoleTarget.as +++ b/src/com/timoxley/components/ConsoleTarget.as @@ -1,42 +1,42 @@ -package au.com.origo.components +package com.timoxley.components { - import au.com.origo.components.interfaces.IMessageBoard; + import com.timoxley.components.interfaces.IMessageBoard; import mx.logging.ILogger; import mx.logging.LogEvent; import mx.logging.LogEventLevel; import mx.logging.targets.LineFormattedTarget; import mx.resources.IResourceManager; public class ConsoleTarget extends LineFormattedTarget { [Inject] public var resourceManager:IResourceManager; public var messageTarget:IMessageBoard; public function ConsoleTarget() { super(); } /** * Event handler that is called by the logging API -- not to be called directly. * @param event */ public override function logEvent(event : LogEvent) : void { // Take care to NOT include mx.*, as code in std lib issues log calls, // which will call this target, which will send a message to server // (through rpc operation), which will log to this again, ... until StackOverflowException var category : String = ILogger(event.target).category; if (category.indexOf("mx.") != 0) { if (messageTarget) { messageTarget.postMessage(event.message); } } } } } diff --git a/src/au/com/origo/components/EditableLabel.as b/src/com/timoxley/components/EditableLabel.as similarity index 95% rename from src/au/com/origo/components/EditableLabel.as rename to src/com/timoxley/components/EditableLabel.as index 098d618..dee2998 100644 --- a/src/au/com/origo/components/EditableLabel.as +++ b/src/com/timoxley/components/EditableLabel.as @@ -1,122 +1,122 @@ -package au.com.origo.components +package com.timoxley.components { - import au.com.origo.components.skins.EditableLabelSkin; + import com.timoxley.components.skins.EditableLabelSkin; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import mx.binding.utils.BindingUtils; import mx.binding.utils.ChangeWatcher; import mx.managers.IFocusManagerComponent; import spark.components.RichEditableText; import spark.components.SkinnableContainer; import spark.components.TextSelectionHighlighting; [SkinState("editing")] public class EditableLabel extends SkinnableContainer implements IFocusManagerComponent { private var _editing:Boolean = false; private var changeWatcher:ChangeWatcher; [Bindable] public var text:String; [SkinPart(required="true")] public var textView:RichEditableText; public function EditableLabel() { super(); - setStyle("skinClass", au.com.origo.components.skins.EditableLabelSkin); + setStyle("skinClass", com.timoxley.components.skins.EditableLabelSkin); this.focusEnabled = false; this.mouseFocusEnabled = false; } public function get editing():Boolean { return _editing; } public function set editing(value:Boolean):void { _editing = value; if (!_editing) { this.focusManager.setFocus(this.focusManager.getNextFocusManagerComponent(true)); this.focusManager.hideFocus(); changeWatcher.reset(textView) } else { changeWatcher.unwatch(); } this.invalidateSkinState(); } override protected function getCurrentSkinState():String { return editing ? "editing" : super.getCurrentSkinState(); } protected function focusHandler(event:FocusEvent):void { if (event.type == FocusEvent.FOCUS_IN) { trace("FOCUS_IN"); //this.editing = true; } else if (event.type == FocusEvent.FOCUS_OUT) { trace("FOCUS_OUT"); this.editing = false; } event.stopPropagation(); } public function clickHandler(event:MouseEvent):void { if (event.type == MouseEvent.DOUBLE_CLICK) { this.editing = true; event.stopImmediatePropagation(); } this.invalidateSkinState(); //event.stopImmediatePropagation(); } private function keyboardHandler(event:KeyboardEvent):void { if (event.keyCode == Keyboard.ENTER) { if (this.editing) { this.editing = false; } } } override protected function partAdded(partName:String, instance:Object):void { if (instance == textView) { textView.doubleClickEnabled = true; textView.addEventListener(MouseEvent.DOUBLE_CLICK, clickHandler); //textView.addEventListener(MouseEvent.CLICK, clickHandler); textView.addEventListener(FocusEvent.FOCUS_IN, focusHandler); textView.addEventListener(FocusEvent.FOCUS_OUT, focusHandler); changeWatcher = BindingUtils.bindProperty(textView, 'text', this, 'text'); textView.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); textView.selectionHighlighting = TextSelectionHighlighting.ALWAYS; } super.partAdded(partName, instance); } override protected function partRemoved(partName:String, instance:Object):void { if (instance == textView) { //textView.removeEventListener(FocusEvent.FOCUS_IN, focusHandler); textView.addEventListener(MouseEvent.DOUBLE_CLICK, clickHandler); textView.removeEventListener(FocusEvent.FOCUS_OUT, focusHandler); textView.removeEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); changeWatcher.unwatch(); } super.partRemoved(partName, instance); } } } \ No newline at end of file diff --git a/src/au/com/origo/components/interfaces/IMessageBoard.as b/src/com/timoxley/components/interfaces/IMessageBoard.as similarity index 68% rename from src/au/com/origo/components/interfaces/IMessageBoard.as rename to src/com/timoxley/components/interfaces/IMessageBoard.as index ff14665..2bef9e5 100644 --- a/src/au/com/origo/components/interfaces/IMessageBoard.as +++ b/src/com/timoxley/components/interfaces/IMessageBoard.as @@ -1,8 +1,8 @@ -package au.com.origo.components.interfaces +package com.timoxley.components.interfaces { public interface IMessageBoard { function postMessage(message:String):void; function clear():void; } } \ No newline at end of file diff --git a/src/au/com/origo/components/skins/ClearBtnSkin.mxml b/src/com/timoxley/components/skins/ClearBtnSkin.mxml similarity index 83% rename from src/au/com/origo/components/skins/ClearBtnSkin.mxml rename to src/com/timoxley/components/skins/ClearBtnSkin.mxml index 76cc3c2..e051f3d 100644 --- a/src/au/com/origo/components/skins/ClearBtnSkin.mxml +++ b/src/com/timoxley/components/skins/ClearBtnSkin.mxml @@ -1,40 +1,41 @@ <?xml version="1.0" encoding="utf-8"?> <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" - xmlns:mx="library://ns.adobe.com/flex/halo" + xmlns:mx="library://ns.adobe.com/flex/halo" + xmlns:mx1="library://ns.adobe.com/flex/mx" width="17" height="17"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ [Embed("assets/clear.png")] private const ClearIcon:Class; ]]> </fx:Script> <fx:Metadata> <![CDATA[ /** * @copy spark.skins.spark.ApplicationSkin#hostComponent */ [HostComponent("spark.components.Button")] ]]> </fx:Metadata> <!-- states --> <s:states> <s:State name="up" /> <s:State name="over" /> <s:State name="down" /> <s:State name="disabled" /> </s:states> - <mx:Image smoothBitmapContent="true" + <mx1:Image smoothBitmapContent="true" source="{ClearIcon}" id="clearBtn" width="17" maintainAspectRatio="true" right="10" top="10" alpha="0.7" alpha.over="1" alpha.down="1" /> </s:SparkSkin> diff --git a/src/au/com/origo/components/skins/ConsoleSkin.mxml b/src/com/timoxley/components/skins/ConsoleSkin.mxml similarity index 90% rename from src/au/com/origo/components/skins/ConsoleSkin.mxml rename to src/com/timoxley/components/skins/ConsoleSkin.mxml index 5d58b8a..f1e361f 100644 --- a/src/au/com/origo/components/skins/ConsoleSkin.mxml +++ b/src/com/timoxley/components/skins/ConsoleSkin.mxml @@ -1,160 +1,161 @@ <?xml version="1.0" encoding="utf-8"?> <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" + xmlns:mx1="library://ns.adobe.com/flex/mx" addedToStage="sparkskin1_addedToStageHandler(event)" width="100%" height="100%" includeInLayout="false"> <fx:Declarations> <s:AnimateColor id="flashLabel" colorTo="0x999999" target="{console}" duration="300" colorFrom="0xDDDDDD" /> <s:Fade id="flashFadeOut" alphaFrom="{console.alpha}" alphaTo="0.5" startDelay="3000" target="{console}" duration="500" /> <s:Fade id="flashFadeIn" alphaFrom="{console.alpha}" alphaTo="1" target="{console}" duration="100" /> <s:Fade id="scrollbarFadeOut" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="0.0" startDelay="3000" target="{ScrollerSkin(scroller.skin).verticalScrollBar}" duration="500" /> <s:Fade id="scrollbarFadeIn" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="1" target="{ScrollerSkin(scroller.skin).verticalScrollBar}" duration="100" /> </fx:Declarations> <fx:Metadata> <![CDATA[ - [HostComponent("au.com.origo.components.Console")] + [HostComponent("com.timoxley.components.Console")] ]]> </fx:Metadata> <fx:Script> <![CDATA[ import mx.events.PropertyChangeEvent; import spark.effects.AnimateColor; import spark.skins.spark.ScrollerSkin; public function flash():void { flashLabel.stop(); flashLabel.play(); flashFadeOut.stop(); flashFadeOut.play(); flashFadeIn.stop(); flashFadeIn.play(); } protected function sparkskin1_addedToStageHandler(event:Event):void { hostComponent.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, function(event:PropertyChangeEvent):void { if (event.property == 'text') { flash(); } }); //clearBtn.addEventListener(MouseEvent.MOUSE_OVER } protected function sparkskin1_mouseOutHandler(event:MouseEvent):void { flashFadeIn.stop(); flashFadeOut.play(); scrollbarFadeIn.stop(); scrollbarFadeOut.play(); } protected function sparkskin1_mouseOverHandler(event:MouseEvent):void { flashFadeOut.stop(); flashFadeIn.play(); scrollbarFadeOut.stop(); scrollbarFadeIn.play(); } ]]> </fx:Script> <s:states> <s:State name="normal" /> <s:State name="disabled" /> </s:states> - <mx:VDividedBox height="100%" width="100%" id="container" liveDragging="true"> + <mx1:VDividedBox height="100%" width="100%" id="container" liveDragging="true"> <s:Group height="100%" width="100%" id="transparent" mouseChildren="true" /> <s:Group height="40" width="100%" id="console" mouseChildren="true" minHeight="40" mouseOver="sparkskin1_mouseOverHandler(event)" mouseOut="sparkskin1_mouseOutHandler(event)"> <s:Rect height="40" width="100%"> <s:fill> <s:LinearGradient rotation="90"> <s:GradientEntry color="0x333333" alpha="0.6" /> <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> </s:LinearGradient> </s:fill> </s:Rect> <s:Rect height="100%" width="100%"> <s:fill> <s:SolidColor color="0xFFFFFF" alpha="0.6" /> </s:fill> <s:stroke> <s:SolidColorStroke weight="1" color="0x5555555" alpha="0.3" /> </s:stroke> </s:Rect> <s:Scroller width="100%" id="scroller" height="100%" contentBackgroundColor="0xFFFFFF" contentBackgroundAlpha="0.6"> <s:Group height="100%" width="100%"> <s:RichText id="textSpace" width="100%" color="0x555555" left="0" paddingLeft="14" paddingTop="14" paddingBottom="0" paddingRight="14" text="{hostComponent.text}" lineHeight="150%" fontFamily="Lucida Console, monospace" /> - <s:Button id="clearBtn" skinClass="au.com.origo.components.skins.ClearBtnSkin" right="0" top="0" /> + <s:Button id="clearBtn" skinClass="com.timoxley.components.skins.ClearBtnSkin" right="0" top="0" /> </s:Group> </s:Scroller> <s:Rect height="40" width="100%" bottom="0"> <s:fill> <s:LinearGradient rotation="90"> <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> <s:GradientEntry color="0x333333" alpha="0.5" /> </s:LinearGradient> </s:fill> </s:Rect> </s:Group> - </mx:VDividedBox> + </mx1:VDividedBox> </s:SparkSkin> diff --git a/src/au/com/origo/components/skins/EditableLabelSkin.mxml b/src/com/timoxley/components/skins/EditableLabelSkin.mxml similarity index 92% rename from src/au/com/origo/components/skins/EditableLabelSkin.mxml rename to src/com/timoxley/components/skins/EditableLabelSkin.mxml index b258186..906084d 100644 --- a/src/au/com/origo/components/skins/EditableLabelSkin.mxml +++ b/src/com/timoxley/components/skins/EditableLabelSkin.mxml @@ -1,96 +1,96 @@ <?xml version="1.0" encoding="utf-8"?> <!-- ADOBE SYSTEMS INCORPORATED Copyright 2008 Adobe Systems Incorporated All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the license agreement accompanying it. --> <!--- The default skin class for Spark TextInput component. @langversion 3.0 @playerversion Flash 10 @playerversion AIR 1.5 @productversion Flex 4 --> <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" > <fx:Metadata> <![CDATA[ /** * @copy spark.skins.default.ApplicationSkin#hostComponent */ - [HostComponent("au.com.origo.components.EditableLabel")] + [HostComponent("com.timoxley.components.EditableLabel")] ]]> </fx:Metadata> <fx:Script> <![CDATA[ - import au.com.origo.components.EditableLabel; + import com.timoxley.components.EditableLabel; /* Define the skin elements that should not be colorized. */ static private const exclusions:Array = ["background", "textView"]; /** * @copy spark.skins.SparkSkin#colorizeExclusions */ override public function get colorizeExclusions():Array {return exclusions;} /* Define the content fill items that should be colored by the "contentBackgroundColor" style. */ static private const contentFill:Array = ["bgFill"]; /** * @inheritDoc */ override public function get contentItems():Array {return contentFill}; ]]> </fx:Script> <s:states> <s:State name="normal"/> <s:State name="disabled"/> <s:State name="editing"/> </s:states> <!-- border --> <s:Rect left="0" right="0" top="0" bottom="0" id="border" alpha.editing="1" alpha.normal="0"> <s:stroke> <s:LinearGradientStroke rotation="90" weight="1"> <s:GradientEntry color="0x000000" alpha="0.5525" /> <s:GradientEntry color="0x000000" alpha="0.6375" /> </s:LinearGradientStroke> </s:stroke> </s:Rect> <!-- fill --> <!--- Defines the appearance of the TextInput component's background. --> <s:Rect id="background" left="1" right="1" top="1" bottom="1" alpha.editing="1.0" alpha.normal="0"> <s:fill> <!--- Defines the background fill color. --> <s:SolidColor id="bgFill" color="0xFFFFFF" /> </s:fill> </s:Rect> <!-- shadow --> <s:Rect left="1" top="1" right="1" height="1" id="shadow" alpha.editing="1.0" alpha.normal="0"> <s:fill> <s:SolidColor color="0x000000" alpha="0.12" /> </s:fill> </s:Rect> <!-- text --> <s:RichEditableText id="textView" lineBreak="explicit" left="1" right="1" top="1" bottom="1" paddingLeft="3" paddingTop="5" paddingRight="3" paddingBottom="3" multiline="false" focusEnabled="false" editable="false" editable.editing="true"/> </s:SparkSkin> diff --git a/src/au/com/origo/utilities/SafeResourceManager.as b/src/com/timoxley/utilities/SafeResourceManager.as similarity index 96% rename from src/au/com/origo/utilities/SafeResourceManager.as rename to src/com/timoxley/utilities/SafeResourceManager.as index b8103a0..5a1a8b5 100644 --- a/src/au/com/origo/utilities/SafeResourceManager.as +++ b/src/com/timoxley/utilities/SafeResourceManager.as @@ -1,186 +1,186 @@ -package au.com.origo.utilities +package com.timoxley.utilities { - import au.com.origo.utilities.events.InfoEvent; + import com.timoxley.utilities.events.InfoEvent; import flash.events.Event; import flash.events.IEventDispatcher; import flash.system.ApplicationDomain; import flash.system.SecurityDomain; import mx.resources.IResourceBundle; import mx.resources.IResourceManager; import mx.resources.ResourceManager; public class SafeResourceManager implements IResourceManager { public static const RESOURCE_NOT_FOUND:String = "resource_not_found"; [Inject] public var eventDispatcher:IEventDispatcher; private var resourceManager:IResourceManager; public function SafeResourceManager() { resourceManager = ResourceManager.getInstance(); } public function get localeChain():Array { return resourceManager.localeChain; } public function set localeChain(value:Array):void { resourceManager.localeChain = value; } public function loadResourceModule(url:String, update:Boolean=true, applicationDomain:ApplicationDomain=null, securityDomain:SecurityDomain=null):IEventDispatcher { return resourceManager.loadResourceModule(url, update, applicationDomain, securityDomain); } public function unloadResourceModule(url:String, update:Boolean=true):void { resourceManager.unloadResourceModule(url, update); } public function addResourceBundle(resourceBundle:IResourceBundle):void { resourceManager.addResourceBundle(resourceBundle); } public function removeResourceBundle(locale:String, bundleName:String):void { resourceManager.removeResourceBundle(locale, bundleName); } public function removeResourceBundlesForLocale(locale:String):void { resourceManager.removeResourceBundlesForLocale(locale); } public function update():void { resourceManager.update(); } public function getLocales():Array { return resourceManager.getLocales(); } public function getPreferredLocaleChain():Array { return resourceManager.getPreferredLocaleChain(); } public function getBundleNamesForLocale(locale:String):Array { return resourceManager.getBundleNamesForLocale(locale); } public function getResourceBundle(locale:String, bundleName:String):IResourceBundle { return resourceManager.getResourceBundle(locale, bundleName); } public function findResourceBundleWithResource(bundleName:String, resourceName:String):IResourceBundle { return resourceManager.findResourceBundleWithResource(bundleName, resourceName); } public function getObject(bundleName:String, resourceName:String, locale:String=null):* { var value:Object = resourceManager.getObject(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return null; } return value; } public function getString(bundleName:String, resourceName:String, parameters:Array=null, locale:String=null):String { var value:String = resourceManager.getString(bundleName, resourceName, parameters, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return resourceName; } return value; } public function getStringArray(bundleName:String, resourceName:String, locale:String=null):Array { var value:Array = resourceManager.getStringArray(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return null; } return value; } public function getNumber(bundleName:String, resourceName:String, locale:String=null):Number { var value:Number = resourceManager.getNumber(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return 0; } return value; } public function getInt(bundleName:String, resourceName:String, locale:String=null):int { var value:int = resourceManager.getInt(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return 0; } return value; } public function getUint(bundleName:String, resourceName:String, locale:String=null):uint { var value:uint = resourceManager.getUint(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return 0; } return value; } public function getBoolean(bundleName:String, resourceName:String, locale:String=null):Boolean { var value:Boolean = resourceManager.getBoolean(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return false; } return value; } public function getClass(bundleName:String, resourceName:String, locale:String=null):Class { var value:Class = resourceManager.getClass(bundleName, resourceName, locale); if (!value) { this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); return null; } return value; } public function installCompiledResourceBundles(applicationDomain:ApplicationDomain, locales:Array, bundleNames:Array):void { resourceManager.installCompiledResourceBundles(applicationDomain, locales, bundleNames); } public function initializeLocaleChain(compiledLocales:Array):void { resourceManager.initializeLocaleChain(compiledLocales); } public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void { eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void { eventDispatcher.removeEventListener(type, listener, useCapture); } public function dispatchEvent(event:Event):Boolean { return eventDispatcher.dispatchEvent(event); } public function hasEventListener(type:String):Boolean { return eventDispatcher.hasEventListener(type); } public function willTrigger(type:String):Boolean { return eventDispatcher.willTrigger(type); } public function hasResource(bundleName:String, resourceName:String, locale:String=null):Boolean { if (resourceManager.getObject(bundleName, resourceName, locale)) { return true; } return false; } } } \ No newline at end of file diff --git a/src/com/timoxley/utilities/Utils.as b/src/com/timoxley/utilities/Utils.as new file mode 100644 index 0000000..f31bbc3 --- /dev/null +++ b/src/com/timoxley/utilities/Utils.as @@ -0,0 +1,126 @@ +//////////////////////////////////////////////////////////// +// +// Copyright Tim Oxley 2010 +// All rights reserved. +// +//////////////////////////////////////////////////////////// + + +package com.timoxley.utilities { + import flash.utils.getQualifiedClassName; + + public class Utils { + + //========================================================== + // + // + // Statics + // + // + //========================================================== + + /** + * Returns just class name of the passed-in object (without the package name) + * @param object Object to get the class name from + * @author Tim Oxley + */ + public static function getClassName(object:*):String { + var qualifiedName:String = getQualifiedClassName(object); + return getClassNameFromQualifiedName(qualifiedName); + } + + /** + * Takes a qualified class name String eg 'flexutils:Utils' and returns just the class name: eg 'Utils' + * @author Tim Oxley + */ + public static function getClassNameFromQualifiedName(qualifiedName:String):String { + var parts:Array = qualifiedName.split('::'); + + if (parts.length == 2) { + // Handle package.path::Class + return parts[1]; + } else if (parts.length == 1) { + // Handle top level packages + // String, Number etc + return parts[0]; + } else { + // parts.length > 2 means we have a malformed package/class name + throw new Error("Malformed package::class name: " + qualifiedName); + } + } + + /** + * Takes a string name and adds a numeric suffix one larger than any existing numeric suffix. + * If no suffix, adds _2 to name. + * Note it doesn't add _1 because this is confusing: + * we naturally start counting from 1: + * <pre> + * + * Object + * Object_1 <- Confusing. Is this the first object? No, the other one is. hmm + * VS. + * Object + * Object_2 <- More clear. Ahh... it's the second object with this name. + * </pre> + * + * Additionally, this is the same method as other apps doing this, + * which I guess is argument enough. + * + * @param name String to append the numeric suffix to + * @return name with its incremented suffix + * @author Tim Oxley + * + * <pre><code> + * Util.incrementNameNumber("name") // name > name_2 + * Util.incrementNameNumber("name_1") // name_1 > name_2 + * Util.incrementNameNumber("name_10") // name_10 > name_11 + * Util.incrementNameNumber("name20") // name20 > name21 + * Util.incrementNameNumber("name0") // name0 > name1 + * <code></pre> + */ + public static function incrementName(name:String):String { + var nameResult:String = name; + var findLastDigit:RegExp = new RegExp("([\\d]+)$"); + var lastDigitsMatches:Array = name.match(findLastDigit); + + if (!lastDigitsMatches) { + // No match + nameResult = name + "_2"; + } else if (lastDigitsMatches.length == 2) { + // Found trailing digits + + // Strip off trailing digits + nameResult = name.replace(findLastDigit, ""); + + // Convert last digit to integer so we can increment it + var index:uint = parseInt(lastDigitsMatches[0]); + + // Append incremented digit to result + nameResult = nameResult + (index + 1); + } else { + // Otherwise, there is something wrong with the regex + throw new Error("The regular expression " + findLastDigit + " is incorrect. Found " + lastDigitsMatches.length + " 'final' digits.") + } + return nameResult; + } + + //========================================================== + // + // + // Members + // + // + //========================================================== + + //-------------------------------------- + // Constructor + //-------------------------------------- + + /** + * Does nothing. Static methods only, no need for an instance. + */ + public function Utils() { + + } + } +} \ No newline at end of file diff --git a/src/au/com/origo/utilities/events/InfoEvent.as b/src/com/timoxley/utilities/events/InfoEvent.as similarity index 94% rename from src/au/com/origo/utilities/events/InfoEvent.as rename to src/com/timoxley/utilities/events/InfoEvent.as index 3187379..00a246c 100644 --- a/src/au/com/origo/utilities/events/InfoEvent.as +++ b/src/com/timoxley/utilities/events/InfoEvent.as @@ -1,65 +1,65 @@ -package au.com.origo.utilities.events +package com.timoxley.utilities.events { import flash.events.ErrorEvent; import flash.events.Event; public class InfoEvent extends Event { public var message:String; public var params:Array; /** * Some information that the user should be notified of. eg * <ul> * <li> Action performed with success * <li> An event occurred * </ul> */ static public const USER_INFO:String = "userInfoFlareEvent"; /** * Some error that the user should be notified of. eg * <ul> * <li> Connection failed * <li> Invalid user text input * <li> * </ul> */ static public const USER_ERROR:String = "userErrorFlareEvent"; /** * Programmer specific information for debugging purposes * */ static public const DEBUG:String = "debugFlareEvent"; /** * Programmer specific information for debugging purposes * */ static public const WARNING:String = "warningFlareEvent"; /** * Programmer specific information for debugging purposes. * Means there is something wrong with the app and it cannot/should not continue. * Program should shut down if it recieves this event. */ static public const FATAL:String = "fatalFlareEvent"; /** * @param type Type of event. If one of the constants defined in this class should be picked up by Logger & ResourceManager * @param message Optional Textual message of event. Use ResourceManager property references (as defined in locale) if using LogCommand. * @param rest other parameters for substitution by ResourceManager.getString */ public function InfoEvent(type:String, message:String="", ... rest:*) { this.params = rest; this.message = message; super(type, true); } override public function clone():Event { return new InfoEvent(this.type, message, params); } } } \ No newline at end of file
timoxley/Components
b1f2136d1e3ea7c493e9036904789bb3a02909a7
Cleaned up trace statements
diff --git a/src/au/com/origo/components/Console.as b/src/au/com/origo/components/Console.as index ee39885..201a091 100644 --- a/src/au/com/origo/components/Console.as +++ b/src/au/com/origo/components/Console.as @@ -1,64 +1,63 @@ package au.com.origo.components { import au.com.origo.components.interfaces.IMessageBoard; import au.com.origo.components.skins.ConsoleSkin; import flash.events.Event; import flash.events.MouseEvent; import mx.logging.ILogger; import mx.logging.Log; import spark.components.Button; import spark.components.RichText; import spark.components.SkinnableContainer; public class Console extends SkinnableContainer implements IMessageBoard { public static const DEFAULT_CATEGORY:String = "DefaultConsoleLoggerCategory"; [SkinPart(required="true")] public var textSpace:RichText; [Bindable] public var text:String = ""; [SkinPart(required="true")] public var clearBtn:Button; public function Console() { super(); - trace("Creating Console"); setStyle("skinClass", au.com.origo.components.skins.ConsoleSkin); this.addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event):void { var consoleTarget:ConsoleTarget = new ConsoleTarget(); consoleTarget.messageTarget = this; Log.addTarget(consoleTarget); clearBtn.addEventListener(MouseEvent.CLICK, handleClick); } public static function getLogger(category:String = null):ILogger { if (category) { return Log.getLogger(category); } else { return Log.getLogger(DEFAULT_CATEGORY); } } public function postMessage(message:String):void { text = message + "\n" + text; } public function clear():void { text = ""; } private function handleClick(event:MouseEvent):void{ clear(); } } -} \ No newline at end of file +} diff --git a/src/au/com/origo/components/ConsoleLogger.as b/src/au/com/origo/components/ConsoleLogger.as deleted file mode 100644 index 54a85c1..0000000 --- a/src/au/com/origo/components/ConsoleLogger.as +++ /dev/null @@ -1,43 +0,0 @@ -package au.com.origo.components -{ - import mx.logging.ILogger; - import mx.logging.ILoggingTarget; - import mx.logging.Log; - - public class ConsoleLogger - { - //~ Instance Attributes ----------------------------------------------- - private var logger : ILogger; - - //~ Constructor ------------------------------------------------------- - /** - * SingletonEnforcer parameter ensures that only the getInstance - * method can create an instance of this class. - */ - public function ConsoleLogger(category:String, enforcer:SingletonEnforcer) : void - { - this.logger = Log.getLogger(category); - } - - //~ Methods ----------------------------------------------------------- - public static function getInstance(category:String):ConsoleLogger - { - return new ConsoleLogger(category, new SingletonEnforcer()); - } - - public static function addTarget(target:ILoggingTarget) : void { - Log.addTarget(target); - } - - public static function removeTarget(target:ILoggingTarget) : void { - Log.removeTarget(target); - } - - public function debug(message : String) : void { - this.logger.debug(message); - } - - // other logging methods by level (e.g. warn, error) - } -} -internal class SingletonEnforcer {} \ No newline at end of file diff --git a/src/au/com/origo/components/ConsoleTarget.as b/src/au/com/origo/components/ConsoleTarget.as index c95a9f5..134861d 100644 --- a/src/au/com/origo/components/ConsoleTarget.as +++ b/src/au/com/origo/components/ConsoleTarget.as @@ -1,43 +1,42 @@ package au.com.origo.components { import au.com.origo.components.interfaces.IMessageBoard; import mx.logging.ILogger; import mx.logging.LogEvent; import mx.logging.LogEventLevel; import mx.logging.targets.LineFormattedTarget; import mx.resources.IResourceManager; public class ConsoleTarget extends LineFormattedTarget { [Inject] public var resourceManager:IResourceManager; public var messageTarget:IMessageBoard; public function ConsoleTarget() { super(); } /** * Event handler that is called by the logging API -- not to be called directly. * @param event */ public override function logEvent(event : LogEvent) : void { // Take care to NOT include mx.*, as code in std lib issues log calls, // which will call this target, which will send a message to server // (through rpc operation), which will log to this again, ... until StackOverflowException var category : String = ILogger(event.target).category; if (category.indexOf("mx.") != 0) { - trace("event.message" + event.message); if (messageTarget) { messageTarget.postMessage(event.message); } } } } -} \ No newline at end of file +}
timoxley/Components
891142b7eac8669afed13c378e1fa67aaccf5eac
Improved skin behaviour
diff --git a/src/au/com/origo/components/skins/ConsoleSkin.mxml b/src/au/com/origo/components/skins/ConsoleSkin.mxml index 4099f30..5d58b8a 100644 --- a/src/au/com/origo/components/skins/ConsoleSkin.mxml +++ b/src/au/com/origo/components/skins/ConsoleSkin.mxml @@ -1,147 +1,160 @@ <?xml version="1.0" encoding="utf-8"?> -<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" - xmlns:s="library://ns.adobe.com/flex/spark" +<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" - addedToStage="sparkskin1_addedToStageHandler(event)" + addedToStage="sparkskin1_addedToStageHandler(event)" width="100%" height="100%" - includeInLayout="false" - > + includeInLayout="false"> <fx:Declarations> <s:AnimateColor id="flashLabel" colorTo="0x999999" target="{console}" duration="300" - colorFrom="0xDDDDDD"/> - <s:Fade id="flashFadeOut" alphaFrom="{console.alpha}" alphaTo="0.5" startDelay="3000" + colorFrom="0xDDDDDD" /> + + <s:Fade id="flashFadeOut" + alphaFrom="{console.alpha}" + alphaTo="0.5" + startDelay="3000" target="{console}" - duration="500" - /> - <s:Fade id="flashFadeIn" alphaFrom="{console.alpha}" alphaTo="1" + duration="500" /> + + <s:Fade id="flashFadeIn" + alphaFrom="{console.alpha}" + alphaTo="1" target="{console}" - duration="100" - /> - <s:Fade id="scrollbarFadeOut" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="0.0" startDelay="3000" + duration="100" /> + + <s:Fade id="scrollbarFadeOut" + alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" + alphaTo="0.0" + startDelay="3000" target="{ScrollerSkin(scroller.skin).verticalScrollBar}" - duration="500" - /> - <s:Fade id="scrollbarFadeIn" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="1" + duration="500" /> + + <s:Fade id="scrollbarFadeIn" + alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" + alphaTo="1" target="{ScrollerSkin(scroller.skin).verticalScrollBar}" - duration="100" - /> + duration="100" /> </fx:Declarations> + <fx:Metadata> <![CDATA[ [HostComponent("au.com.origo.components.Console")] ]]> - </fx:Metadata> + </fx:Metadata> + <fx:Script> <![CDATA[ import mx.events.PropertyChangeEvent; - import spark.effects.AnimateColor; import spark.skins.spark.ScrollerSkin; - protected function sparkskin1_addedToStageHandler(event:Event):void { - hostComponent.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, function(event:PropertyChangeEvent):void { - if (event.property == 'text') { - flash(); - } - }); - //clearBtn.addEventListener(MouseEvent.MOUSE_OVER - - } - public function flash():void { flashLabel.stop(); flashLabel.play(); flashFadeOut.stop(); flashFadeOut.play(); flashFadeIn.stop(); flashFadeIn.play(); } - protected function sparkskin1_mouseOverHandler(event:MouseEvent):void { - flashFadeOut.stop(); - flashFadeIn.play(); - scrollbarFadeOut.stop(); - scrollbarFadeIn.play(); + protected function sparkskin1_addedToStageHandler(event:Event):void { + hostComponent.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, + function(event:PropertyChangeEvent):void { + if (event.property == 'text') { + flash(); + } + }); + //clearBtn.addEventListener(MouseEvent.MOUSE_OVER + } - protected function sparkskin1_mouseOutHandler(event:MouseEvent):void { + protected function sparkskin1_mouseOutHandler(event:MouseEvent):void { flashFadeIn.stop(); flashFadeOut.play(); scrollbarFadeIn.stop(); scrollbarFadeOut.play(); } - + protected function sparkskin1_mouseOverHandler(event:MouseEvent):void { + flashFadeOut.stop(); + flashFadeIn.play(); + scrollbarFadeOut.stop(); + scrollbarFadeIn.play(); + } ]]> </fx:Script> - + <s:states> - <s:State name="normal"/> - <s:State name="disabled"/> + <s:State name="normal" /> + + <s:State name="disabled" /> </s:states> + <mx:VDividedBox height="100%" width="100%" id="container" liveDragging="true"> <s:Group height="100%" width="100%" id="transparent" mouseChildren="true" /> - <s:Group height="40" width="100%" id="console" mouseChildren="true" minHeight="40" - mouseOver="sparkskin1_mouseOverHandler(event)" + + <s:Group height="40" + width="100%" + id="console" + mouseChildren="true" + minHeight="40" + mouseOver="sparkskin1_mouseOverHandler(event)" mouseOut="sparkskin1_mouseOutHandler(event)"> - <s:Rect height="40" width="100%"> - <s:fill> - <s:LinearGradient rotation="90"> + <s:LinearGradient rotation="90"> <s:GradientEntry color="0x333333" alpha="0.6" /> - <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8"/> + + <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> </s:LinearGradient> - </s:fill> </s:Rect> - - + <s:Rect height="100%" width="100%"> - <s:fill> <s:SolidColor color="0xFFFFFF" alpha="0.6" /> </s:fill> + <s:stroke> <s:SolidColorStroke weight="1" color="0x5555555" alpha="0.3" /> </s:stroke> - </s:Rect> - - <s:Scroller width="100%" id="scroller" height="100%" contentBackgroundColor="0xFFFFFF" contentBackgroundAlpha="0.6"> + + <s:Scroller width="100%" + id="scroller" + height="100%" + contentBackgroundColor="0xFFFFFF" + contentBackgroundAlpha="0.6"> <s:Group height="100%" width="100%"> <s:RichText id="textSpace" width="100%" color="0x555555" left="0" paddingLeft="14" paddingTop="14" paddingBottom="0" - paddingRight="14" - text="{hostComponent.text}" - lineHeight="150%" fontFamily="Lucida Console, monospace"/> - + paddingRight="14" + text="{hostComponent.text}" + lineHeight="150%" + fontFamily="Lucida Console, monospace" /> + <s:Button id="clearBtn" skinClass="au.com.origo.components.skins.ClearBtnSkin" right="0" top="0" /> - - </s:Group> </s:Scroller> + <s:Rect height="40" width="100%" bottom="0"> - <s:fill> <s:LinearGradient rotation="90"> - <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> + <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> + <s:GradientEntry color="0x333333" alpha="0.5" /> - </s:LinearGradient> - </s:fill> </s:Rect> - </s:Group> </mx:VDividedBox> </s:SparkSkin>
timoxley/Components
b4ecfbdfa4190acfe9e9710fde034ea310a4fe23
Added Console and Utilities
diff --git a/assets/clear.png b/assets/clear.png new file mode 100644 index 0000000..fdc6aaa Binary files /dev/null and b/assets/clear.png differ diff --git a/src/FlexUnitApplication.mxml b/src/FlexUnitApplication.mxml new file mode 100644 index 0000000..14031e7 --- /dev/null +++ b/src/FlexUnitApplication.mxml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768" xmlns:flexunit="flexunit.flexui.*" creationComplete="onCreationComplete()" > +<fx:Script> + <![CDATA[ + + import org.flexunit.runner.Request; + import tests.TestUtils; + + public function currentRunTestSuite():Array + { + var testsToRun:Array = new Array(); + testsToRun.push(tests.TestUtils); + return testsToRun; + } + private function onCreationComplete():void + { + testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "Components"); + } +]]> +</fx:Script> +<flexunit:FlexUnitTestRunnerUI id="testRunner"/> +</s:Application> diff --git a/src/au/com/origo/components/Console.as b/src/au/com/origo/components/Console.as new file mode 100644 index 0000000..ee39885 --- /dev/null +++ b/src/au/com/origo/components/Console.as @@ -0,0 +1,64 @@ +package au.com.origo.components { + + import au.com.origo.components.interfaces.IMessageBoard; + import au.com.origo.components.skins.ConsoleSkin; + + import flash.events.Event; + import flash.events.MouseEvent; + + import mx.logging.ILogger; + import mx.logging.Log; + + import spark.components.Button; + import spark.components.RichText; + import spark.components.SkinnableContainer; + + public class Console extends SkinnableContainer implements IMessageBoard + { + public static const DEFAULT_CATEGORY:String = "DefaultConsoleLoggerCategory"; + + [SkinPart(required="true")] + public var textSpace:RichText; + + [Bindable] + public var text:String = ""; + + [SkinPart(required="true")] + public var clearBtn:Button; + + public function Console() { + super(); + trace("Creating Console"); + setStyle("skinClass", au.com.origo.components.skins.ConsoleSkin); + this.addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(event:Event):void { + var consoleTarget:ConsoleTarget = new ConsoleTarget(); + consoleTarget.messageTarget = this; + Log.addTarget(consoleTarget); + clearBtn.addEventListener(MouseEvent.CLICK, handleClick); + } + + public static function getLogger(category:String = null):ILogger { + if (category) { + return Log.getLogger(category); + } else { + return Log.getLogger(DEFAULT_CATEGORY); + } + } + + public function postMessage(message:String):void { + text = message + "\n" + text; + } + + public function clear():void { + text = ""; + } + + private function handleClick(event:MouseEvent):void{ + clear(); + } + + } +} \ No newline at end of file diff --git a/src/au/com/origo/components/ConsoleLogger.as b/src/au/com/origo/components/ConsoleLogger.as new file mode 100644 index 0000000..54a85c1 --- /dev/null +++ b/src/au/com/origo/components/ConsoleLogger.as @@ -0,0 +1,43 @@ +package au.com.origo.components +{ + import mx.logging.ILogger; + import mx.logging.ILoggingTarget; + import mx.logging.Log; + + public class ConsoleLogger + { + //~ Instance Attributes ----------------------------------------------- + private var logger : ILogger; + + //~ Constructor ------------------------------------------------------- + /** + * SingletonEnforcer parameter ensures that only the getInstance + * method can create an instance of this class. + */ + public function ConsoleLogger(category:String, enforcer:SingletonEnforcer) : void + { + this.logger = Log.getLogger(category); + } + + //~ Methods ----------------------------------------------------------- + public static function getInstance(category:String):ConsoleLogger + { + return new ConsoleLogger(category, new SingletonEnforcer()); + } + + public static function addTarget(target:ILoggingTarget) : void { + Log.addTarget(target); + } + + public static function removeTarget(target:ILoggingTarget) : void { + Log.removeTarget(target); + } + + public function debug(message : String) : void { + this.logger.debug(message); + } + + // other logging methods by level (e.g. warn, error) + } +} +internal class SingletonEnforcer {} \ No newline at end of file diff --git a/src/au/com/origo/components/ConsoleTarget.as b/src/au/com/origo/components/ConsoleTarget.as new file mode 100644 index 0000000..c95a9f5 --- /dev/null +++ b/src/au/com/origo/components/ConsoleTarget.as @@ -0,0 +1,43 @@ +package au.com.origo.components +{ + + import au.com.origo.components.interfaces.IMessageBoard; + + import mx.logging.ILogger; + import mx.logging.LogEvent; + import mx.logging.LogEventLevel; + import mx.logging.targets.LineFormattedTarget; + import mx.resources.IResourceManager; + + public class ConsoleTarget extends LineFormattedTarget + { + [Inject] + public var resourceManager:IResourceManager; + + public var messageTarget:IMessageBoard; + + public function ConsoleTarget() + { + super(); + } + + /** + * Event handler that is called by the logging API -- not to be called directly. + * @param event + */ + public override function logEvent(event : LogEvent) : void { + + // Take care to NOT include mx.*, as code in std lib issues log calls, + // which will call this target, which will send a message to server + // (through rpc operation), which will log to this again, ... until StackOverflowException + var category : String = ILogger(event.target).category; + if (category.indexOf("mx.") != 0) { + trace("event.message" + event.message); + if (messageTarget) { + + messageTarget.postMessage(event.message); + } + } + } + } +} \ No newline at end of file diff --git a/src/au/com/origo/components/EditableLabel.as b/src/au/com/origo/components/EditableLabel.as index 7aaeb5b..098d618 100644 --- a/src/au/com/origo/components/EditableLabel.as +++ b/src/au/com/origo/components/EditableLabel.as @@ -1,87 +1,122 @@ package au.com.origo.components { import au.com.origo.components.skins.EditableLabelSkin; import flash.events.FocusEvent; import flash.events.KeyboardEvent; + import flash.events.MouseEvent; import flash.ui.Keyboard; + import mx.binding.utils.BindingUtils; + import mx.binding.utils.ChangeWatcher; + import mx.managers.IFocusManagerComponent; + import spark.components.RichEditableText; - import spark.components.TextInput; + import spark.components.SkinnableContainer; + import spark.components.TextSelectionHighlighting; [SkinState("editing")] - public class EditableLabel extends TextInput + public class EditableLabel extends SkinnableContainer implements IFocusManagerComponent { private var _editing:Boolean = false; + private var changeWatcher:ChangeWatcher; + + [Bindable] + public var text:String; [SkinPart(required="true")] public var textView:RichEditableText; public function EditableLabel() { super(); - setStyle("skinClass", au.com.origo.components.skins.EditableLabelSkin); - this.focusEnabled = false; + setStyle("skinClass", au.com.origo.components.skins.EditableLabelSkin); + this.focusEnabled = false; + this.mouseFocusEnabled = false; } public function get editing():Boolean { return _editing; } public function set editing(value:Boolean):void { _editing = value; if (!_editing) { this.focusManager.setFocus(this.focusManager.getNextFocusManagerComponent(true)); this.focusManager.hideFocus(); + changeWatcher.reset(textView) + } else { + changeWatcher.unwatch(); } this.invalidateSkinState(); } override protected function getCurrentSkinState():String { return editing ? "editing" : super.getCurrentSkinState(); } protected function focusHandler(event:FocusEvent):void { if (event.type == FocusEvent.FOCUS_IN) { - this.editing = true; + trace("FOCUS_IN"); + //this.editing = true; } else if (event.type == FocusEvent.FOCUS_OUT) { + trace("FOCUS_OUT"); this.editing = false; } event.stopPropagation(); + + } + + public function clickHandler(event:MouseEvent):void { + if (event.type == MouseEvent.DOUBLE_CLICK) { + this.editing = true; + event.stopImmediatePropagation(); + } + this.invalidateSkinState(); + //event.stopImmediatePropagation(); } private function keyboardHandler(event:KeyboardEvent):void { if (event.keyCode == Keyboard.ENTER) { if (this.editing) { this.editing = false; } } + } override protected function partAdded(partName:String, instance:Object):void { - super.partAdded(partName, instance); - if (instance == textView) { + textView.doubleClickEnabled = true; + textView.addEventListener(MouseEvent.DOUBLE_CLICK, clickHandler); + //textView.addEventListener(MouseEvent.CLICK, clickHandler); textView.addEventListener(FocusEvent.FOCUS_IN, focusHandler); textView.addEventListener(FocusEvent.FOCUS_OUT, focusHandler); + changeWatcher = BindingUtils.bindProperty(textView, 'text', this, 'text'); + textView.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); + textView.selectionHighlighting = TextSelectionHighlighting.ALWAYS; } + + super.partAdded(partName, instance); } override protected function partRemoved(partName:String, instance:Object):void { - if (instance == textView) - { - textView.removeEventListener(FocusEvent.FOCUS_IN, focusHandler); + + if (instance == textView) { + //textView.removeEventListener(FocusEvent.FOCUS_IN, focusHandler); + textView.addEventListener(MouseEvent.DOUBLE_CLICK, clickHandler); textView.removeEventListener(FocusEvent.FOCUS_OUT, focusHandler); textView.removeEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); + changeWatcher.unwatch(); } super.partRemoved(partName, instance); } } } \ No newline at end of file diff --git a/src/au/com/origo/components/interfaces/IMessageBoard.as b/src/au/com/origo/components/interfaces/IMessageBoard.as new file mode 100644 index 0000000..ff14665 --- /dev/null +++ b/src/au/com/origo/components/interfaces/IMessageBoard.as @@ -0,0 +1,8 @@ +package au.com.origo.components.interfaces +{ + public interface IMessageBoard + { + function postMessage(message:String):void; + function clear():void; + } +} \ No newline at end of file diff --git a/src/au/com/origo/components/skins/ClearBtnSkin.mxml b/src/au/com/origo/components/skins/ClearBtnSkin.mxml new file mode 100644 index 0000000..76cc3c2 --- /dev/null +++ b/src/au/com/origo/components/skins/ClearBtnSkin.mxml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/halo" + width="17" height="17"> + <fx:Declarations> + <!-- Place non-visual elements (e.g., services, value objects) here --> + </fx:Declarations> + <fx:Script> + <![CDATA[ + + [Embed("assets/clear.png")] + private const ClearIcon:Class; + + ]]> + </fx:Script> + <fx:Metadata> + <![CDATA[ + /** + * @copy spark.skins.spark.ApplicationSkin#hostComponent + */ + [HostComponent("spark.components.Button")] + ]]> + </fx:Metadata> + + <!-- states --> + <s:states> + <s:State name="up" /> + <s:State name="over" /> + <s:State name="down" /> + <s:State name="disabled" /> + </s:states> + <mx:Image smoothBitmapContent="true" + source="{ClearIcon}" + id="clearBtn" + width="17" + maintainAspectRatio="true" + right="10" + top="10" alpha="0.7" alpha.over="1" alpha.down="1" /> +</s:SparkSkin> diff --git a/src/au/com/origo/components/skins/ConsoleSkin.mxml b/src/au/com/origo/components/skins/ConsoleSkin.mxml new file mode 100644 index 0000000..4099f30 --- /dev/null +++ b/src/au/com/origo/components/skins/ConsoleSkin.mxml @@ -0,0 +1,147 @@ +<?xml version="1.0" encoding="utf-8"?> +<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/halo" + addedToStage="sparkskin1_addedToStageHandler(event)" + width="100%" + height="100%" + includeInLayout="false" + > + <fx:Declarations> + <s:AnimateColor id="flashLabel" + colorTo="0x999999" + target="{console}" + duration="300" + colorFrom="0xDDDDDD"/> + <s:Fade id="flashFadeOut" alphaFrom="{console.alpha}" alphaTo="0.5" startDelay="3000" + target="{console}" + duration="500" + /> + <s:Fade id="flashFadeIn" alphaFrom="{console.alpha}" alphaTo="1" + target="{console}" + duration="100" + /> + <s:Fade id="scrollbarFadeOut" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="0.0" startDelay="3000" + target="{ScrollerSkin(scroller.skin).verticalScrollBar}" + duration="500" + /> + <s:Fade id="scrollbarFadeIn" alphaFrom="{ScrollerSkin(scroller.skin).verticalScrollBar.alpha}" alphaTo="1" + target="{ScrollerSkin(scroller.skin).verticalScrollBar}" + duration="100" + /> + </fx:Declarations> + <fx:Metadata> + <![CDATA[ + [HostComponent("au.com.origo.components.Console")] + ]]> + </fx:Metadata> + <fx:Script> + <![CDATA[ + import mx.events.PropertyChangeEvent; + + import spark.effects.AnimateColor; + import spark.skins.spark.ScrollerSkin; + + protected function sparkskin1_addedToStageHandler(event:Event):void { + hostComponent.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, function(event:PropertyChangeEvent):void { + if (event.property == 'text') { + flash(); + } + }); + //clearBtn.addEventListener(MouseEvent.MOUSE_OVER + + } + + public function flash():void { + flashLabel.stop(); + flashLabel.play(); + flashFadeOut.stop(); + flashFadeOut.play(); + flashFadeIn.stop(); + flashFadeIn.play(); + } + + protected function sparkskin1_mouseOverHandler(event:MouseEvent):void { + flashFadeOut.stop(); + flashFadeIn.play(); + scrollbarFadeOut.stop(); + scrollbarFadeIn.play(); + } + + protected function sparkskin1_mouseOutHandler(event:MouseEvent):void { + flashFadeIn.stop(); + flashFadeOut.play(); + scrollbarFadeIn.stop(); + scrollbarFadeOut.play(); + } + + + ]]> + </fx:Script> + + <s:states> + <s:State name="normal"/> + <s:State name="disabled"/> + </s:states> + <mx:VDividedBox height="100%" width="100%" id="container" liveDragging="true"> + <s:Group height="100%" width="100%" id="transparent" mouseChildren="true" /> + <s:Group height="40" width="100%" id="console" mouseChildren="true" minHeight="40" + mouseOver="sparkskin1_mouseOverHandler(event)" + mouseOut="sparkskin1_mouseOutHandler(event)"> + + <s:Rect height="40" width="100%"> + + <s:fill> + <s:LinearGradient rotation="90"> + <s:GradientEntry color="0x333333" alpha="0.6" /> + <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8"/> + </s:LinearGradient> + + </s:fill> + </s:Rect> + + + <s:Rect height="100%" width="100%"> + + <s:fill> + <s:SolidColor color="0xFFFFFF" alpha="0.6" /> + </s:fill> + <s:stroke> + <s:SolidColorStroke weight="1" color="0x5555555" alpha="0.3" /> + </s:stroke> + + </s:Rect> + + <s:Scroller width="100%" id="scroller" height="100%" contentBackgroundColor="0xFFFFFF" contentBackgroundAlpha="0.6"> + <s:Group height="100%" width="100%"> + <s:RichText id="textSpace" + width="100%" + color="0x555555" + left="0" + paddingLeft="14" + paddingTop="14" + paddingBottom="0" + paddingRight="14" + text="{hostComponent.text}" + lineHeight="150%" fontFamily="Lucida Console, monospace"/> + + <s:Button id="clearBtn" skinClass="au.com.origo.components.skins.ClearBtnSkin" right="0" top="0" /> + + + </s:Group> + </s:Scroller> + <s:Rect height="40" width="100%" bottom="0"> + + <s:fill> + <s:LinearGradient rotation="90"> + <s:GradientEntry color="0xFFFFFF" alpha="0" ratio="0.8" /> + <s:GradientEntry color="0x333333" alpha="0.5" /> + + </s:LinearGradient> + + </s:fill> + </s:Rect> + + </s:Group> + </mx:VDividedBox> +</s:SparkSkin> diff --git a/src/au/com/origo/components/skins/EditableLabelSkin.mxml b/src/au/com/origo/components/skins/EditableLabelSkin.mxml index 0942854..b258186 100644 --- a/src/au/com/origo/components/skins/EditableLabelSkin.mxml +++ b/src/au/com/origo/components/skins/EditableLabelSkin.mxml @@ -1,88 +1,96 @@ <?xml version="1.0" encoding="utf-8"?> <!-- ADOBE SYSTEMS INCORPORATED Copyright 2008 Adobe Systems Incorporated All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the license agreement accompanying it. --> <!--- The default skin class for Spark TextInput component. @langversion 3.0 @playerversion Flash 10 @playerversion AIR 1.5 @productversion Flex 4 --> <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" - alpha.disabled="0.5"> + > <fx:Metadata> <![CDATA[ /** * @copy spark.skins.default.ApplicationSkin#hostComponent */ [HostComponent("au.com.origo.components.EditableLabel")] ]]> </fx:Metadata> <fx:Script> - /* Define the skin elements that should not be colorized. */ + <![CDATA[ + import au.com.origo.components.EditableLabel; + +/* Define the skin elements that should not be colorized. */ static private const exclusions:Array = ["background", "textView"]; /** * @copy spark.skins.SparkSkin#colorizeExclusions */ override public function get colorizeExclusions():Array {return exclusions;} /* Define the content fill items that should be colored by the "contentBackgroundColor" style. */ static private const contentFill:Array = ["bgFill"]; /** * @inheritDoc */ override public function get contentItems():Array {return contentFill}; + + + ]]> </fx:Script> <s:states> <s:State name="normal"/> <s:State name="disabled"/> <s:State name="editing"/> </s:states> <!-- border --> <s:Rect left="0" right="0" top="0" bottom="0" id="border" alpha.editing="1" alpha.normal="0"> <s:stroke> <s:LinearGradientStroke rotation="90" weight="1"> <s:GradientEntry color="0x000000" alpha="0.5525" /> <s:GradientEntry color="0x000000" alpha="0.6375" /> </s:LinearGradientStroke> </s:stroke> </s:Rect> <!-- fill --> <!--- Defines the appearance of the TextInput component's background. --> <s:Rect id="background" left="1" right="1" top="1" bottom="1" alpha.editing="1.0" alpha.normal="0"> <s:fill> <!--- Defines the background fill color. --> <s:SolidColor id="bgFill" color="0xFFFFFF" /> </s:fill> </s:Rect> <!-- shadow --> <s:Rect left="1" top="1" right="1" height="1" id="shadow" alpha.editing="1.0" alpha.normal="0"> <s:fill> <s:SolidColor color="0x000000" alpha="0.12" /> </s:fill> </s:Rect> <!-- text --> <s:RichEditableText id="textView" lineBreak="explicit" left="1" right="1" top="1" bottom="1" paddingLeft="3" paddingTop="5" - paddingRight="3" paddingBottom="3" text="{hostComponent.text}" multiline="false" focusEnabled="false"/> + paddingRight="3" paddingBottom="3" + multiline="false" focusEnabled="false" + editable="false" editable.editing="true"/> </s:SparkSkin> diff --git a/src/au/com/origo/utilities/SafeResourceManager.as b/src/au/com/origo/utilities/SafeResourceManager.as new file mode 100644 index 0000000..b8103a0 --- /dev/null +++ b/src/au/com/origo/utilities/SafeResourceManager.as @@ -0,0 +1,186 @@ +package au.com.origo.utilities +{ + import au.com.origo.utilities.events.InfoEvent; + + import flash.events.Event; + import flash.events.IEventDispatcher; + import flash.system.ApplicationDomain; + import flash.system.SecurityDomain; + + import mx.resources.IResourceBundle; + import mx.resources.IResourceManager; + import mx.resources.ResourceManager; + + public class SafeResourceManager implements IResourceManager + { + public static const RESOURCE_NOT_FOUND:String = "resource_not_found"; + + [Inject] + public var eventDispatcher:IEventDispatcher; + + private var resourceManager:IResourceManager; + + public function SafeResourceManager() { + resourceManager = ResourceManager.getInstance(); + } + + public function get localeChain():Array { + return resourceManager.localeChain; + } + + public function set localeChain(value:Array):void { + resourceManager.localeChain = value; + } + + public function loadResourceModule(url:String, update:Boolean=true, applicationDomain:ApplicationDomain=null, securityDomain:SecurityDomain=null):IEventDispatcher { + return resourceManager.loadResourceModule(url, update, applicationDomain, securityDomain); + } + + public function unloadResourceModule(url:String, update:Boolean=true):void { + resourceManager.unloadResourceModule(url, update); + } + + public function addResourceBundle(resourceBundle:IResourceBundle):void { + resourceManager.addResourceBundle(resourceBundle); + } + + public function removeResourceBundle(locale:String, bundleName:String):void { + resourceManager.removeResourceBundle(locale, bundleName); + } + + public function removeResourceBundlesForLocale(locale:String):void { + resourceManager.removeResourceBundlesForLocale(locale); + } + + public function update():void { + resourceManager.update(); + } + + public function getLocales():Array { + return resourceManager.getLocales(); + } + + public function getPreferredLocaleChain():Array { + return resourceManager.getPreferredLocaleChain(); + } + + public function getBundleNamesForLocale(locale:String):Array { + return resourceManager.getBundleNamesForLocale(locale); + } + + public function getResourceBundle(locale:String, bundleName:String):IResourceBundle { + return resourceManager.getResourceBundle(locale, bundleName); + } + + public function findResourceBundleWithResource(bundleName:String, resourceName:String):IResourceBundle { + return resourceManager.findResourceBundleWithResource(bundleName, resourceName); + } + + public function getObject(bundleName:String, resourceName:String, locale:String=null):* { + var value:Object = resourceManager.getObject(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return null; + } + return value; + } + + public function getString(bundleName:String, resourceName:String, parameters:Array=null, locale:String=null):String { + var value:String = resourceManager.getString(bundleName, resourceName, parameters, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return resourceName; + } + return value; + } + + public function getStringArray(bundleName:String, resourceName:String, locale:String=null):Array { + var value:Array = resourceManager.getStringArray(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return null; + } + return value; + } + + public function getNumber(bundleName:String, resourceName:String, locale:String=null):Number { + var value:Number = resourceManager.getNumber(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return 0; + } + return value; + } + + public function getInt(bundleName:String, resourceName:String, locale:String=null):int { + var value:int = resourceManager.getInt(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return 0; + } + return value; + } + + public function getUint(bundleName:String, resourceName:String, locale:String=null):uint { + var value:uint = resourceManager.getUint(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return 0; + } + return value; + } + + public function getBoolean(bundleName:String, resourceName:String, locale:String=null):Boolean { + var value:Boolean = resourceManager.getBoolean(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return false; + } + return value; + } + + public function getClass(bundleName:String, resourceName:String, locale:String=null):Class { + var value:Class = resourceManager.getClass(bundleName, resourceName, locale); + if (!value) { + this.eventDispatcher.dispatchEvent(new InfoEvent(InfoEvent.WARNING, RESOURCE_NOT_FOUND, resourceName)); + return null; + } + return value; + } + + public function installCompiledResourceBundles(applicationDomain:ApplicationDomain, locales:Array, bundleNames:Array):void { + resourceManager.installCompiledResourceBundles(applicationDomain, locales, bundleNames); + } + + public function initializeLocaleChain(compiledLocales:Array):void { + resourceManager.initializeLocaleChain(compiledLocales); + } + + public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void { + eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); + } + + public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void { + eventDispatcher.removeEventListener(type, listener, useCapture); + } + + public function dispatchEvent(event:Event):Boolean { + return eventDispatcher.dispatchEvent(event); + } + + public function hasEventListener(type:String):Boolean { + return eventDispatcher.hasEventListener(type); + } + + public function willTrigger(type:String):Boolean { + return eventDispatcher.willTrigger(type); + } + + public function hasResource(bundleName:String, resourceName:String, locale:String=null):Boolean { + if (resourceManager.getObject(bundleName, resourceName, locale)) { + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/au/com/origo/utilities/Utils.as b/src/au/com/origo/utilities/Utils.as new file mode 100644 index 0000000..d6b6ed5 --- /dev/null +++ b/src/au/com/origo/utilities/Utils.as @@ -0,0 +1,97 @@ +package au.com.origo.utilities +{ + public class Utils + { + import flash.utils.getQualifiedClassName; + + + + + public function Utils() + { + + } + + /** + * Returns the name of the class without its package name from any passed in object + * @param object Object to get the class name from + */ + static public function getClassName(object:*):String { + var qualifiedName:String = getQualifiedClassName(object); + return qualifiedNameToClassName(qualifiedName); + } + + static public function qualifiedNameToClassName(qualifiedName:String):String { + var parts:Array = qualifiedName.split('::'); + if (parts.length == 2) { + // Handle package.path::Class + return parts[1]; + } else if (parts.length == 1) { + // Handle top level packages + // String, Number etc + return parts[0]; + } else { + // parts.length > 2 means we have a malformed package/class name + throw new Error("Malformed package::class name: " + qualifiedName); + } + } + + /** + * Takes a string name and adds a numeric suffix one larger than any existing numeric suffix. + * If no suffix, adds _2 to name. + * Note it doesn't add _1 because this is confusing: + * we naturally start counting from 1: + * <pre> + * + * Object + * Object_1 <- Confusing. Is this the first object? No, the other one is. hmm + * VS. + * Object + * Object_2 <- More clear. Ahh... it's the second object with this name. + * </pre> + * + * Additionally, this is the same method as other apps doing this, + * which I guess is argument enough. + * + * @param name String to append the numeric suffix to + * @return name with its incremented suffix + * + * <pre><code> + * Util.incrementNameNumber("name") // name_2 + * Util.incrementNameNumber("name_1") // name_2 + * Util.incrementNameNumber("name_10") // name_11 + * Util.incrementNameNumber("name20") // name21 + * Util.incrementNameNumber("name0") // name1 + * <code></pre> + */ + static public function incrementNameNumber(name:String):String { + var nameResult:String = name; + var findLastDigit:RegExp = new RegExp("([\\d]+)$"); + var lastDigitsMatches:Array = name.match(findLastDigit); + + if (!lastDigitsMatches) { + // No match + nameResult = name + "_2"; + } else if (lastDigitsMatches.length == 2) { + //Found trailing digits + //(for some reason length == 2 when it correctly identifies + // a match :/ ) + + //strip off trailing digits + nameResult = name.replace(findLastDigit, ""); + + //Convert string to integer + var index:uint = parseInt(lastDigitsMatches[0]); + + //Append incremented digit to result + nameResult = nameResult + (index + 1); + } else { + //Something wrong with regex + throw new Error("The regular expression " + findLastDigit + + " is incorrect. Found " + lastDigitsMatches.length + " 'final' digits.") + } + return nameResult; + } + + } +} \ No newline at end of file diff --git a/src/au/com/origo/utilities/events/InfoEvent.as b/src/au/com/origo/utilities/events/InfoEvent.as new file mode 100644 index 0000000..3187379 --- /dev/null +++ b/src/au/com/origo/utilities/events/InfoEvent.as @@ -0,0 +1,65 @@ +package au.com.origo.utilities.events +{ + import flash.events.ErrorEvent; + import flash.events.Event; + + public class InfoEvent extends Event + { + public var message:String; + public var params:Array; + + /** + * Some information that the user should be notified of. eg + * <ul> + * <li> Action performed with success + * <li> An event occurred + * </ul> + */ + static public const USER_INFO:String = "userInfoFlareEvent"; + + /** + * Some error that the user should be notified of. eg + * <ul> + * <li> Connection failed + * <li> Invalid user text input + * <li> + * </ul> + */ + static public const USER_ERROR:String = "userErrorFlareEvent"; + + /** + * Programmer specific information for debugging purposes + * + */ + static public const DEBUG:String = "debugFlareEvent"; + + /** + * Programmer specific information for debugging purposes + * + */ + static public const WARNING:String = "warningFlareEvent"; + + /** + * Programmer specific information for debugging purposes. + * Means there is something wrong with the app and it cannot/should not continue. + * Program should shut down if it recieves this event. + */ + static public const FATAL:String = "fatalFlareEvent"; + + /** + * @param type Type of event. If one of the constants defined in this class should be picked up by Logger & ResourceManager + * @param message Optional Textual message of event. Use ResourceManager property references (as defined in locale) if using LogCommand. + * @param rest other parameters for substitution by ResourceManager.getString + */ + public function InfoEvent(type:String, message:String="", ... rest:*) { + this.params = rest; + this.message = message; + super(type, true); + } + + override public function clone():Event { + return new InfoEvent(this.type, message, params); + } + + } +} \ No newline at end of file diff --git a/src/tests/TestUtils.as b/src/tests/TestUtils.as new file mode 100644 index 0000000..c28fe41 --- /dev/null +++ b/src/tests/TestUtils.as @@ -0,0 +1,58 @@ +package tests +{ + import au.com.origo.utilities.Utils; + + import flexunit.framework.Assert; + + import mx.containers.Accordion; + import mx.controls.Button; + + public class TestUtils + { + // Reference declaration for class to test + private var classToTestRef:Utils; + public function TestUtils() + { + } + + [Test] + public function testGetClassName():void { + Assert.assertEquals(Utils.getClassName(Button), 'Button'); + Assert.assertEquals(Utils.getClassName(new Accordion()), 'Accordion'); + Assert.assertEquals(Utils.getClassName('sdfsdf'), 'String'); + Assert.assertEquals(Utils.getClassName(null), 'null'); + } + + + + [Test] + public function testIncrementNameNumber():void { + Assert.assertEquals(Utils.incrementNameNumber('name'), 'name_2'); + Assert.assertEquals(Utils.incrementNameNumber('name_1'), 'name_2'); + Assert.assertEquals(Utils.incrementNameNumber('name_0'), 'name_1'); + Assert.assertEquals(Utils.incrementNameNumber('name_00'), 'name_1'); + Assert.assertEquals(Utils.incrementNameNumber('name_000'), 'name_1'); + Assert.assertEquals(Utils.incrementNameNumber('name_-1'), 'name_-2'); + Assert.assertEquals(Utils.incrementNameNumber('name_100'), 'name_101'); + Assert.assertEquals(Utils.incrementNameNumber('name0'), 'name1'); + Assert.assertEquals(Utils.incrementNameNumber('name00'), 'name1'); + Assert.assertEquals(Utils.incrementNameNumber('name000'), 'name1'); + Assert.assertEquals(Utils.incrementNameNumber('name001'), 'name2'); + Assert.assertEquals(Utils.incrementNameNumber('name0011'), 'name12'); + Assert.assertEquals(Utils.incrementNameNumber('name100'), 'name101'); + Assert.assertEquals(Utils.incrementNameNumber('name000_000'), 'name000_1'); + Assert.assertEquals(Utils.incrementNameNumber('name234'), 'name235'); + Assert.assertEquals(Utils.incrementNameNumber('name_234_101'), 'name_234_102'); + Assert.assertEquals(Utils.incrementNameNumber('name_234_101_'), 'name_234_101__2'); + Assert.assertEquals(Utils.incrementNameNumber('name_234_101_z'), 'name_234_101_z_2'); + Assert.assertEquals(Utils.incrementNameNumber('Generic Node 7'), 'Generic Node 8'); + Assert.assertEquals(Utils.incrementNameNumber('Generic Node_8'), 'Generic Node_9'); + } + + + [Test(expects="Error")] + public function testIncrementNameNumberNull():void { + Utils.incrementNameNumber(null); + } + } +} \ No newline at end of file
timoxley/Components
4c4e42c262d3d60ea19604877874ba12126e837c
Added EditableLabel component
diff --git a/README.textile b/README.textile index d7ef754..08683ba 100644 --- a/README.textile +++ b/README.textile @@ -1,3 +1,6 @@ -h1. EditableLabel +h1. Flex Components + + +h3. EditableLabel Flex control. Extends Text Input so that it appears as a label until given focus. diff --git a/src/au/com/origo/components/EditableLabel.as b/src/au/com/origo/components/EditableLabel.as new file mode 100644 index 0000000..7aaeb5b --- /dev/null +++ b/src/au/com/origo/components/EditableLabel.as @@ -0,0 +1,87 @@ +package au.com.origo.components +{ + import au.com.origo.components.skins.EditableLabelSkin; + + import flash.events.FocusEvent; + import flash.events.KeyboardEvent; + import flash.ui.Keyboard; + + import spark.components.RichEditableText; + import spark.components.TextInput; + + [SkinState("editing")] + + public class EditableLabel extends TextInput + { + private var _editing:Boolean = false; + + [SkinPart(required="true")] + public var textView:RichEditableText; + + public function EditableLabel() { + super(); + setStyle("skinClass", au.com.origo.components.skins.EditableLabelSkin); + this.focusEnabled = false; + } + + public function get editing():Boolean { + return _editing; + } + + public function set editing(value:Boolean):void { + _editing = value; + + if (!_editing) { + this.focusManager.setFocus(this.focusManager.getNextFocusManagerComponent(true)); + this.focusManager.hideFocus(); + } + this.invalidateSkinState(); + } + + override protected function getCurrentSkinState():String { + return editing ? "editing" : super.getCurrentSkinState(); + } + + protected function focusHandler(event:FocusEvent):void { + + if (event.type == FocusEvent.FOCUS_IN) { + this.editing = true; + + } else if (event.type == FocusEvent.FOCUS_OUT) { + this.editing = false; + } + event.stopPropagation(); + } + + private function keyboardHandler(event:KeyboardEvent):void { + + if (event.keyCode == Keyboard.ENTER) { + if (this.editing) { + this.editing = false; + } + } + } + + override protected function partAdded(partName:String, instance:Object):void { + + super.partAdded(partName, instance); + + if (instance == textView) { + textView.addEventListener(FocusEvent.FOCUS_IN, focusHandler); + textView.addEventListener(FocusEvent.FOCUS_OUT, focusHandler); + textView.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); + } + } + + override protected function partRemoved(partName:String, instance:Object):void { + if (instance == textView) + { + textView.removeEventListener(FocusEvent.FOCUS_IN, focusHandler); + textView.removeEventListener(FocusEvent.FOCUS_OUT, focusHandler); + textView.removeEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler); + } + + super.partRemoved(partName, instance); + } + } +} \ No newline at end of file diff --git a/src/au/com/origo/components/skins/EditableLabelSkin.mxml b/src/au/com/origo/components/skins/EditableLabelSkin.mxml new file mode 100644 index 0000000..0942854 --- /dev/null +++ b/src/au/com/origo/components/skins/EditableLabelSkin.mxml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + +ADOBE SYSTEMS INCORPORATED +Copyright 2008 Adobe Systems Incorporated +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file +in accordance with the terms of the license agreement accompanying it. + +--> +<!--- The default skin class for Spark TextInput component. + +@langversion 3.0 +@playerversion Flash 10 +@playerversion AIR 1.5 +@productversion Flex 4 +--> +<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + alpha.disabled="0.5"> + + <fx:Metadata> + <![CDATA[ + /** + * @copy spark.skins.default.ApplicationSkin#hostComponent + */ + [HostComponent("au.com.origo.components.EditableLabel")] + ]]> + </fx:Metadata> + + <fx:Script> + /* Define the skin elements that should not be colorized. */ + static private const exclusions:Array = ["background", "textView"]; + + /** + * @copy spark.skins.SparkSkin#colorizeExclusions + */ + override public function get colorizeExclusions():Array {return exclusions;} + + /* Define the content fill items that should be colored by the "contentBackgroundColor" style. */ + static private const contentFill:Array = ["bgFill"]; + + /** + * @inheritDoc + */ + override public function get contentItems():Array {return contentFill}; + </fx:Script> + + <s:states> + <s:State name="normal"/> + <s:State name="disabled"/> + <s:State name="editing"/> + </s:states> + + <!-- border --> + <s:Rect left="0" right="0" top="0" bottom="0" id="border" alpha.editing="1" alpha.normal="0"> + <s:stroke> + <s:LinearGradientStroke rotation="90" weight="1"> + <s:GradientEntry color="0x000000" alpha="0.5525" /> + <s:GradientEntry color="0x000000" alpha="0.6375" /> + </s:LinearGradientStroke> + </s:stroke> + </s:Rect> + + <!-- fill --> + <!--- Defines the appearance of the TextInput component's background. --> + <s:Rect id="background" left="1" right="1" top="1" bottom="1" alpha.editing="1.0" alpha.normal="0"> + <s:fill> + <!--- Defines the background fill color. --> + <s:SolidColor id="bgFill" color="0xFFFFFF" /> + </s:fill> + </s:Rect> + + <!-- shadow --> + <s:Rect left="1" top="1" right="1" height="1" id="shadow" alpha.editing="1.0" alpha.normal="0"> + <s:fill> + <s:SolidColor color="0x000000" alpha="0.12" /> + </s:fill> + </s:Rect> + + <!-- text --> + <s:RichEditableText id="textView" lineBreak="explicit" + left="1" right="1" top="1" bottom="1" + paddingLeft="3" paddingTop="5" + paddingRight="3" paddingBottom="3" text="{hostComponent.text}" multiline="false" focusEnabled="false"/> + +</s:SparkSkin>
flextao/inflector
087f786e4e0e0627457eac5b747dd94865ebc249
added a simple README
diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..095c96f --- /dev/null +++ b/README.rdoc @@ -0,0 +1,22 @@ + += inflector + +Inflector is a Java port of the excellent Inflector class in ruby's ActiveSupport library. Forked from jactiveresource: jactiveresource.org + +The methods ported: + + singularize + pluralize + underscore + underscorize + dasherize + +See org.jactiveresource.Inflector.java for details. + +== License + +See LICENSE.TXT + +== Author + +Jared Crapo
flextao/inflector
bdc6edf9860017c938dcd01fad8d248b59c1a2c6
packaged Inflector which is ported from rails from jactiveresource
diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..cd3540a --- /dev/null +++ b/.classpath @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" path="test"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="lib" path="lib/junit-4.4.jar"/> + <classpathentry kind="output" path="targets/classes"/> +</classpath> diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ce2dc8 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +targets \ No newline at end of file diff --git a/.project b/.project new file mode 100644 index 0000000..2ddf912 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>inflector</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..4d3836d --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright (c) 2008, Jared Crapo All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name of jactiveresource.org nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..e263c5b --- /dev/null +++ b/build.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project name="inflector" basedir="." default="jar"> + <property name="libs.dir" value="${basedir}/lib" /> + <property name="src.dir" value="${basedir}/src" /> + <property name="test.dir" value="${basedir}/test" /> + + <property name="targets.dir" value="${basedir}/targets" /> + <property name="targets.classes.dir" value="${targets.dir}/classes" /> + <property name="targets.test.classes.dir" value="${targets.dir}/test-classes" /> + <property name="targets.dist.dir" value="${targets.dir}" /> + <property name="targets.test-reports.dir" value="${targets.dir}/test-reports" /> + + <target name="test" depends="clean, compile, compile-test, jt" /> + <target name="jar" depends="test, xjar, srcjar" /> + + <target name="clean"> + <delete dir="${targets.dir}" /> + </target> + + <target name="compile"> + <mkdir dir="${targets.classes.dir}" /> + <javac srcdir="${src.dir}" destdir="${targets.classes.dir}" debug="true" encoding="utf-8" failonerror="true"> + <classpath> + <fileset dir="${libs.dir}"> + <include name="*.jar" /> + </fileset> + </classpath> + <include name="**/*.java" /> + </javac> + </target> + + <target name="compile-test"> + <mkdir dir="${targets.test.classes.dir}" /> + <javac srcdir="${test.dir}" destdir="${targets.test.classes.dir}" debug="true" encoding="utf-8" failonerror="true"> + <classpath> + <fileset dir="${libs.dir}"> + <include name="*.jar" /> + </fileset> + <pathelement location="${targets.classes.dir}" /> + </classpath> + <include name="**/*.java" /> + </javac> + </target> + + <target name="xjar"> + <jar destfile="${targets.dist.dir}/inflector.jar"> + <fileset dir="${targets.classes.dir}" /> + </jar> + </target> + + <target name="srcjar"> + <jar destfile="${targets.dist.dir}/inflector-src.jar"> + <fileset dir="${src.dir}" /> + </jar> + </target> + <target name="jt"> + <mkdir dir="${targets.dir}/test-reports" /> + <junit printsummary="yes" showoutput="yes" haltonfailure="yes"> + <formatter type="xml" /> + <classpath> + <pathelement location="${targets.classes.dir}" /> + <pathelement location="${targets.test.classes.dir}" /> + <fileset dir="${libs.dir}"> + <include name="*.jar"/> + </fileset> + </classpath> + <batchtest todir="${targets.test-reports.dir}"> + <fileset dir="${test.dir}"> + <include name="**/Test*.java" /> + </fileset> + </batchtest> + </junit> + </target> +</project> diff --git a/lib/junit-4.4.jar b/lib/junit-4.4.jar new file mode 100644 index 0000000..649b0b3 Binary files /dev/null and b/lib/junit-4.4.jar differ diff --git a/src/org/jactiveresource/Inflector.java b/src/org/jactiveresource/Inflector.java new file mode 100644 index 0000000..202da37 --- /dev/null +++ b/src/org/jactiveresource/Inflector.java @@ -0,0 +1,268 @@ +/* + +Copyright (c) 2008, Jared Crapo All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name of jactiveresource.org nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + */ + +package org.jactiveresource; + + +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * a port of the excellent Inflector class in ruby's ActiveSupport library + * + * @version $LastChangedRevision: 5 $ <br> + * $LastChangedDate: 2008-05-03 13:44:24 -0600 (Sat, 03 May 2008) $ + * @author $LastChangedBy: jared $ + */ +public class Inflector { + + public static String camelize( String word, boolean firstLetterInUppercase ) { + + return null; + } + + private static Pattern underscorePattern = Pattern.compile( "_" ); + + /** + * replace underscores with dashes in a string + * + * @param word + * @return + */ + public static String dasherize( String word ) { + Matcher m = underscorePattern.matcher( word ); + return m.replaceAll( "-" ); + } + + private static Pattern dashPattern = Pattern.compile( "-" ); + + /** + * replace dashes with underscores in a string + * + * @param word + * @return + */ + public static String underscorize( String word ) { + Matcher m = dashPattern.matcher( word ); + return m.replaceAll( "_" ); + } + + private static Pattern doubleColonPattern = Pattern.compile( "::" ); + private static Pattern underscore1Pattern = Pattern + .compile( "([A-Z]+)([A-Z][a-z])" ); + private static Pattern underscore2Pattern = Pattern + .compile( "([a-z\\d])([A-Z])" ); + + /** + * The reverse of camelize. Makes an underscored form from the expression in + * the string. + * + * Changes '::' to '/' to convert namespaces to paths. + * + * @param word + * @return + */ + public static String underscore( String word ) { + + String out; + Matcher m; + + m = doubleColonPattern.matcher( word ); + out = m.replaceAll( "/" ); + + m = underscore1Pattern.matcher( out ); + out = m.replaceAll( "$1_$2" ); + + m = underscore2Pattern.matcher( out ); + out = m.replaceAll( "$1_$2" ); + + out = underscorize( out ); + + return out.toLowerCase(); + } + + /** + * return the plural form of word + * + * @param word + * @return + */ + public static String pluralize( String word ) { + String out = new String( word ); + if ( ( out.length() == 0 ) + || ( !uncountables.contains( word.toLowerCase() ) ) ) { + for ( ReplacementRule r : plurals ) { + if ( r.find( word ) ) { + out = r.replace( word ); + break; + } + } + } + return out; + } + + /** + * return the singular form of word + * + * @param word + * @return + */ + public static String singularize( String word ) { + String out = new String( word ); + if ( ( out.length() == 0 ) + || ( !uncountables.contains( out.toLowerCase() ) ) ) { + for ( ReplacementRule r : singulars ) { + if ( r.find( word ) ) { + out = r.replace( word ); + break; + } + } + } + return out; + } + + public static void irregular( String singular, String plural ) { + String regexp, repl; + + if ( singular.substring( 0, 1 ).toUpperCase().equals( + plural.substring( 0, 1 ).toUpperCase() ) ) { + // singular and plural start with the same letter + regexp = "(?i)(" + singular.substring( 0, 1 ) + ")" + + singular.substring( 1 ) + "$"; + repl = "$1" + plural.substring( 1 ); + plurals.add( 0, new ReplacementRule( regexp, repl ) ); + + regexp = "(?i)(" + plural.substring( 0, 1 ) + ")" + + plural.substring( 1 ) + "$"; + repl = "$1" + singular.substring( 1 ); + singulars.add( 0, new ReplacementRule( regexp, repl ) ); + } else { + // singular and plural don't start with the same letter + regexp = singular.substring( 0, 1 ).toUpperCase() + "(?i)" + + singular.substring( 1 ) + "$"; + repl = plural.substring( 0, 1 ).toUpperCase() + + plural.substring( 1 ); + plurals.add( 0, new ReplacementRule( regexp, repl ) ); + + regexp = singular.substring( 0, 1 ).toLowerCase() + "(?i)" + + singular.substring( 1 ) + "$"; + repl = plural.substring( 0, 1 ).toLowerCase() + + plural.substring( 1 ); + plurals.add( 0, new ReplacementRule( regexp, repl ) ); + + regexp = plural.substring( 0, 1 ).toUpperCase() + "(?i)" + + plural.substring( 1 ) + "$"; + repl = singular.substring( 0, 1 ).toUpperCase() + + singular.substring( 1 ); + singulars.add( 0, new ReplacementRule( regexp, repl ) ); + + regexp = plural.substring( 0, 1 ).toLowerCase() + "(?i)" + + plural.substring( 1 ) + "$"; + repl = singular.substring( 0, 1 ).toLowerCase() + + singular.substring( 1 ); + singulars.add( 0, new ReplacementRule( regexp, repl ) ); + } + } + + private static ArrayList<ReplacementRule> plurals; + private static ArrayList<ReplacementRule> singulars; + private static ArrayList<String> uncountables; + + static { + plurals = new ArrayList<ReplacementRule>( 17 ); + plurals.add( 0, new ReplacementRule( "$", "s" ) ); + plurals.add( 0, new ReplacementRule( "(?i)s$", "s" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(ax|test)is$", "$1es" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(octop|vir)us$", "$1i" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(alias|status)$", "$1es" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(bu)s$", "$1es" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(buffal|tomat)o$", "$1oes" ) ); + plurals.add( 0, new ReplacementRule( "(?i)([ti])um$", "$1a" ) ); + plurals.add( 0, new ReplacementRule( "sis$", "ses" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(?:([^f])fe|([lr])f)$", "$1$2ves" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(hive)$", "$1s" ) ); + plurals.add( 0, new ReplacementRule( "(?i)([^aeiouy]|qu)y$", "$1ies" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(x|ch|ss|sh)$", "$1es" ) ); + plurals.add( 0, + new ReplacementRule( "(?i)(matr|vert|ind)(?:ix|ex)$", "$1ices" ) ); + plurals.add( 0, new ReplacementRule( "(?i)([m|l])ouse$", "$1ice" ) ); + plurals.add( 0, new ReplacementRule( "^(?i)(ox)$", "$1en" ) ); + plurals.add( 0, new ReplacementRule( "(?i)(quiz)$", "$1zes" ) ); + + singulars = new ArrayList<ReplacementRule>( 24 ); + singulars.add( 0, new ReplacementRule( "s$", "" ) ); + singulars.add( 0, new ReplacementRule( "(n)ews$", "$1ews" ) ); + singulars.add( 0, new ReplacementRule( "([ti])a$", "$1um" ) ); + singulars.add( 0, new ReplacementRule( + "((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", + "$1$2sis" ) ); + singulars.add( 0, new ReplacementRule( "(^analy)ses$", "$1sis" ) ); + singulars.add( 0, new ReplacementRule( "([^f])ves$", "$1fe" ) ); + singulars.add( 0, new ReplacementRule( "(hive)s$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(tive)s$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "([lr])ves$", "$1f" ) ); + singulars.add( 0, new ReplacementRule( "([^aeiouy]|qu)ies$", "$1y" ) ); + singulars.add( 0, new ReplacementRule( "(s)eries$", "$1eries" ) ); + singulars.add( 0, new ReplacementRule( "(m)ovies$", "$1ovie" ) ); + singulars.add( 0, new ReplacementRule( "(x|ch|ss|sh)es$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "([m|l])ice$", "$1ouse" ) ); + singulars.add( 0, new ReplacementRule( "(bus)es$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(o)es$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(shoe)s$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(cris|ax|test)es$", "$1is" ) ); + singulars.add( 0, new ReplacementRule( "(octop|vir)i$", "$1us" ) ); + singulars.add( 0, new ReplacementRule( "(alias|status)es$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(ox)en$", "$1" ) ); + singulars.add( 0, new ReplacementRule( "(virt|ind)ices$", "$1ex" ) ); + singulars.add( 0, new ReplacementRule( "(matr)ices$", "$1ix" ) ); + singulars.add( 0, new ReplacementRule( "(quiz)zes$", "$1" ) ); + + irregular( "person", "people" ); + irregular( "man", "men" ); + irregular( "child", "children" ); + irregular( "sex", "sexes" ); + irregular( "move", "moves" ); + irregular( "cow", "kine" ); + + uncountables = new ArrayList<String>( 8 ); + uncountables.add( "equipment" ); + uncountables.add( "information" ); + uncountables.add( "rice" ); + uncountables.add( "money" ); + uncountables.add( "species" ); + uncountables.add( "series" ); + uncountables.add( "fish" ); + uncountables.add( "sheep" ); + } +} diff --git a/src/org/jactiveresource/ReplacementRule.java b/src/org/jactiveresource/ReplacementRule.java new file mode 100644 index 0000000..ba56780 --- /dev/null +++ b/src/org/jactiveresource/ReplacementRule.java @@ -0,0 +1,59 @@ +/* + +Copyright (c) 2008, Jared Crapo All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name of jactiveresource.org nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +*/ + +package org.jactiveresource; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ReplacementRule { + + private Pattern p; + private Matcher m; + private String r; + + public ReplacementRule( String regexp, String replacement ) { + p = Pattern.compile( regexp ); + r = replacement; + } + + public boolean find( String word ) { + m = p.matcher( word ); + return m.find(); + } + + public String replace( String word ) { + m = p.matcher( word ); + return m.replaceAll( this.r ); + } +} \ No newline at end of file diff --git a/test/org/jactiveresource/TestInflector.java b/test/org/jactiveresource/TestInflector.java new file mode 100644 index 0000000..f1e0f37 --- /dev/null +++ b/test/org/jactiveresource/TestInflector.java @@ -0,0 +1,95 @@ +/* + +Copyright (c) 2008, Jared Crapo All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name of jactiveresource.org nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +*/ + +package org.jactiveresource; + +import static org.junit.Assert.*; +import static org.jactiveresource.Inflector.*; +import org.junit.Test; + +/** + * + * @version $LastChangedRevision: 5 $ <br> + * $LastChangedDate: 2008-05-03 13:44:24 -0600 (Sat, 03 May 2008) $ + * @author $LastChangedBy: jared $ + */ +public class TestInflector { + + @Test + public void underscoreTest() { + assertEquals( "asset", underscore( "Asset" ) ); + assertEquals( "asset_type", underscore( "AssetType" ) ); + assertEquals( "active_record/errors", + underscore( "ActiveRecord::Errors" ) ); + } + + @Test + public void pluralizeTest() { + assertEquals( "assets", pluralize( "asset" ) ); + assertEquals( "Assets", pluralize( "Asset" ) ); + assertEquals( "guts", pluralize( "guts" ) ); + // assertEquals( "GUTs", pluralize( "GUTS" ) ); + assertEquals( "axes", pluralize( "axis" ) ); + assertEquals( "Axes", pluralize( "Axis" ) ); + assertEquals( "calves", pluralize( "calf" ) ); + assertEquals( "halves", pluralize( "half" ) ); + assertEquals( "Halves", pluralize( "Half" ) ); + assertEquals( "AXes", pluralize( "AXIS" ) ); + assertEquals( "Hives", pluralize( "Hive" ) ); + assertEquals( "QUEries", pluralize( "QUEry" ) ); + assertEquals( "rice", pluralize( "rice" ) ); + assertEquals( "oxen", pluralize( "ox" ) ); + assertEquals( "Oxen", pluralize( "Ox" ) ); + assertEquals( "matrices", pluralize( "matrix" ) ); + assertEquals( "indices", pluralize( "index" ) ); + assertEquals( "indices", pluralize( "indix" ) ); + assertEquals( "people", pluralize( "person" ) ); + assertEquals( "People", pluralize( "Person" ) ); + assertEquals( "Kine", pluralize( "Cow" ) ); + assertEquals( "kine", pluralize( "cow" ) ); + } + + @Test + public void singularizeTest() { + assertEquals( "duck", singularize( "ducks" ) ); + assertEquals( "thesis", singularize( "theses" ) ); + assertEquals( "diagnosis", singularize( "diagnoses" ) ); + assertEquals( "analysis", singularize( "analyses" ) ); + assertEquals( "half", singularize( "halves" ) ); + assertEquals( "alias", singularize( "aliases" ) ); + assertEquals( "person", singularize( "people" ) ); + assertEquals( "Person", singularize( "People" ) ); + assertEquals( "cow", singularize( "kine" ) ); + assertEquals( "Cow", singularize( "Kine" ) ); + } +} diff --git a/test/org/jactiveresource/TestReplacementRule.java b/test/org/jactiveresource/TestReplacementRule.java new file mode 100644 index 0000000..120cc57 --- /dev/null +++ b/test/org/jactiveresource/TestReplacementRule.java @@ -0,0 +1,58 @@ +/* + +Copyright (c) 2008, Jared Crapo All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name of jactiveresource.org nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +*/ + +package org.jactiveresource; + +import static org.junit.Assert.assertEquals; + +import org.jactiveresource.ReplacementRule; +import org.junit.Test; + +/** + * test the ReplacementRule class + * + * @version $LastChangedRevision: 5 $ <br> + * $LastChangedDate: 2008-05-03 13:44:24 -0600 (Sat, 03 May 2008) $ + * @author $LastChangedBy: jared $ + */ +public class TestReplacementRule { + + @Test + public void replaceTest() { + ReplacementRule r; + + r = new ReplacementRule( "$", "s" ); + assertEquals( true, r.find("dog") ); + assertEquals( "dogs", r.replace("dog") ); + } +}
todeus/tcc
b4ffc5aeade4edc9a0e2fc519f64f68457bd79b0
Надеюсь прокатит на зачет ;)
diff --git a/parser.cpp b/parser.cpp index 4d492f0..e66703b 100755 --- a/parser.cpp +++ b/parser.cpp @@ -1,427 +1,427 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; - s->next(); - obj = ParseState(); + + obj = ParseBlock(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; if( (s->get().getSource() == "int")|| (s->get().getSource() == "float")|| (s->get().getSource() == "void") ) return ParseVarDecl(); if(s->get().getSource() == "while") return ParseWhile(); if(s->get().getSource() == "do") return ParseDo(); if(s->get().getSource() == "for") return ParseFor(); if(s->get().getSource() == "if") return ParseIf(); if(s->get().getType() == ttBegin) return ParseBlock(); else { r = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); return (SynExpr*)r; } } SynExpr * Parser::ParseVarDecl() { Token name; Token type; Token value_; SynNode * param; SynNode * body; type = s->get(); s->next(); name = s->get(); s->next(); if(s->get().getType()==ttLeftBracket) { param = ParseParam(); if(s->get().getType()!=ttBegin) s->error(-13,"",s->getPos()); body = ParseBlock(); } else { param = NULL; body = NULL; if(s->get().getType()==ttAssign) { s->next(); if((s->get().getType()==ttInt)||(s->get().getType()==ttInt16)||(s->get().getType()==ttReal)) value_=s->get(); else s->error(-8,"",s->getPos()); } } s->next(); return new SynVarDecl(type,name,value_,param,body); } SynExpr * Parser::ParseParam() { SynBlockParam * block; SynNode * st; s->next(); block = new SynBlockParam(); while(s->get().getType()!=ttRightBracket) { if(s->get().getType()!=ttKeyword) s->error(-10,"",s->getPos()); st = ParseVarDecl(); block->push_back(st); if((s->get().getType()!=ttRightBracket)&&(s->get().getType()!=ttComma)) s->error(-14,"",s->getPos()); if(s->get().getType()==ttComma) { s->next(); } } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseBlock() { SynBlock * block; SynNode * st; s->next(); block = new SynBlock(); - while(s->get().getType()!=ttEnd) + while((s->get().getType()!=ttEnd)&&(s->get().getType()!=ttEOF)) { st = ParseState(); block->push_back(st); } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseIf() { SynNode * condition; SynNode * operation; SynNode * alt_operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); if(s->get().getSource() == "else") { s->next(); alt_operation = ParseState(); return (SynExpr*)new SynIf(condition,operation,alt_operation); } return (SynExpr*)new SynIf(condition,operation,NULL); } SynExpr * Parser::ParseWhile() { SynNode * condition; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynWhile(condition,operation); } SynExpr * Parser::ParseDo() { SynNode * condition; SynNode * operation; s->next(); operation = ParseState(); if(s->get().getSource()!="while") s->error(-9,"",s->getPos()); s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); return (SynExpr*)new SynDo(condition,operation); } SynExpr * Parser::ParseFor() { SynNode * condition1; SynNode * condition2; SynNode * condition3; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition1 = ParseVarDecl(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); condition2 = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); condition3 = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynFor(condition1,condition2,condition3,operation); } diff --git a/test11.txt b/test11.txt index 9d23de6..ef96b88 100644 --- a/test11.txt +++ b/test11.txt @@ -1,7 +1,14 @@ -for(int i=1;i<10;i=i+1) -{ - if(i%2==0) - x=10; - else - x=0; +int x; +void main(){ + for(int i=1;i<10;i=i+1) + { + if(i%2==0) + x=10; + else + x=0; + while(true) + do + a<<b+c-d=f==w+=f*s; + while(false); + } }
todeus/tcc
bf04e9aae100960351ceefa90e6fe321bc610ced
Строит дерево для FOR
diff --git a/node.cpp b/node.cpp index 852c27e..66af681 100755 --- a/node.cpp +++ b/node.cpp @@ -1,306 +1,355 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; void SynNode::print(int n) { } SynNode::SynNode() { } SynNode::~SynNode() { } SynExpr::SynExpr() { } SynExpr::~SynExpr() { } SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } void SynBinOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } void SynUnOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { token = t; } SynVar::~SynVar() { } void SynVar::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynConst::SynConst(Token t) { token = t; } SynConst::~SynConst() { } void SynConst::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynWhile::SynWhile(SynNode* con, SynNode* op) { condition = con; operation = op; } SynWhile::~SynWhile() { } void SynWhile::print(int n) { cout << "[WHILE]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } } SynDo::SynDo(SynNode* con, SynNode* op) { condition = con; operation = op; } SynDo::~SynDo() { } void SynDo::print(int n) { cout << "[DO]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } } SynIf::SynIf(SynNode* con, SynNode* op, SynNode* alt_op) { condition = con; operation = op; alt_operation = alt_op; } SynIf::~SynIf() { } void SynIf::print(int n) { cout << "[IF]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } if(alt_operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; alt_operation->print(n+1); } } +SynFor::SynFor(SynNode* con1, SynNode* con2, SynNode* con3, SynNode* op) +{ + condition1 = con1; + condition2 = con2; + condition3 = con3; + operation = op; +} +SynFor::~SynFor() +{ +} + +void SynFor::print(int n) +{ + cout << "[FOR]" << endl; + + if(condition1) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + condition1->print(n+1); + } + if(condition2) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + condition2->print(n+1); + } + if(condition3) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + condition3->print(n+1); + } + + if(operation) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + operation->print(n+1); + } + +} + + + SynBlock::SynBlock() { } SynBlock::~SynBlock() { } void SynBlock::push_back(SynNode *st) { body.push_back(st); } void SynBlock::print(int n) { SynNode * c; cout << "[BLOCK {...}]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; c->print(n+1); } body.pop_back(); } } SynBlockParam::SynBlockParam() { } SynBlockParam::~SynBlockParam() { } void SynBlockParam::push_back(SynNode *st) { body.push_back(st); } void SynBlockParam::print(int n) { SynNode * c; cout << "[BLOCK (...)]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; c->print(n+1); } body.pop_back(); } } SynVarDecl::SynVarDecl(Token tp ,Token t, Token val, SynNode *p, SynNode *b) { name = t; param = p; value_ = val; body = b; type = tp; } SynVarDecl::~SynVarDecl() { } void SynVarDecl::print(int n) { cout << "[DECLARATION]" << endl; for(int i=0;i<n;i++) cout<<" "; cout<<" '-[" << type.getSource() << "]" << endl; for(int i=0;i<n;i++) cout<<" "; cout<<" '-[" << name.getSource() << "]" << endl; if(value_.getSource()!="") { for(int i=0;i<n;i++) cout<<" "; cout<<" '-[" << value_.getSource() << "]" << endl; } if(param) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; param->print(n+1); } if(body) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; body->print(n+1); } } diff --git a/node.h b/node.h index ff4fb9c..121c15a 100755 --- a/node.h +++ b/node.h @@ -1,145 +1,158 @@ #ifndef NODE_H #define NODE_H #include <vector> #include "scanner.h" class SynNode { public: SynNode(); ~SynNode(); virtual void print(int n); }; class SynExpr:public SynNode { public: SynExpr(); ~SynExpr(); }; class SynWhile:public SynExpr { public: SynWhile(SynNode* con, SynNode* op); ~SynWhile(); void print(int n); private: SynNode * condition; SynNode * operation; }; +class SynFor:public SynExpr +{ +public: + SynFor(SynNode* con1, SynNode* con2, SynNode* con3, SynNode* op); + ~SynFor(); + void print(int n); +private: + SynNode * condition1; + SynNode * condition2; + SynNode * condition3; + SynNode * operation; +}; + class SynDo:public SynExpr { public: SynDo(SynNode* con, SynNode* op); ~SynDo(); void print(int n); private: SynNode * condition; SynNode * operation; }; class SynIf:public SynExpr { public: SynIf(SynNode* con, SynNode* op, SynNode* alt_op); ~SynIf(); void print(int n); private: SynNode * condition; SynNode * operation; SynNode * alt_operation; }; class SynVarDecl:public SynExpr { public: SynVarDecl(Token tp, Token t, Token val, SynNode* p, SynNode* b); ~SynVarDecl(); void print(int n); private: Token name; Token type; Token value_; SynNode * param; SynNode * body; }; class SynBlock:public SynExpr { public: SynBlock(); ~SynBlock(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; class SynBlockParam:public SynExpr { public: SynBlockParam(); ~SynBlockParam(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; class SynBinOp:public SynExpr { public: SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); void print(int n); private: SynNode * left; SynNode * right; Token token; }; class SynUnOp:public SynExpr { public: SynUnOp(Token t, SynNode* l); ~SynUnOp(); void print(int n); private: SynNode * left; Token token; }; class SynVar:public SynExpr { public: SynVar(Token t); ~SynVar(); void print(int n); private: Token token; }; class SynConst:public SynExpr { public: SynConst(Token t); ~SynConst(); void print(int n); private: Token token; }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index b9daa5e..4d492f0 100755 --- a/parser.cpp +++ b/parser.cpp @@ -1,397 +1,427 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); obj = ParseState(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; if( (s->get().getSource() == "int")|| (s->get().getSource() == "float")|| (s->get().getSource() == "void") ) return ParseVarDecl(); if(s->get().getSource() == "while") return ParseWhile(); if(s->get().getSource() == "do") return ParseDo(); + if(s->get().getSource() == "for") return ParseFor(); if(s->get().getSource() == "if") return ParseIf(); if(s->get().getType() == ttBegin) return ParseBlock(); else { r = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); return (SynExpr*)r; } } SynExpr * Parser::ParseVarDecl() { Token name; Token type; Token value_; SynNode * param; SynNode * body; type = s->get(); s->next(); name = s->get(); s->next(); if(s->get().getType()==ttLeftBracket) { param = ParseParam(); if(s->get().getType()!=ttBegin) s->error(-13,"",s->getPos()); body = ParseBlock(); } else { param = NULL; body = NULL; if(s->get().getType()==ttAssign) { s->next(); if((s->get().getType()==ttInt)||(s->get().getType()==ttInt16)||(s->get().getType()==ttReal)) value_=s->get(); else s->error(-8,"",s->getPos()); } } s->next(); return new SynVarDecl(type,name,value_,param,body); } SynExpr * Parser::ParseParam() { SynBlockParam * block; SynNode * st; s->next(); block = new SynBlockParam(); while(s->get().getType()!=ttRightBracket) { if(s->get().getType()!=ttKeyword) s->error(-10,"",s->getPos()); st = ParseVarDecl(); block->push_back(st); if((s->get().getType()!=ttRightBracket)&&(s->get().getType()!=ttComma)) s->error(-14,"",s->getPos()); if(s->get().getType()==ttComma) { s->next(); } } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseBlock() { SynBlock * block; SynNode * st; s->next(); block = new SynBlock(); while(s->get().getType()!=ttEnd) { st = ParseState(); block->push_back(st); } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseIf() { SynNode * condition; SynNode * operation; SynNode * alt_operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); if(s->get().getSource() == "else") { s->next(); alt_operation = ParseState(); return (SynExpr*)new SynIf(condition,operation,alt_operation); } return (SynExpr*)new SynIf(condition,operation,NULL); } SynExpr * Parser::ParseWhile() { SynNode * condition; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynWhile(condition,operation); } SynExpr * Parser::ParseDo() { SynNode * condition; SynNode * operation; s->next(); operation = ParseState(); if(s->get().getSource()!="while") s->error(-9,"",s->getPos()); s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); return (SynExpr*)new SynDo(condition,operation); } + +SynExpr * Parser::ParseFor() +{ + SynNode * condition1; + SynNode * condition2; + SynNode * condition3; + SynNode * operation; + + s->next(); + if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); + s->next(); + condition1 = ParseVarDecl(); + + if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); + s->next(); + condition2 = ParseExpr(); + + if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); + s->next(); + condition3 = ParseExpr(); + + + if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); + s->next(); + operation = ParseState(); + + return (SynExpr*)new SynFor(condition1,condition2,condition3,operation); + +} diff --git a/parser.h b/parser.h index 4a43802..3c849e7 100644 --- a/parser.h +++ b/parser.h @@ -1,37 +1,38 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); SynExpr * ParseState(); SynExpr * ParseBlock(); SynExpr * ParseIf(); SynExpr * ParseWhile(); SynExpr * ParseDo(); + SynExpr * ParseFor(); SynExpr * ParseVarDecl(); SynExpr * ParseParam(); private: SynNode * obj; }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index 811f858..9d23de6 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1,7 @@ -do { int x=10; a+b; } while(a>b); +for(int i=1;i<10;i=i+1) +{ + if(i%2==0) + x=10; + else + x=0; +}
todeus/tcc
051c83941a8f737127a16170581afdacf6f1022c
Строит дерево для DO .. WHILE Исправлены некоторые ошибки
diff --git a/KA.h b/KA.h old mode 100644 new mode 100755 diff --git a/Makefile b/Makefile old mode 100644 new mode 100755 diff --git a/README b/README old mode 100644 new mode 100755 diff --git a/main.cpp b/main.cpp index 26f55b2..b553fe7 100755 --- a/main.cpp +++ b/main.cpp @@ -1,63 +1,65 @@ #include <iostream> #include <fstream> #include "scanner.h" #include "parser.h" using namespace std; int main(int argc, char* argv[]) { if(argc==1) { std::cout << "*****************************" << std::endl; std::cout << " Todeus C Compiler " << std::endl; std::cout << " " << std::endl; std::cout << " Author: Mikhail S. Pavlov " << std::endl; std::cout << " " << std::endl; std::cout << " Group: 238 " << std::endl; std::cout << "*****************************" << std::endl; } //if(argc==2) { try { Scanner * s = new Scanner("test11.txt"); /* //Вывод результата работы лексического анализатора(список лексем) while(s->next().getType()!=ttEOF) { std::cout << s->get().print() << endl; } */ Parser * p = new Parser(s); } catch(MyEx error) { switch(error.code) { case -1: cout << "Error: File \'" << error.str << "\' not found!"; break; case 0: cout << "Error: Unknown symbol \'"<< error.str <<"\'!"; break; case 1: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Constant is too long!"; break; case 202: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Unclosed string literal!"; break; case 203: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in numeric constant!"; break; case 204: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in char constant!"; break; case 206: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error escape sequence!"; break; + case -8: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Must be numeric"; break; + case -9: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected 'while'"; break; case -10: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected declaration"; break; case -11: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected '('"; break; case -12: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ')'"; break; case -13: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected '{'"; break; case -14: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ','"; break; case -15: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ';'"; break; default: cout << "Error: Unknown error(" << error.code << ")"; break; } } } return 0; } diff --git a/myEx.h b/myEx.h old mode 100644 new mode 100755 diff --git a/node.cpp b/node.cpp index 534298b..852c27e 100755 --- a/node.cpp +++ b/node.cpp @@ -1,270 +1,306 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; void SynNode::print(int n) { } SynNode::SynNode() { } SynNode::~SynNode() { } SynExpr::SynExpr() { } SynExpr::~SynExpr() { } SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } void SynBinOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } void SynUnOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { token = t; } SynVar::~SynVar() { } void SynVar::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynConst::SynConst(Token t) { token = t; } SynConst::~SynConst() { } void SynConst::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynWhile::SynWhile(SynNode* con, SynNode* op) { condition = con; operation = op; } SynWhile::~SynWhile() { } void SynWhile::print(int n) { cout << "[WHILE]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } } +SynDo::SynDo(SynNode* con, SynNode* op) +{ + condition = con; + operation = op; +} +SynDo::~SynDo() +{ +} + +void SynDo::print(int n) +{ + cout << "[DO]" << endl; + + if(condition) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + condition->print(n+1); + } + if(operation) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + operation->print(n+1); + } + +} + SynIf::SynIf(SynNode* con, SynNode* op, SynNode* alt_op) { condition = con; operation = op; alt_operation = alt_op; } SynIf::~SynIf() { } void SynIf::print(int n) { cout << "[IF]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } if(alt_operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; alt_operation->print(n+1); } } SynBlock::SynBlock() { } SynBlock::~SynBlock() { } void SynBlock::push_back(SynNode *st) { body.push_back(st); } void SynBlock::print(int n) { SynNode * c; cout << "[BLOCK {...}]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; c->print(n+1); } body.pop_back(); } } SynBlockParam::SynBlockParam() { } SynBlockParam::~SynBlockParam() { } void SynBlockParam::push_back(SynNode *st) { body.push_back(st); } void SynBlockParam::print(int n) { SynNode * c; cout << "[BLOCK (...)]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; c->print(n+1); } body.pop_back(); } } -SynVarDecl::SynVarDecl(Token tp ,Token t, SynNode *p, SynNode *b) +SynVarDecl::SynVarDecl(Token tp ,Token t, Token val, SynNode *p, SynNode *b) { name = t; param = p; + value_ = val; body = b; type = tp; } SynVarDecl::~SynVarDecl() { } void SynVarDecl::print(int n) { cout << "[DECLARATION]" << endl; for(int i=0;i<n;i++) cout<<" "; cout<<" '-[" << type.getSource() << "]" << endl; for(int i=0;i<n;i++) cout<<" "; cout<<" '-[" << name.getSource() << "]" << endl; - + if(value_.getSource()!="") + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-[" << value_.getSource() << "]" << endl; + } if(param) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; param->print(n+1); } if(body) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; body->print(n+1); } } diff --git a/node.h b/node.h index 50c3db4..ff4fb9c 100755 --- a/node.h +++ b/node.h @@ -1,133 +1,145 @@ #ifndef NODE_H #define NODE_H #include <vector> #include "scanner.h" class SynNode { public: SynNode(); ~SynNode(); virtual void print(int n); }; class SynExpr:public SynNode { public: SynExpr(); ~SynExpr(); }; class SynWhile:public SynExpr { public: SynWhile(SynNode* con, SynNode* op); ~SynWhile(); void print(int n); private: SynNode * condition; SynNode * operation; }; +class SynDo:public SynExpr +{ +public: + SynDo(SynNode* con, SynNode* op); + ~SynDo(); + void print(int n); +private: + SynNode * condition; + SynNode * operation; +}; + class SynIf:public SynExpr { public: SynIf(SynNode* con, SynNode* op, SynNode* alt_op); ~SynIf(); void print(int n); private: SynNode * condition; SynNode * operation; SynNode * alt_operation; }; class SynVarDecl:public SynExpr { public: - SynVarDecl(Token tp, Token t, SynNode* p, SynNode* b); + SynVarDecl(Token tp, Token t, Token val, SynNode* p, SynNode* b); ~SynVarDecl(); void print(int n); private: Token name; Token type; + Token value_; SynNode * param; SynNode * body; }; class SynBlock:public SynExpr { public: SynBlock(); ~SynBlock(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; class SynBlockParam:public SynExpr { public: SynBlockParam(); ~SynBlockParam(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; class SynBinOp:public SynExpr { public: SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); void print(int n); private: SynNode * left; SynNode * right; Token token; }; class SynUnOp:public SynExpr { public: SynUnOp(Token t, SynNode* l); ~SynUnOp(); void print(int n); private: SynNode * left; Token token; }; class SynVar:public SynExpr { public: SynVar(Token t); ~SynVar(); void print(int n); private: Token token; }; class SynConst:public SynExpr { public: SynConst(Token t); ~SynConst(); void print(int n); private: Token token; }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index a970e66..b9daa5e 100755 --- a/parser.cpp +++ b/parser.cpp @@ -1,361 +1,397 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); obj = ParseState(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; - if(s->get().getSource() == "int")return ParseVarDecl(); + if( + (s->get().getSource() == "int")|| + (s->get().getSource() == "float")|| + (s->get().getSource() == "void") + ) + return ParseVarDecl(); if(s->get().getSource() == "while") return ParseWhile(); + if(s->get().getSource() == "do") return ParseDo(); if(s->get().getSource() == "if") return ParseIf(); if(s->get().getType() == ttBegin) return ParseBlock(); else { r = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); return (SynExpr*)r; } } SynExpr * Parser::ParseVarDecl() { Token name; Token type; + Token value_; SynNode * param; SynNode * body; type = s->get(); s->next(); name = s->get(); s->next(); if(s->get().getType()==ttLeftBracket) { param = ParseParam(); if(s->get().getType()!=ttBegin) s->error(-13,"",s->getPos()); body = ParseBlock(); } else { param = NULL; body = NULL; - } - return new SynVarDecl(type,name,param,body); + if(s->get().getType()==ttAssign) + { + s->next(); + if((s->get().getType()==ttInt)||(s->get().getType()==ttInt16)||(s->get().getType()==ttReal)) + value_=s->get(); + else + s->error(-8,"",s->getPos()); + } + } + s->next(); + return new SynVarDecl(type,name,value_,param,body); } SynExpr * Parser::ParseParam() { SynBlockParam * block; SynNode * st; s->next(); block = new SynBlockParam(); while(s->get().getType()!=ttRightBracket) { if(s->get().getType()!=ttKeyword) s->error(-10,"",s->getPos()); st = ParseVarDecl(); block->push_back(st); if((s->get().getType()!=ttRightBracket)&&(s->get().getType()!=ttComma)) s->error(-14,"",s->getPos()); if(s->get().getType()==ttComma) { s->next(); - //cout << s->get().getSource() << endl; } } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseBlock() { SynBlock * block; SynNode * st; s->next(); block = new SynBlock(); while(s->get().getType()!=ttEnd) { st = ParseState(); block->push_back(st); } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseIf() { SynNode * condition; SynNode * operation; SynNode * alt_operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); if(s->get().getSource() == "else") { s->next(); alt_operation = ParseState(); return (SynExpr*)new SynIf(condition,operation,alt_operation); } return (SynExpr*)new SynIf(condition,operation,NULL); } SynExpr * Parser::ParseWhile() { SynNode * condition; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynWhile(condition,operation); } + +SynExpr * Parser::ParseDo() +{ + SynNode * condition; + SynNode * operation; + + s->next(); + operation = ParseState(); + if(s->get().getSource()!="while") s->error(-9,"",s->getPos()); + s->next(); + if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); + s->next(); + condition = ParseExpr(); + if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); + s->next(); + if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); + + + return (SynExpr*)new SynDo(condition,operation); + +} diff --git a/parser.h b/parser.h index 03a2e4d..4a43802 100644 --- a/parser.h +++ b/parser.h @@ -1,36 +1,37 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); SynExpr * ParseState(); SynExpr * ParseBlock(); SynExpr * ParseIf(); SynExpr * ParseWhile(); + SynExpr * ParseDo(); SynExpr * ParseVarDecl(); SynExpr * ParseParam(); private: SynNode * obj; }; #endif // PARSER_H diff --git a/scanner.cpp b/scanner.cpp old mode 100644 new mode 100755 diff --git a/scanner.h b/scanner.h old mode 100644 new mode 100755 diff --git a/struct.h b/struct.h old mode 100644 new mode 100755 diff --git a/tcc.pro b/tcc.pro old mode 100644 new mode 100755 diff --git a/test11.txt b/test11.txt index 6fc533f..811f858 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1 @@ -int foo() { a=b; } +do { int x=10; a+b; } while(a>b); diff --git a/token.cpp b/token.cpp old mode 100644 new mode 100755 diff --git a/token.h b/token.h old mode 100644 new mode 100755
todeus/tcc
28784c4621e85ee492ecf32377910740b2213c09
Парсит любые функции.
diff --git a/main.cpp b/main.cpp old mode 100644 new mode 100755 index 4b19799..26f55b2 --- a/main.cpp +++ b/main.cpp @@ -1,60 +1,63 @@ #include <iostream> #include <fstream> #include "scanner.h" #include "parser.h" using namespace std; int main(int argc, char* argv[]) { if(argc==1) { std::cout << "*****************************" << std::endl; std::cout << " Todeus C Compiler " << std::endl; std::cout << " " << std::endl; std::cout << " Author: Mikhail S. Pavlov " << std::endl; std::cout << " " << std::endl; std::cout << " Group: 238 " << std::endl; std::cout << "*****************************" << std::endl; } //if(argc==2) { try { Scanner * s = new Scanner("test11.txt"); /* //Вывод результата работы лексического анализатора(список лексем) while(s->next().getType()!=ttEOF) { std::cout << s->get().print() << endl; } */ Parser * p = new Parser(s); } catch(MyEx error) { switch(error.code) { case -1: cout << "Error: File \'" << error.str << "\' not found!"; break; case 0: cout << "Error: Unknown symbol \'"<< error.str <<"\'!"; break; case 1: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Constant is too long!"; break; case 202: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Unclosed string literal!"; break; case 203: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in numeric constant!"; break; case 204: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in char constant!"; break; case 206: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error escape sequence!"; break; + case -10: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected declaration"; break; case -11: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected '('"; break; case -12: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ')'"; break; + case -13: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected '{'"; break; + case -14: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ','"; break; case -15: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ';'"; break; default: cout << "Error: Unknown error(" << error.code << ")"; break; } } } return 0; } diff --git a/node.cpp b/node.cpp old mode 100644 new mode 100755 index 17baf09..534298b --- a/node.cpp +++ b/node.cpp @@ -1,201 +1,270 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; void SynNode::print(int n) { } SynNode::SynNode() { } SynNode::~SynNode() { } SynExpr::SynExpr() { } SynExpr::~SynExpr() { } SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } void SynBinOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } void SynUnOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { token = t; } SynVar::~SynVar() { } void SynVar::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynConst::SynConst(Token t) { token = t; } SynConst::~SynConst() { } void SynConst::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynWhile::SynWhile(SynNode* con, SynNode* op) { condition = con; operation = op; } SynWhile::~SynWhile() { } void SynWhile::print(int n) { cout << "[WHILE]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } } SynIf::SynIf(SynNode* con, SynNode* op, SynNode* alt_op) { condition = con; operation = op; alt_operation = alt_op; } SynIf::~SynIf() { } void SynIf::print(int n) { cout << "[IF]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } if(alt_operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; alt_operation->print(n+1); } } SynBlock::SynBlock() { } SynBlock::~SynBlock() { } void SynBlock::push_back(SynNode *st) { body.push_back(st); } void SynBlock::print(int n) { SynNode * c; cout << "[BLOCK {...}]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; - //condition->print(n+1); c->print(n+1); } body.pop_back(); } } + + +SynBlockParam::SynBlockParam() +{ +} +SynBlockParam::~SynBlockParam() +{ +} +void SynBlockParam::push_back(SynNode *st) +{ + body.push_back(st); +} +void SynBlockParam::print(int n) +{ + SynNode * c; + + cout << "[BLOCK (...)]" << endl; + + while(!body.empty()) + { + c = body.back(); + if(c) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + c->print(n+1); + } + body.pop_back(); + } + +} + +SynVarDecl::SynVarDecl(Token tp ,Token t, SynNode *p, SynNode *b) +{ + name = t; + param = p; + body = b; + type = tp; +} +SynVarDecl::~SynVarDecl() +{ +} + +void SynVarDecl::print(int n) +{ + cout << "[DECLARATION]" << endl; + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-[" << type.getSource() << "]" << endl; + + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-[" << name.getSource() << "]" << endl; + + if(param) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + param->print(n+1); + } + if(body) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + body->print(n+1); + } +} diff --git a/node.h b/node.h old mode 100644 new mode 100755 index 7248004..50c3db4 --- a/node.h +++ b/node.h @@ -1,106 +1,133 @@ #ifndef NODE_H #define NODE_H #include <vector> #include "scanner.h" class SynNode { public: SynNode(); ~SynNode(); virtual void print(int n); }; class SynExpr:public SynNode { public: SynExpr(); ~SynExpr(); }; class SynWhile:public SynExpr { public: SynWhile(SynNode* con, SynNode* op); ~SynWhile(); void print(int n); private: SynNode * condition; SynNode * operation; }; class SynIf:public SynExpr { public: SynIf(SynNode* con, SynNode* op, SynNode* alt_op); ~SynIf(); void print(int n); private: SynNode * condition; SynNode * operation; SynNode * alt_operation; }; +class SynVarDecl:public SynExpr +{ +public: + SynVarDecl(Token tp, Token t, SynNode* p, SynNode* b); + ~SynVarDecl(); + void print(int n); +private: + Token name; + Token type; + SynNode * param; + SynNode * body; +}; + + class SynBlock:public SynExpr { public: SynBlock(); ~SynBlock(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; +class SynBlockParam:public SynExpr +{ +public: + SynBlockParam(); + ~SynBlockParam(); + void print(int n); + void push_back(SynNode* st); + vector <SynNode*> body; + int x; +//private: + +}; + class SynBinOp:public SynExpr { public: SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); void print(int n); private: SynNode * left; SynNode * right; Token token; }; class SynUnOp:public SynExpr { public: SynUnOp(Token t, SynNode* l); ~SynUnOp(); void print(int n); private: SynNode * left; Token token; }; class SynVar:public SynExpr { public: SynVar(Token t); ~SynVar(); void print(int n); private: Token token; }; class SynConst:public SynExpr { public: SynConst(Token t); ~SynConst(); void print(int n); private: Token token; }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp old mode 100644 new mode 100755 index 15a5999..a970e66 --- a/parser.cpp +++ b/parser.cpp @@ -1,309 +1,361 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); obj = ParseState(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); - if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); + if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; + + if(s->get().getSource() == "int")return ParseVarDecl(); if(s->get().getSource() == "while") return ParseWhile(); if(s->get().getSource() == "if") return ParseIf(); - else if(s->get().getType() == ttBegin) return ParseBlock(); + if(s->get().getType() == ttBegin) return ParseBlock(); else { r = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); return (SynExpr*)r; } } +SynExpr * Parser::ParseVarDecl() +{ + Token name; + Token type; + SynNode * param; + SynNode * body; + + type = s->get(); + s->next(); + name = s->get(); + s->next(); + if(s->get().getType()==ttLeftBracket) + { + param = ParseParam(); + if(s->get().getType()!=ttBegin) s->error(-13,"",s->getPos()); + body = ParseBlock(); + + } + else + { + param = NULL; + body = NULL; + } + + return new SynVarDecl(type,name,param,body); +} + +SynExpr * Parser::ParseParam() +{ + SynBlockParam * block; + SynNode * st; + + s->next(); + block = new SynBlockParam(); + while(s->get().getType()!=ttRightBracket) + { + if(s->get().getType()!=ttKeyword) s->error(-10,"",s->getPos()); + st = ParseVarDecl(); + block->push_back(st); + if((s->get().getType()!=ttRightBracket)&&(s->get().getType()!=ttComma)) s->error(-14,"",s->getPos()); + if(s->get().getType()==ttComma) + { + s->next(); + //cout << s->get().getSource() << endl; + } + } + s->next(); + return (SynExpr*)block; +} + SynExpr * Parser::ParseBlock() { SynBlock * block; SynNode * st; s->next(); block = new SynBlock(); while(s->get().getType()!=ttEnd) { st = ParseState(); block->push_back(st); } s->next(); return (SynExpr*)block; } SynExpr * Parser::ParseIf() { SynNode * condition; SynNode * operation; SynNode * alt_operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); if(s->get().getSource() == "else") { s->next(); alt_operation = ParseState(); return (SynExpr*)new SynIf(condition,operation,alt_operation); } return (SynExpr*)new SynIf(condition,operation,NULL); } SynExpr * Parser::ParseWhile() { SynNode * condition; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynWhile(condition,operation); } diff --git a/parser.h b/parser.h index d416d3e..03a2e4d 100644 --- a/parser.h +++ b/parser.h @@ -1,34 +1,36 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); SynExpr * ParseState(); SynExpr * ParseBlock(); SynExpr * ParseIf(); SynExpr * ParseWhile(); + SynExpr * ParseVarDecl(); + SynExpr * ParseParam(); private: SynNode * obj; }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index 158cebe..6fc533f 100644 --- a/test11.txt +++ b/test11.txt @@ -1,19 +1 @@ -while(true) -{ - i+=2; - - if(a>b){ - x*=10; - } else { - a=c; - } - - { - if (true) - a=x; - else - b=x; - n=i+j; - } - ++j; -} +int foo() { a=b; }
todeus/tcc
b1f94997c4dd571c89bd83670a1e629a9dd7d85a
Строит дерево IF ... ELSE
diff --git a/node.cpp b/node.cpp index 92ac7c8..17baf09 100644 --- a/node.cpp +++ b/node.cpp @@ -1,163 +1,201 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; void SynNode::print(int n) { } SynNode::SynNode() { } SynNode::~SynNode() { } SynExpr::SynExpr() { } SynExpr::~SynExpr() { } SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } void SynBinOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } void SynUnOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { token = t; } SynVar::~SynVar() { } void SynVar::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynConst::SynConst(Token t) { token = t; } SynConst::~SynConst() { } void SynConst::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynWhile::SynWhile(SynNode* con, SynNode* op) { condition = con; operation = op; } SynWhile::~SynWhile() { } void SynWhile::print(int n) { cout << "[WHILE]" << endl; if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; condition->print(n+1); } if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; operation->print(n+1); } } +SynIf::SynIf(SynNode* con, SynNode* op, SynNode* alt_op) +{ + condition = con; + operation = op; + alt_operation = alt_op; +} +SynIf::~SynIf() +{ +} + +void SynIf::print(int n) +{ + cout << "[IF]" << endl; + + if(condition) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + condition->print(n+1); + } + if(operation) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + operation->print(n+1); + } + if(alt_operation) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + alt_operation->print(n+1); + } + +} + SynBlock::SynBlock() { } SynBlock::~SynBlock() { } void SynBlock::push_back(SynNode *st) { body.push_back(st); } void SynBlock::print(int n) { SynNode * c; cout << "[BLOCK {...}]" << endl; while(!body.empty()) { c = body.back(); if(c) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; //condition->print(n+1); c->print(n+1); } body.pop_back(); } } diff --git a/node.h b/node.h index e900a21..7248004 100644 --- a/node.h +++ b/node.h @@ -1,95 +1,106 @@ #ifndef NODE_H #define NODE_H #include <vector> #include "scanner.h" class SynNode { public: SynNode(); ~SynNode(); virtual void print(int n); }; class SynExpr:public SynNode { public: SynExpr(); ~SynExpr(); }; class SynWhile:public SynExpr { public: SynWhile(SynNode* con, SynNode* op); ~SynWhile(); void print(int n); private: SynNode * condition; SynNode * operation; }; +class SynIf:public SynExpr +{ +public: + SynIf(SynNode* con, SynNode* op, SynNode* alt_op); + ~SynIf(); + void print(int n); +private: + SynNode * condition; + SynNode * operation; + SynNode * alt_operation; +}; class SynBlock:public SynExpr { public: SynBlock(); ~SynBlock(); void print(int n); void push_back(SynNode* st); vector <SynNode*> body; int x; //private: }; class SynBinOp:public SynExpr { public: SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); void print(int n); private: SynNode * left; SynNode * right; Token token; }; class SynUnOp:public SynExpr { public: SynUnOp(Token t, SynNode* l); ~SynUnOp(); void print(int n); private: SynNode * left; Token token; }; class SynVar:public SynExpr { public: SynVar(Token t); ~SynVar(); void print(int n); private: Token token; }; class SynConst:public SynExpr { public: SynConst(Token t); ~SynConst(); void print(int n); private: Token token; }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index d14ddad..15a5999 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,282 +1,309 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); obj = ParseState(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| (s->get().getType()==ttModAssign) ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; if(s->get().getSource() == "while") return ParseWhile(); + if(s->get().getSource() == "if") return ParseIf(); else if(s->get().getType() == ttBegin) return ParseBlock(); else { r = ParseExpr(); if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); s->next(); return (SynExpr*)r; } } SynExpr * Parser::ParseBlock() { SynBlock * block; SynNode * st; s->next(); block = new SynBlock(); while(s->get().getType()!=ttEnd) { st = ParseState(); block->push_back(st); } s->next(); return (SynExpr*)block; } +SynExpr * Parser::ParseIf() +{ + SynNode * condition; + SynNode * operation; + SynNode * alt_operation; + + s->next(); + if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); + s->next(); + condition = ParseExpr(); + if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); + s->next(); + operation = ParseState(); + if(s->get().getSource() == "else") + { + s->next(); + alt_operation = ParseState(); + return (SynExpr*)new SynIf(condition,operation,alt_operation); + } + + + return (SynExpr*)new SynIf(condition,operation,NULL); + +} + + SynExpr * Parser::ParseWhile() { SynNode * condition; SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); operation = ParseState(); return (SynExpr*)new SynWhile(condition,operation); } diff --git a/parser.h b/parser.h index 09e9f12..d416d3e 100644 --- a/parser.h +++ b/parser.h @@ -1,33 +1,34 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); SynExpr * ParseState(); SynExpr * ParseBlock(); + SynExpr * ParseIf(); SynExpr * ParseWhile(); private: SynNode * obj; }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index ff3fefa..158cebe 100644 --- a/test11.txt +++ b/test11.txt @@ -1,9 +1,19 @@ while(true) { i+=2; - { + + if(a>b){ x*=10; + } else { + a=c; + } + + { + if (true) + a=x; + else + b=x; + n=i+j; } - n=i+j; ++j; }
todeus/tcc
a3f3243b7a2b78261cff0c8861c92c488dd9a3fc
Строит дерево для блока {...} Исправлены мелкие косяки
diff --git a/main.cpp b/main.cpp index 35bb061..4b19799 100644 --- a/main.cpp +++ b/main.cpp @@ -1,57 +1,60 @@ #include <iostream> #include <fstream> #include "scanner.h" #include "parser.h" using namespace std; int main(int argc, char* argv[]) { if(argc==1) { std::cout << "*****************************" << std::endl; std::cout << " Todeus C Compiler " << std::endl; std::cout << " " << std::endl; std::cout << " Author: Mikhail S. Pavlov " << std::endl; std::cout << " " << std::endl; std::cout << " Group: 238 " << std::endl; std::cout << "*****************************" << std::endl; } //if(argc==2) { try { Scanner * s = new Scanner("test11.txt"); /* //Вывод результата работы лексического анализатора(список лексем) while(s->next().getType()!=ttEOF) { std::cout << s->get().print() << endl; } */ Parser * p = new Parser(s); } catch(MyEx error) { switch(error.code) { case -1: cout << "Error: File \'" << error.str << "\' not found!"; break; case 0: cout << "Error: Unknown symbol \'"<< error.str <<"\'!"; break; case 1: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Constant is too long!"; break; case 202: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Unclosed string literal!"; break; case 203: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in numeric constant!"; break; case 204: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in char constant!"; break; - case 206: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error escape ...!"; break; + case 206: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error escape sequence!"; break; + case -11: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected '('"; break; + case -12: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ')'"; break; + case -15: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error: expected ';'"; break; default: cout << "Error: Unknown error(" << error.code << ")"; break; } } } return 0; } diff --git a/node.cpp b/node.cpp index c4b4c41..92ac7c8 100644 --- a/node.cpp +++ b/node.cpp @@ -1,142 +1,163 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; void SynNode::print(int n) { } -SynExpr::SynExpr() +SynNode::SynNode() { - left = 0; - right = 0; } -SynExpr::~SynExpr() +SynNode::~SynNode() { } -/* -SynState::SynState() +SynExpr::SynExpr() { - left = 0; - right = 0; } - -SynState::~SynState() +SynExpr::~SynExpr() { } -*/ SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } void SynBinOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } void SynUnOp::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { - left = 0; - right = 0; token = t; } SynVar::~SynVar() { } void SynVar::print(int n) { cout << "[" << token.getSource() << "]" << endl; } SynConst::SynConst(Token t) { - left = 0; - right = 0; token = t; } SynConst::~SynConst() { } void SynConst::print(int n) { cout << "[" << token.getSource() << "]" << endl; } -SynWhile::SynWhile(SynNode* l, SynNode* r) +SynWhile::SynWhile(SynNode* con, SynNode* op) { - left = l; - right = r; + condition = con; + operation = op; } SynWhile::~SynWhile() { } void SynWhile::print(int n) { cout << "[WHILE]" << endl; - if(left) + if(condition) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; - left->print(n+1); + condition->print(n+1); } - if(right) + if(operation) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; - right->print(n+1); + operation->print(n+1); + } + +} + +SynBlock::SynBlock() +{ +} +SynBlock::~SynBlock() +{ +} +void SynBlock::push_back(SynNode *st) +{ + body.push_back(st); +} +void SynBlock::print(int n) +{ + SynNode * c; + + cout << "[BLOCK {...}]" << endl; + + while(!body.empty()) + { + c = body.back(); + if(c) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + //condition->print(n+1); + c->print(n+1); + } + body.pop_back(); } } diff --git a/node.h b/node.h index cf56712..e900a21 100644 --- a/node.h +++ b/node.h @@ -1,74 +1,95 @@ #ifndef NODE_H #define NODE_H +#include <vector> #include "scanner.h" class SynNode { - public: +public: + SynNode(); + ~SynNode(); virtual void print(int n); }; -/* -class SynState:public SynNode -{ - public: - SynNode* left; - SynNode* right; - SynState(); - ~SynState(); -}; -*/ - class SynExpr:public SynNode { - public: - SynNode * left; - SynNode * right; - Token token; +public: SynExpr(); ~SynExpr(); }; class SynWhile:public SynExpr { - public: - SynWhile(SynNode* l, SynNode* r); +public: + SynWhile(SynNode* con, SynNode* op); ~SynWhile(); void print(int n); +private: + SynNode * condition; + SynNode * operation; +}; + + +class SynBlock:public SynExpr +{ +public: + SynBlock(); + ~SynBlock(); + void print(int n); + void push_back(SynNode* st); + vector <SynNode*> body; + int x; +//private: + }; class SynBinOp:public SynExpr { - public: +public: SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); void print(int n); +private: + SynNode * left; + SynNode * right; + Token token; + }; class SynUnOp:public SynExpr { - public: +public: SynUnOp(Token t, SynNode* l); ~SynUnOp(); void print(int n); +private: + SynNode * left; + Token token; + }; class SynVar:public SynExpr { - public: +public: SynVar(Token t); ~SynVar(); void print(int n); +private: + Token token; + }; class SynConst:public SynExpr { - public: +public: SynConst(Token t); ~SynConst(); void print(int n); +private: + Token token; + }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index 9e699b4..d14ddad 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,255 +1,282 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); obj = ParseState(); obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); - if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) + if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| + (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| + (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| + (s->get().getType()==ttModAssign) + ) { - while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) + while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)|| + (s->get().getType()==ttAddAssign)||(s->get().getType()==ttSubAssign)|| + (s->get().getType()==ttMulAssign)||(s->get().getType()==ttDivAssign)|| + (s->get().getType()==ttModAssign) + ) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynExpr * Parser::ParseState() { SynNode * r; - if(s->get().getSource() == "while") + if(s->get().getSource() == "while") return ParseWhile(); + else if(s->get().getType() == ttBegin) return ParseBlock(); + else { - return ParseWhile(); - } else { - return ParseExpr(); + r = ParseExpr(); + if(s->get().getType()!=ttSemicolon) s->error(-15,"",s->getPos()); + s->next(); + return (SynExpr*)r; } } +SynExpr * Parser::ParseBlock() +{ + SynBlock * block; + SynNode * st; + + s->next(); + block = new SynBlock(); + while(s->get().getType()!=ttEnd) + { + st = ParseState(); + block->push_back(st); + } + s->next(); + return (SynExpr*)block; +} + SynExpr * Parser::ParseWhile() { - SynNode * l; - SynNode * r; + SynNode * condition; + SynNode * operation; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); - l = ParseExpr(); + condition = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); s->next(); - r = ParseState(); + operation = ParseState(); - return (SynExpr*)new SynWhile(l,r); + return (SynExpr*)new SynWhile(condition,operation); } diff --git a/parser.h b/parser.h index 61d3480..09e9f12 100644 --- a/parser.h +++ b/parser.h @@ -1,36 +1,33 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); SynExpr * ParseState(); + SynExpr * ParseBlock(); SynExpr * ParseWhile(); - - //SynState * ParseState(); - //SynState * ParseFor(); - //SynState * ParseWhile(); private: SynNode * obj; }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index 0ef7533..ff3fefa 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1,9 @@ -while(q<a)c=d-e +while(true) +{ + i+=2; + { + x*=10; + } + n=i+j; + ++j; +}
todeus/tcc
94222426fb76b9e0600f1c27afcea46ab049c7fd
Строит дерево для while
diff --git a/node.cpp b/node.cpp index c609653..c4b4c41 100644 --- a/node.cpp +++ b/node.cpp @@ -1,95 +1,142 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; +void SynNode::print(int n) +{ +} + SynExpr::SynExpr() { left = 0; right = 0; } -int SynExpr::print(int n) -{ - cout << "[" << token.getSource() << "]" << endl; - if(left) - { - for(int i=0;i<n;i++) - cout<<" "; - cout<<" '-"; - left->print(n+1); - } - if(right) - { - for(int i=0;i<n;i++) - cout<<" "; - cout<<" '-"; - right->print(n+1); - } -} SynExpr::~SynExpr() { } +/* SynState::SynState() { + left = 0; + right = 0; } SynState::~SynState() { } -/* -SynFor::SynFor(SynState * par1, SynExpr * par2, SynState * par3, SynState * par4) -{ -} */ - -SynBinOp::SynBinOp(Token t, SynExpr* l, SynExpr* r) +SynBinOp::SynBinOp(Token t, SynNode* l, SynNode* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } -SynUnOp::SynUnOp(Token t, SynExpr* l) +void SynBinOp::print(int n) +{ + cout << "[" << token.getSource() << "]" << endl; + if(left) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + left->print(n+1); + } + if(right) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + right->print(n+1); + } +} + +SynUnOp::SynUnOp(Token t, SynNode* l) { left = l; token = t; } +void SynUnOp::print(int n) +{ + cout << "[" << token.getSource() << "]" << endl; + if(left) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + left->print(n+1); + } +} + SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { left = 0; right = 0; token = t; } SynVar::~SynVar() { } +void SynVar::print(int n) +{ + cout << "[" << token.getSource() << "]" << endl; +} + SynConst::SynConst(Token t) { left = 0; right = 0; token = t; } SynConst::~SynConst() { } +void SynConst::print(int n) +{ + cout << "[" << token.getSource() << "]" << endl; +} -//SynWhile::SynWhile(SynExpr* e, SynState* st) -SynWhile::SynWhile(SynExpr* e, SynExpr* st) +SynWhile::SynWhile(SynNode* l, SynNode* r) { - condition = e; - operation = st; + left = l; + right = r; +} +SynWhile::~SynWhile() +{ +} + +void SynWhile::print(int n) +{ + cout << "[WHILE]" << endl; + + if(left) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + left->print(n+1); + } + if(right) + { + for(int i=0;i<n;i++) + cout<<" "; + cout<<" '-"; + right->print(n+1); + } + } diff --git a/node.h b/node.h index 958117b..cf56712 100644 --- a/node.h +++ b/node.h @@ -1,78 +1,74 @@ #ifndef NODE_H #define NODE_H #include "scanner.h" class SynNode { public: - int print(int n); + virtual void print(int n); }; -class SynState:SynNode +/* +class SynState:public SynNode { public: + SynNode* left; + SynNode* right; SynState(); ~SynState(); }; +*/ -class SynExpr:SynNode +class SynExpr:public SynNode { public: - SynExpr * left; - SynExpr * right; + SynNode * left; + SynNode * right; Token token; SynExpr(); ~SynExpr(); - int print(int n); -}; -/* -class SynWhile:SynState -{ - public: - SynWhile(SynExpr* e, SynState* st); - ~SynWhile(); - private: - SynExpr* condition; - SynState* operation; }; -*/ -class SynWhile:SynState + + +class SynWhile:public SynExpr { public: - SynWhile(SynExpr* e, SynExpr* st); + SynWhile(SynNode* l, SynNode* r); ~SynWhile(); - private: - SynExpr* condition; - SynExpr* operation; + void print(int n); }; -class SynBinOp:SynExpr +class SynBinOp:public SynExpr { public: - SynBinOp(Token t, SynExpr* l, SynExpr* r); + SynBinOp(Token t, SynNode* l, SynNode* r); ~SynBinOp(); + void print(int n); }; -class SynUnOp:SynExpr +class SynUnOp:public SynExpr { public: - SynUnOp(Token t, SynExpr* l); + SynUnOp(Token t, SynNode* l); ~SynUnOp(); + void print(int n); }; -class SynVar:SynExpr +class SynVar:public SynExpr { public: SynVar(Token t); ~SynVar(); + void print(int n); }; -class SynConst:SynExpr +class SynConst:public SynExpr { public: SynConst(Token t); ~SynConst(); + void print(int n); }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index 4db0f1f..9e699b4 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,268 +1,255 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); - SynState *e = ParseWhile(); - //e->print(0); + obj = ParseState(); + obj->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } -SynState * Parser::ParseState() +SynExpr * Parser::ParseState() { - if(s->get().getString() == "while") + SynNode * r; + if(s->get().getSource() == "while") + { return ParseWhile(); + } else { + return ParseExpr(); + } } -SynState * Parser::ParseWhile() +SynExpr * Parser::ParseWhile() { - SynState * r; - SynExpr * e; - //SynState * stat; - SynExpr * stat; + SynNode * l; + SynNode * r; s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); - e = ParseExpr(); + l = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); - //stat = ParseState(); - stat = ParseExpr(); - - r = (SynState*)new SynWhile(e,stat); - return r; -} + s->next(); + r = ParseState(); -/* -SynState * Parser::ParseFor() -{ - SynState * par_1; - SynExpr * par_2; - SynState * par_3; - SynState * par_4; - if(s->get().getString() == "for") - { - s->next(); - if(s->get().getType()!=ttLeftBracket) s->error(-10,"",s->getPos()); + return (SynExpr*)new SynWhile(l,r); - } } -*/ diff --git a/parser.h b/parser.h index 267949a..61d3480 100644 --- a/parser.h +++ b/parser.h @@ -1,32 +1,36 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { - public: +public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); - SynState * ParseState(); - SynState * ParseFor(); - SynState * ParseWhile(); + SynExpr * ParseState(); + SynExpr * ParseWhile(); + //SynState * ParseState(); + //SynState * ParseFor(); + //SynState * ParseWhile(); +private: + SynNode * obj; }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index 17f4416..0ef7533 100644 --- a/test11.txt +++ b/test11.txt @@ -1,2 +1 @@ -while(a<b) a+b - +while(q<a)c=d-e
todeus/tcc
a2efb535387939f3a33e6fc72acb01a9c08d7aca
Вроде как теперь парсит while, дерево пока не строит, но хоть ошибок не выдает. :)
diff --git a/main.cpp b/main.cpp index e50c9e3..35bb061 100644 --- a/main.cpp +++ b/main.cpp @@ -1,57 +1,57 @@ #include <iostream> #include <fstream> #include "scanner.h" #include "parser.h" using namespace std; int main(int argc, char* argv[]) { if(argc==1) { std::cout << "*****************************" << std::endl; std::cout << " Todeus C Compiler " << std::endl; std::cout << " " << std::endl; std::cout << " Author: Mikhail S. Pavlov " << std::endl; std::cout << " " << std::endl; std::cout << " Group: 238 " << std::endl; std::cout << "*****************************" << std::endl; } //if(argc==2) { try { Scanner * s = new Scanner("test11.txt"); /* //Вывод результата работы лексического анализатора(список лексем) while(s->next().getType()!=ttEOF) { std::cout << s->get().print() << endl; } */ Parser * p = new Parser(s); } catch(MyEx error) { switch(error.code) { case -1: cout << "Error: File \'" << error.str << "\' not found!"; break; case 0: cout << "Error: Unknown symbol \'"<< error.str <<"\'!"; break; case 1: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Constant is too long!"; break; case 202: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Unclosed string literal!"; break; case 203: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in numeric constant!"; break; case 204: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error in char constant!"; break; case 206: cout << "Error(" << error.pos.line << "," << error.pos.position << "): Error escape ...!"; break; - default: cout << "Error: Unknown error!"; break; + default: cout << "Error: Unknown error(" << error.code << ")"; break; } } } return 0; } diff --git a/node.cpp b/node.cpp index 0c1b332..c609653 100644 --- a/node.cpp +++ b/node.cpp @@ -1,88 +1,95 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; SynExpr::SynExpr() { left = 0; right = 0; } int SynExpr::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynExpr::~SynExpr() { } SynState::SynState() { } SynState::~SynState() { } /* SynFor::SynFor(SynState * par1, SynExpr * par2, SynState * par3, SynState * par4) { } */ SynBinOp::SynBinOp(Token t, SynExpr* l, SynExpr* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } SynUnOp::SynUnOp(Token t, SynExpr* l) { left = l; token = t; } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { left = 0; right = 0; token = t; } SynVar::~SynVar() { } SynConst::SynConst(Token t) { left = 0; right = 0; token = t; } SynConst::~SynConst() { } + +//SynWhile::SynWhile(SynExpr* e, SynState* st) +SynWhile::SynWhile(SynExpr* e, SynExpr* st) +{ + condition = e; + operation = st; +} diff --git a/node.h b/node.h index b08fef3..958117b 100644 --- a/node.h +++ b/node.h @@ -1,67 +1,78 @@ #ifndef NODE_H #define NODE_H #include "scanner.h" class SynNode { public: int print(int n); }; class SynState:SynNode { public: SynState(); ~SynState(); }; +class SynExpr:SynNode +{ + public: + SynExpr * left; + SynExpr * right; + Token token; + SynExpr(); + ~SynExpr(); + int print(int n); +}; +/* class SynWhile:SynState { public: SynWhile(SynExpr* e, SynState* st); ~SynWhile(); private: SynExpr* condition; SynState* operation; }; - -class SynExpr:SynNode +*/ +class SynWhile:SynState { public: - SynExpr * left; - SynExpr * right; - Token token; - SynExpr(); - ~SynExpr(); - int print(int n); + SynWhile(SynExpr* e, SynExpr* st); + ~SynWhile(); + private: + SynExpr* condition; + SynExpr* operation; }; + class SynBinOp:SynExpr { public: SynBinOp(Token t, SynExpr* l, SynExpr* r); ~SynBinOp(); }; class SynUnOp:SynExpr { public: SynUnOp(Token t, SynExpr* l); ~SynUnOp(); }; class SynVar:SynExpr { public: SynVar(Token t); ~SynVar(); }; class SynConst:SynExpr { public: SynConst(Token t); ~SynConst(); }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index 1d45c8d..4db0f1f 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,265 +1,268 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); - SynExpr *e = ParseExpr(); - e->print(0); + SynState *e = ParseWhile(); + //e->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } SynState * Parser::ParseState() { if(s->get().getString() == "while") return ParseWhile(); } SynState * Parser::ParseWhile() { + SynState * r; SynExpr * e; - SynState * stat; + //SynState * stat; + SynExpr * stat; s->next(); - if(s->get().getType()!=ttLeftBracket) s->error(-10,"",s->getPos()); + if(s->get().getType()!=ttLeftBracket) s->error(-11,"",s->getPos()); s->next(); e = ParseExpr(); - s->next(); - if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); - st = ParseState(); + if(s->get().getType()!=ttRightBracket) s->error(-12,"",s->getPos()); + //stat = ParseState(); + stat = ParseExpr(); - return + r = (SynState*)new SynWhile(e,stat); + return r; } /* SynState * Parser::ParseFor() { SynState * par_1; SynExpr * par_2; SynState * par_3; SynState * par_4; if(s->get().getString() == "for") { s->next(); if(s->get().getType()!=ttLeftBracket) s->error(-10,"",s->getPos()); } } */ diff --git a/test11.txt b/test11.txt index 68e1765..17f4416 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1,2 @@ -(a+(a+a))+((a+a)+a) +while(a<b) a+b +
todeus/tcc
b3d4fb22835b119cb4cc460e990a5e2bf54fbf6b
еще раз =)
diff --git a/node.cpp b/node.cpp index 8b5bf4c..0c1b332 100644 --- a/node.cpp +++ b/node.cpp @@ -1,86 +1,88 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; SynExpr::SynExpr() { left = 0; right = 0; } int SynExpr::print(int n) { cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynExpr::~SynExpr() { } SynState::SynState() { } SynState::~SynState() { } - -SynFor::SynFor(SynState * par1/*, SynExpr * par2*/, SynState * par3, SynState * par4) +/* +SynFor::SynFor(SynState * par1, SynExpr * par2, SynState * par3, SynState * par4) { } +*/ + SynBinOp::SynBinOp(Token t, SynExpr* l, SynExpr* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } SynUnOp::SynUnOp(Token t, SynExpr* l) { left = l; token = t; } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { left = 0; right = 0; token = t; } SynVar::~SynVar() { } SynConst::SynConst(Token t) { left = 0; right = 0; token = t; } SynConst::~SynConst() { }
todeus/tcc
ea208ad00194a2b0c113fb308c18fb35bd041499
Прромежуточный коммт
diff --git a/node.cpp b/node.cpp index aee0792..8b5bf4c 100644 --- a/node.cpp +++ b/node.cpp @@ -1,75 +1,86 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; SynExpr::SynExpr() { left = 0; right = 0; } int SynExpr::print(int n) { - //cout << "1" << endl; cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; - if(left) cout<<" '-"; else cout<<"."; + cout<<" '-"; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynExpr::~SynExpr() { } +SynState::SynState() +{ +} + +SynState::~SynState() +{ +} + +SynFor::SynFor(SynState * par1/*, SynExpr * par2*/, SynState * par3, SynState * par4) +{ +} + SynBinOp::SynBinOp(Token t, SynExpr* l, SynExpr* r) { left = l; right = r; token = t; } SynBinOp::~SynBinOp() { } SynUnOp::SynUnOp(Token t, SynExpr* l) { left = l; token = t; } SynUnOp::~SynUnOp() { } SynVar::SynVar(Token t) { left = 0; right = 0; token = t; } SynVar::~SynVar() { } SynConst::SynConst(Token t) { left = 0; right = 0; token = t; } SynConst::~SynConst() { } diff --git a/node.h b/node.h index c48df89..b08fef3 100644 --- a/node.h +++ b/node.h @@ -1,49 +1,67 @@ #ifndef NODE_H #define NODE_H #include "scanner.h" class SynNode { + public: int print(int n); }; +class SynState:SynNode +{ + public: + SynState(); + ~SynState(); +}; + +class SynWhile:SynState +{ + public: + SynWhile(SynExpr* e, SynState* st); + ~SynWhile(); + private: + SynExpr* condition; + SynState* operation; +}; + class SynExpr:SynNode { public: SynExpr * left; SynExpr * right; Token token; SynExpr(); ~SynExpr(); int print(int n); }; class SynBinOp:SynExpr { public: SynBinOp(Token t, SynExpr* l, SynExpr* r); ~SynBinOp(); }; class SynUnOp:SynExpr { public: SynUnOp(Token t, SynExpr* l); ~SynUnOp(); }; class SynVar:SynExpr { public: SynVar(Token t); ~SynVar(); }; class SynConst:SynExpr { public: SynConst(Token t); ~SynConst(); }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index 1f9149e..1d45c8d 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,225 +1,265 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); SynExpr *e = ParseExpr(); e->print(0); } + + SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { while((s->get().getType()==ttAstr)|| (s->get().getType()==ttDiv)|| (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; case ttPlus: case ttMinus: case ttNot: case ttInc: case ttDec: Token token = s->get(); s->next(); r = (SynExpr*)new SynUnOp(token, ParseExpr()); return r; } return 0; } + +SynState * Parser::ParseState() +{ + if(s->get().getString() == "while") + return ParseWhile(); +} + +SynState * Parser::ParseWhile() +{ + SynExpr * e; + SynState * stat; + + s->next(); + if(s->get().getType()!=ttLeftBracket) s->error(-10,"",s->getPos()); + s->next(); + e = ParseExpr(); + s->next(); + if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); + st = ParseState(); + + return +} + +/* +SynState * Parser::ParseFor() +{ + SynState * par_1; + SynExpr * par_2; + SynState * par_3; + SynState * par_4; + if(s->get().getString() == "for") + { + s->next(); + if(s->get().getType()!=ttLeftBracket) s->error(-10,"",s->getPos()); + + } +} +*/ diff --git a/parser.h b/parser.h index 33077dc..267949a 100644 --- a/parser.h +++ b/parser.h @@ -1,28 +1,32 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); SynExpr * ParseAssignExpr(); SynExpr * ParseLogOrExpr(); SynExpr * ParseLogAndExpr(); SynExpr * ParseBitOrExpr(); SynExpr * ParseAndExpr(); SynExpr * ParseEquExpr(); SynExpr * ParseRelExpr(); SynExpr * ParseShiftExpr(); SynExpr * ParseAddExpr(); SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); + SynState * ParseState(); + SynState * ParseFor(); + SynState * ParseWhile(); + }; #endif // PARSER_H diff --git a/test11.txt b/test11.txt index fffb040..68e1765 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1 @@ -a+ ++b +(a+(a+a))+((a+a)+a)
todeus/tcc
c1b79c1ac159bf8eb4eb4b6caf52b47be9f2b8dc
Парсятся операции с одним параметром. Исправлена ошибка с целочисленным делением. Теперь оно тоже парсится. :)
diff --git a/Makefile b/Makefile index 587d116..2ac406b 100644 --- a/Makefile +++ b/Makefile @@ -1,229 +1,229 @@ ############################################################################# # Makefile for building: tcc -# Generated by qmake (2.01a) (Qt 4.5.3) on: ?? ????. 18 00:17:49 2010 +# Generated by qmake (2.01a) (Qt 4.5.3) on: ?? ????. 19 11:49:31 2010 # Project: tcc.pro # Template: app # Command: /usr/bin/qmake -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro ############################################################################# ####### Compiler, tools and options CC = gcc CXX = g++ DEFINES = -DQT_CORE_LIB -DQT_SHARED CFLAGS = -pipe -g -Wall -W -D_REENTRANT $(DEFINES) CXXFLAGS = -pipe -g -Wall -W -D_REENTRANT $(DEFINES) INCPATH = -I/usr/share/qt/mkspecs/linux-g++ -I. -I/usr/include/QtCore -I/usr/include -I. LINK = g++ LFLAGS = LIBS = $(SUBLIBS) -L/usr/lib -lQtCore -L/usr/lib -lz -lm -pthread -lgthread-2.0 -lrt -lglib-2.0 -ldl -lpthread AR = ar cqs RANLIB = QMAKE = /usr/bin/qmake TAR = tar -cf COMPRESS = gzip -9f COPY = cp -f SED = sed COPY_FILE = $(COPY) COPY_DIR = $(COPY) -r INSTALL_FILE = install -m 644 -p INSTALL_DIR = $(COPY_DIR) INSTALL_PROGRAM = install -m 755 -p DEL_FILE = rm -f SYMLINK = ln -sf DEL_DIR = rmdir MOVE = mv -f CHK_DIR_EXISTS= test -d MKDIR = mkdir -p ####### Output directory OBJECTS_DIR = ./ ####### Files SOURCES = main.cpp \ scanner.cpp \ token.cpp \ parser.cpp \ node.cpp OBJECTS = main.o \ scanner.o \ token.o \ parser.o \ node.o DIST = /usr/share/qt/mkspecs/common/g++.conf \ /usr/share/qt/mkspecs/common/unix.conf \ /usr/share/qt/mkspecs/common/linux.conf \ /usr/share/qt/mkspecs/qconfig.pri \ /usr/share/qt/mkspecs/features/qt_functions.prf \ /usr/share/qt/mkspecs/features/qt_config.prf \ /usr/share/qt/mkspecs/features/exclusive_builds.prf \ /usr/share/qt/mkspecs/features/default_pre.prf \ /usr/share/qt/mkspecs/features/debug.prf \ /usr/share/qt/mkspecs/features/default_post.prf \ /usr/share/qt/mkspecs/features/warn_on.prf \ /usr/share/qt/mkspecs/features/qt.prf \ /usr/share/qt/mkspecs/features/unix/thread.prf \ /usr/share/qt/mkspecs/features/moc.prf \ /usr/share/qt/mkspecs/features/resources.prf \ /usr/share/qt/mkspecs/features/uic.prf \ /usr/share/qt/mkspecs/features/yacc.prf \ /usr/share/qt/mkspecs/features/lex.prf \ /usr/share/qt/mkspecs/features/include_source_dir.prf \ tcc.pro QMAKE_TARGET = tcc DESTDIR = TARGET = tcc first: all ####### Implicit rules .SUFFIXES: .o .c .cpp .cc .cxx .C .cpp.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cc.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cxx.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .C.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .c.o: $(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<" ####### Build rules all: Makefile $(TARGET) $(TARGET): $(OBJECTS) $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) Makefile: tcc.pro /usr/share/qt/mkspecs/linux-g++/qmake.conf /usr/share/qt/mkspecs/common/g++.conf \ /usr/share/qt/mkspecs/common/unix.conf \ /usr/share/qt/mkspecs/common/linux.conf \ /usr/share/qt/mkspecs/qconfig.pri \ /usr/share/qt/mkspecs/features/qt_functions.prf \ /usr/share/qt/mkspecs/features/qt_config.prf \ /usr/share/qt/mkspecs/features/exclusive_builds.prf \ /usr/share/qt/mkspecs/features/default_pre.prf \ /usr/share/qt/mkspecs/features/debug.prf \ /usr/share/qt/mkspecs/features/default_post.prf \ /usr/share/qt/mkspecs/features/warn_on.prf \ /usr/share/qt/mkspecs/features/qt.prf \ /usr/share/qt/mkspecs/features/unix/thread.prf \ /usr/share/qt/mkspecs/features/moc.prf \ /usr/share/qt/mkspecs/features/resources.prf \ /usr/share/qt/mkspecs/features/uic.prf \ /usr/share/qt/mkspecs/features/yacc.prf \ /usr/share/qt/mkspecs/features/lex.prf \ /usr/share/qt/mkspecs/features/include_source_dir.prf \ /usr/lib/libQtCore.prl $(QMAKE) -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro /usr/share/qt/mkspecs/common/g++.conf: /usr/share/qt/mkspecs/common/unix.conf: /usr/share/qt/mkspecs/common/linux.conf: /usr/share/qt/mkspecs/qconfig.pri: /usr/share/qt/mkspecs/features/qt_functions.prf: /usr/share/qt/mkspecs/features/qt_config.prf: /usr/share/qt/mkspecs/features/exclusive_builds.prf: /usr/share/qt/mkspecs/features/default_pre.prf: /usr/share/qt/mkspecs/features/debug.prf: /usr/share/qt/mkspecs/features/default_post.prf: /usr/share/qt/mkspecs/features/warn_on.prf: /usr/share/qt/mkspecs/features/qt.prf: /usr/share/qt/mkspecs/features/unix/thread.prf: /usr/share/qt/mkspecs/features/moc.prf: /usr/share/qt/mkspecs/features/resources.prf: /usr/share/qt/mkspecs/features/uic.prf: /usr/share/qt/mkspecs/features/yacc.prf: /usr/share/qt/mkspecs/features/lex.prf: /usr/share/qt/mkspecs/features/include_source_dir.prf: /usr/lib/libQtCore.prl: qmake: FORCE @$(QMAKE) -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro dist: @$(CHK_DIR_EXISTS) .tmp/tcc1.0.0 || $(MKDIR) .tmp/tcc1.0.0 $(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/tcc1.0.0/ && $(COPY_FILE) --parents scanner.h KA.h token.h struct.h myEx.h parser.h node.h .tmp/tcc1.0.0/ && $(COPY_FILE) --parents main.cpp scanner.cpp token.cpp parser.cpp node.cpp .tmp/tcc1.0.0/ && (cd `dirname .tmp/tcc1.0.0` && $(TAR) tcc1.0.0.tar tcc1.0.0 && $(COMPRESS) tcc1.0.0.tar) && $(MOVE) `dirname .tmp/tcc1.0.0`/tcc1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/tcc1.0.0 clean:compiler_clean -$(DEL_FILE) $(OBJECTS) -$(DEL_FILE) *~ core *.core ####### Sub-libraries distclean: clean -$(DEL_FILE) $(TARGET) -$(DEL_FILE) Makefile mocclean: compiler_moc_header_clean compiler_moc_source_clean mocables: compiler_moc_header_make_all compiler_moc_source_make_all compiler_moc_header_make_all: compiler_moc_header_clean: compiler_rcc_make_all: compiler_rcc_clean: compiler_image_collection_make_all: qmake_image_collection.cpp compiler_image_collection_clean: -$(DEL_FILE) qmake_image_collection.cpp compiler_moc_source_make_all: compiler_moc_source_clean: compiler_uic_make_all: compiler_uic_clean: compiler_yacc_decl_make_all: compiler_yacc_decl_clean: compiler_yacc_impl_make_all: compiler_yacc_impl_clean: compiler_lex_make_all: compiler_lex_clean: compiler_clean: ####### Compile main.o: main.cpp scanner.h \ token.h \ struct.h \ parser.h \ node.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp scanner.o: scanner.cpp scanner.h \ token.h \ struct.h \ KA.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o scanner.o scanner.cpp token.o: token.cpp token.h \ struct.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o token.o token.cpp parser.o: parser.cpp parser.h \ scanner.h \ token.h \ struct.h \ node.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o parser.o parser.cpp node.o: node.cpp node.h \ scanner.h \ token.h \ struct.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o node.o node.cpp ####### Install install: FORCE uninstall: FORCE FORCE: diff --git a/README b/README index 3412c05..3cb73af 100644 --- a/README +++ b/README @@ -1 +1,3 @@ -This is my C compiler +TCC - Todeus C Compiler + +This is my C compiler ;) diff --git a/node.cpp b/node.cpp index 37bbef9..aee0792 100644 --- a/node.cpp +++ b/node.cpp @@ -1,63 +1,75 @@ #include <iostream> #include <sstream> #include "node.h" using namespace std; SynExpr::SynExpr() { left = 0; right = 0; } int SynExpr::print(int n) { //cout << "1" << endl; cout << "[" << token.getSource() << "]" << endl; if(left) { for(int i=0;i<n;i++) cout<<" "; if(left) cout<<" '-"; else cout<<"."; left->print(n+1); } if(right) { for(int i=0;i<n;i++) cout<<" "; cout<<" '-"; right->print(n+1); } } SynExpr::~SynExpr() { } SynBinOp::SynBinOp(Token t, SynExpr* l, SynExpr* r) { left = l; right = r; token = t; } + SynBinOp::~SynBinOp() { } +SynUnOp::SynUnOp(Token t, SynExpr* l) +{ + left = l; + token = t; +} + +SynUnOp::~SynUnOp() +{ +} + + SynVar::SynVar(Token t) { left = 0; right = 0; token = t; } SynVar::~SynVar() { } SynConst::SynConst(Token t) { left = 0; right = 0; token = t; } SynConst::~SynConst() { } diff --git a/node.h b/node.h index 5922523..c48df89 100644 --- a/node.h +++ b/node.h @@ -1,42 +1,49 @@ #ifndef NODE_H #define NODE_H #include "scanner.h" class SynNode { int print(int n); }; class SynExpr:SynNode { public: SynExpr * left; SynExpr * right; Token token; SynExpr(); ~SynExpr(); int print(int n); }; class SynBinOp:SynExpr { public: SynBinOp(Token t, SynExpr* l, SynExpr* r); ~SynBinOp(); }; +class SynUnOp:SynExpr +{ + public: + SynUnOp(Token t, SynExpr* l); + ~SynUnOp(); +}; + class SynVar:SynExpr { public: SynVar(Token t); ~SynVar(); }; class SynConst:SynExpr { public: SynConst(Token t); ~SynConst(); }; #endif // NODE_H diff --git a/parser.cpp b/parser.cpp index fea8b45..1f9149e 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,212 +1,225 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); SynExpr *e = ParseExpr(); e->print(0); } SynExpr * Parser::ParseExpr() { SynExpr * e = ParseAssignExpr(); return e; } SynExpr * Parser::ParseAssignExpr() { SynExpr * e = ParseLogOrExpr(); if(s->get().getType()==ttAssign) { while(s->get().getType()==ttAssign) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogOrExpr() { SynExpr * e = ParseLogAndExpr(); if(s->get().getType()==ttOr) { while(s->get().getType()==ttOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseLogAndExpr() { SynExpr * e = ParseBitOrExpr(); if(s->get().getType()==ttAnd) { while(s->get().getType()==ttAnd) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); } return e; } return e; } SynExpr * Parser::ParseBitOrExpr() { SynExpr * e = ParseAndExpr(); if(s->get().getType()==ttBitOr) { while(s->get().getType()==ttBitOr) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAndExpr() { SynExpr * e = ParseEquExpr(); if(s->get().getType()==ttAmp) { while(s->get().getType()==ttAmp) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); } return e; } return e; } SynExpr * Parser::ParseEquExpr() { SynExpr * e = ParseRelExpr(); if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); } return e; } return e; } SynExpr * Parser::ParseRelExpr() { SynExpr * e = ParseShiftExpr(); if((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { while((s->get().getType()==ttGreaterEq)|| (s->get().getType()==ttLessEq)|| (s->get().getType()==ttLess)|| (s->get().getType()==ttGreater)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); } return e; } return e; } SynExpr * Parser::ParseShiftExpr() { SynExpr * e = ParseAddExpr(); if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); } return e; } return e; } SynExpr * Parser::ParseAddExpr() { SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); } return e; } return e; } SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); - if((s->get().getType()==ttAstr)||(s->get().getType()==ttDiv)) + if((s->get().getType()==ttAstr)|| + (s->get().getType()==ttDiv)|| + (s->get().getType()==ttMod)) { - while((s->get().getType()==ttAstr)||(s->get().getType()==ttDiv)) + while((s->get().getType()==ttAstr)|| + (s->get().getType()==ttDiv)|| + (s->get().getType()==ttMod)) { Token token = s->get(); s->next(); e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); } return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; + case ttPlus: + case ttMinus: + case ttNot: + case ttInc: + case ttDec: + Token token = s->get(); + s->next(); + r = (SynExpr*)new SynUnOp(token, ParseExpr()); + return r; } return 0; } diff --git a/test11.txt b/test11.txt index ff854f7..fffb040 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1 @@ -qwerty=xp!=x>=f||fa+b*c&d|d>>d<<c==df&&dfsf+88*ss +a+ ++b
todeus/tcc
d0b57b18ab44424569af83a1b567719b8b367aaa
Все бинарные операции теперь парсятся...
diff --git a/Makefile b/Makefile index d02d2a5..587d116 100644 --- a/Makefile +++ b/Makefile @@ -1,229 +1,229 @@ ############################################################################# # Makefile for building: tcc -# Generated by qmake (2.01a) (Qt 4.5.3) on: ?? ????. 18 15:11:57 2010 +# Generated by qmake (2.01a) (Qt 4.5.3) on: ?? ????. 18 00:17:49 2010 # Project: tcc.pro # Template: app # Command: /usr/bin/qmake -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro ############################################################################# ####### Compiler, tools and options CC = gcc CXX = g++ DEFINES = -DQT_CORE_LIB -DQT_SHARED CFLAGS = -pipe -g -Wall -W -D_REENTRANT $(DEFINES) CXXFLAGS = -pipe -g -Wall -W -D_REENTRANT $(DEFINES) INCPATH = -I/usr/share/qt/mkspecs/linux-g++ -I. -I/usr/include/QtCore -I/usr/include -I. LINK = g++ LFLAGS = LIBS = $(SUBLIBS) -L/usr/lib -lQtCore -L/usr/lib -lz -lm -pthread -lgthread-2.0 -lrt -lglib-2.0 -ldl -lpthread AR = ar cqs RANLIB = QMAKE = /usr/bin/qmake TAR = tar -cf COMPRESS = gzip -9f COPY = cp -f SED = sed COPY_FILE = $(COPY) COPY_DIR = $(COPY) -r INSTALL_FILE = install -m 644 -p INSTALL_DIR = $(COPY_DIR) INSTALL_PROGRAM = install -m 755 -p DEL_FILE = rm -f SYMLINK = ln -sf DEL_DIR = rmdir MOVE = mv -f CHK_DIR_EXISTS= test -d MKDIR = mkdir -p ####### Output directory OBJECTS_DIR = ./ ####### Files SOURCES = main.cpp \ scanner.cpp \ token.cpp \ parser.cpp \ node.cpp OBJECTS = main.o \ scanner.o \ token.o \ parser.o \ node.o DIST = /usr/share/qt/mkspecs/common/g++.conf \ /usr/share/qt/mkspecs/common/unix.conf \ /usr/share/qt/mkspecs/common/linux.conf \ /usr/share/qt/mkspecs/qconfig.pri \ /usr/share/qt/mkspecs/features/qt_functions.prf \ /usr/share/qt/mkspecs/features/qt_config.prf \ /usr/share/qt/mkspecs/features/exclusive_builds.prf \ /usr/share/qt/mkspecs/features/default_pre.prf \ /usr/share/qt/mkspecs/features/debug.prf \ /usr/share/qt/mkspecs/features/default_post.prf \ /usr/share/qt/mkspecs/features/warn_on.prf \ /usr/share/qt/mkspecs/features/qt.prf \ /usr/share/qt/mkspecs/features/unix/thread.prf \ /usr/share/qt/mkspecs/features/moc.prf \ /usr/share/qt/mkspecs/features/resources.prf \ /usr/share/qt/mkspecs/features/uic.prf \ /usr/share/qt/mkspecs/features/yacc.prf \ /usr/share/qt/mkspecs/features/lex.prf \ /usr/share/qt/mkspecs/features/include_source_dir.prf \ tcc.pro QMAKE_TARGET = tcc DESTDIR = TARGET = tcc first: all ####### Implicit rules .SUFFIXES: .o .c .cpp .cc .cxx .C .cpp.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cc.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .cxx.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .C.o: $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" .c.o: $(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<" ####### Build rules all: Makefile $(TARGET) $(TARGET): $(OBJECTS) $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) Makefile: tcc.pro /usr/share/qt/mkspecs/linux-g++/qmake.conf /usr/share/qt/mkspecs/common/g++.conf \ /usr/share/qt/mkspecs/common/unix.conf \ /usr/share/qt/mkspecs/common/linux.conf \ /usr/share/qt/mkspecs/qconfig.pri \ /usr/share/qt/mkspecs/features/qt_functions.prf \ /usr/share/qt/mkspecs/features/qt_config.prf \ /usr/share/qt/mkspecs/features/exclusive_builds.prf \ /usr/share/qt/mkspecs/features/default_pre.prf \ /usr/share/qt/mkspecs/features/debug.prf \ /usr/share/qt/mkspecs/features/default_post.prf \ /usr/share/qt/mkspecs/features/warn_on.prf \ /usr/share/qt/mkspecs/features/qt.prf \ /usr/share/qt/mkspecs/features/unix/thread.prf \ /usr/share/qt/mkspecs/features/moc.prf \ /usr/share/qt/mkspecs/features/resources.prf \ /usr/share/qt/mkspecs/features/uic.prf \ /usr/share/qt/mkspecs/features/yacc.prf \ /usr/share/qt/mkspecs/features/lex.prf \ /usr/share/qt/mkspecs/features/include_source_dir.prf \ /usr/lib/libQtCore.prl $(QMAKE) -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro /usr/share/qt/mkspecs/common/g++.conf: /usr/share/qt/mkspecs/common/unix.conf: /usr/share/qt/mkspecs/common/linux.conf: /usr/share/qt/mkspecs/qconfig.pri: /usr/share/qt/mkspecs/features/qt_functions.prf: /usr/share/qt/mkspecs/features/qt_config.prf: /usr/share/qt/mkspecs/features/exclusive_builds.prf: /usr/share/qt/mkspecs/features/default_pre.prf: /usr/share/qt/mkspecs/features/debug.prf: /usr/share/qt/mkspecs/features/default_post.prf: /usr/share/qt/mkspecs/features/warn_on.prf: /usr/share/qt/mkspecs/features/qt.prf: /usr/share/qt/mkspecs/features/unix/thread.prf: /usr/share/qt/mkspecs/features/moc.prf: /usr/share/qt/mkspecs/features/resources.prf: /usr/share/qt/mkspecs/features/uic.prf: /usr/share/qt/mkspecs/features/yacc.prf: /usr/share/qt/mkspecs/features/lex.prf: /usr/share/qt/mkspecs/features/include_source_dir.prf: /usr/lib/libQtCore.prl: qmake: FORCE @$(QMAKE) -spec /usr/share/qt/mkspecs/linux-g++ -unix CONFIG+=debug -o Makefile tcc.pro dist: @$(CHK_DIR_EXISTS) .tmp/tcc1.0.0 || $(MKDIR) .tmp/tcc1.0.0 $(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/tcc1.0.0/ && $(COPY_FILE) --parents scanner.h KA.h token.h struct.h myEx.h parser.h node.h .tmp/tcc1.0.0/ && $(COPY_FILE) --parents main.cpp scanner.cpp token.cpp parser.cpp node.cpp .tmp/tcc1.0.0/ && (cd `dirname .tmp/tcc1.0.0` && $(TAR) tcc1.0.0.tar tcc1.0.0 && $(COMPRESS) tcc1.0.0.tar) && $(MOVE) `dirname .tmp/tcc1.0.0`/tcc1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/tcc1.0.0 clean:compiler_clean -$(DEL_FILE) $(OBJECTS) -$(DEL_FILE) *~ core *.core ####### Sub-libraries distclean: clean -$(DEL_FILE) $(TARGET) -$(DEL_FILE) Makefile mocclean: compiler_moc_header_clean compiler_moc_source_clean mocables: compiler_moc_header_make_all compiler_moc_source_make_all compiler_moc_header_make_all: compiler_moc_header_clean: compiler_rcc_make_all: compiler_rcc_clean: compiler_image_collection_make_all: qmake_image_collection.cpp compiler_image_collection_clean: -$(DEL_FILE) qmake_image_collection.cpp compiler_moc_source_make_all: compiler_moc_source_clean: compiler_uic_make_all: compiler_uic_clean: compiler_yacc_decl_make_all: compiler_yacc_decl_clean: compiler_yacc_impl_make_all: compiler_yacc_impl_clean: compiler_lex_make_all: compiler_lex_clean: compiler_clean: ####### Compile main.o: main.cpp scanner.h \ token.h \ struct.h \ parser.h \ node.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp scanner.o: scanner.cpp scanner.h \ token.h \ struct.h \ KA.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o scanner.o scanner.cpp token.o: token.cpp token.h \ struct.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o token.o token.cpp parser.o: parser.cpp parser.h \ scanner.h \ token.h \ struct.h \ node.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o parser.o parser.cpp node.o: node.cpp node.h \ scanner.h \ token.h \ struct.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o node.o node.cpp ####### Install install: FORCE uninstall: FORCE FORCE: diff --git a/parser.cpp b/parser.cpp index 25ce06e..fea8b45 100644 --- a/parser.cpp +++ b/parser.cpp @@ -1,61 +1,212 @@ #include <iostream> #include "parser.h" #include "scanner.h" #include "node.h" Parser::Parser(Scanner *scan) { s = scan; s->next(); SynExpr *e = ParseExpr(); e->print(0); } SynExpr * Parser::ParseExpr() { - SynExpr * e = ParseTerm(); + SynExpr * e = ParseAssignExpr(); + return e; +} + +SynExpr * Parser::ParseAssignExpr() +{ + SynExpr * e = ParseLogOrExpr(); + if(s->get().getType()==ttAssign) + { + while(s->get().getType()==ttAssign) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseLogOrExpr(), e); + } + return e; + } + return e; +} + + +SynExpr * Parser::ParseLogOrExpr() +{ + SynExpr * e = ParseLogAndExpr(); + if(s->get().getType()==ttOr) + { + while(s->get().getType()==ttOr) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseLogAndExpr(), e); + } + return e; + } + return e; +} + + +SynExpr * Parser::ParseLogAndExpr() +{ + SynExpr * e = ParseBitOrExpr(); + if(s->get().getType()==ttAnd) + { + while(s->get().getType()==ttAnd) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseBitOrExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseBitOrExpr() +{ + SynExpr * e = ParseAndExpr(); + if(s->get().getType()==ttBitOr) + { + while(s->get().getType()==ttBitOr) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseAndExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseAndExpr() +{ + SynExpr * e = ParseEquExpr(); + if(s->get().getType()==ttAmp) + { + while(s->get().getType()==ttAmp) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseEquExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseEquExpr() +{ + SynExpr * e = ParseRelExpr(); + if((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) + { + while((s->get().getType()==ttNotAssign)||(s->get().getType()==ttEq)) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseRelExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseRelExpr() +{ + SynExpr * e = ParseShiftExpr(); + if((s->get().getType()==ttGreaterEq)|| + (s->get().getType()==ttLessEq)|| + (s->get().getType()==ttLess)|| + (s->get().getType()==ttGreater)) + { + while((s->get().getType()==ttGreaterEq)|| + (s->get().getType()==ttLessEq)|| + (s->get().getType()==ttLess)|| + (s->get().getType()==ttGreater)) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseShiftExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseShiftExpr() +{ + SynExpr * e = ParseAddExpr(); + if((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) + { + while((s->get().getType()==ttShiftLeft)||(s->get().getType()==ttShiftRight)) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseAddExpr(), e); + } + return e; + } + return e; +} + +SynExpr * Parser::ParseAddExpr() +{ + SynExpr * e = ParseMulExpr(); if((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) { - Token token = s->get(); - s->next(); - e = (SynExpr*)new SynBinOp(token, ParseExpr(), e); + while ((s->get().getType()==ttPlus)||(s->get().getType()==ttMinus)) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseMulExpr(), e); + } + return e; } return e; } -SynExpr * Parser::ParseTerm() + +SynExpr * Parser::ParseMulExpr() { SynExpr * e = ParseFactor(); if((s->get().getType()==ttAstr)||(s->get().getType()==ttDiv)) { - Token token = s->get(); - s->next(); - e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); + while((s->get().getType()==ttAstr)||(s->get().getType()==ttDiv)) + { + Token token = s->get(); + s->next(); + e = (SynExpr*)new SynBinOp(token, ParseFactor(), e); + } + return e; } return e; } SynExpr * Parser::ParseFactor() { SynExpr * r; switch(s->get().getType()) { case ttIdent: r = (SynExpr*)new SynVar(s->get()); s->next(); return r; case ttInt: case ttInt16: case ttReal: r = (SynExpr*)new SynConst(s->get()); s->next(); return r; case ttLeftBracket: s->next(); r = ParseExpr(); if(s->get().getType()!=ttRightBracket) s->error(-10,"",s->getPos()); s->next(); return r; } return 0; } diff --git a/parser.h b/parser.h index 56c779a..33077dc 100644 --- a/parser.h +++ b/parser.h @@ -1,19 +1,28 @@ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #include "node.h" class Parser { public: Scanner *s; Parser(Scanner *scan); SynExpr * ParseExpr(); - SynExpr * ParseTerm(); + SynExpr * ParseAssignExpr(); + SynExpr * ParseLogOrExpr(); + SynExpr * ParseLogAndExpr(); + SynExpr * ParseBitOrExpr(); + SynExpr * ParseAndExpr(); + SynExpr * ParseEquExpr(); + SynExpr * ParseRelExpr(); + SynExpr * ParseShiftExpr(); + SynExpr * ParseAddExpr(); + SynExpr * ParseMulExpr(); SynExpr * ParseFactor(); }; #endif // PARSER_H diff --git a/tcc.pro b/tcc.pro index ec63224..1d092d6 100644 --- a/tcc.pro +++ b/tcc.pro @@ -1,23 +1,22 @@ # ------------------------------------------------- # Project created by QtCreator 2010-02-15T11:18:36 # ------------------------------------------------- QT -= gui TARGET = tcc CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp \ scanner.cpp \ token.cpp \ parser.cpp \ node.cpp HEADERS += scanner.h \ KA.h \ token.h \ struct.h \ myEx.h \ parser.h \ node.h OTHER_FILES += test11.txt \ - README \ - Makefile + README diff --git a/test11.txt b/test11.txt index d6ab4f5..ff854f7 100644 --- a/test11.txt +++ b/test11.txt @@ -1 +1 @@ -a+b*c+d*700 +qwerty=xp!=x>=f||fa+b*c&d|d>>d<<c==df&&dfsf+88*ss
mattscilipoti/mattscilipoti.github.io
eb34f42c9b22eb6d28723c39ec147210ac6fc8e2
Replace old jekyl site with redirect to who-am-i page
diff --git a/.rvmrc b/.rvmrc deleted file mode 100644 index f0d9c29..0000000 --- a/.rvmrc +++ /dev/null @@ -1 +0,0 @@ -rvm use ree@blog diff --git a/Gemfile b/Gemfile deleted file mode 100644 index a82b70c..0000000 --- a/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -# 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 deleted file mode 100644 index fd93192..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,24 +0,0 @@ -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) diff --git a/README.textile b/README.textile deleted file mode 100644 index bc5f575..0000000 --- a/README.textile +++ /dev/null @@ -1,14 +0,0 @@ -h1. This is the data for my blog - -It is automatically transformed by "Jekyll":http://github.com/mojombo/jekyll into a static site whenever I push this repository to GitHub. - -This site is copied from Tom Preston-Werner. Like Tom, I was tired of having my blog posts end up in a database off on some remote server. "That is backwards. I've lost valuable posts that way. I want to author my posts locally in Textile or Markdown. My blog should be easily stylable and customizable any way I please. It should take care of creating a feed for me. And most of all, my site should be stored on GitHub so that I never lose data again." - -h1. License - -The following directories and their contents are Copyright Matt Scilipoti. You may not reuse anything therein without my permission: - -* _posts/ -* images/ - -All other directories and files are MIT Licensed. Feel free to use the HTML and CSS as you please. If you do use them, a link back to http://github.com/mojombo/jekyll would be appreciated, but is not required. diff --git a/_config.yml b/_config.yml deleted file mode 100644 index e989c29..0000000 --- a/_config.yml +++ /dev/null @@ -1,4 +0,0 @@ -markdown: rdiscount -pygments: true -rdiscount: - extensions: [smart] diff --git a/_includes/category_page.textile b/_includes/category_page.textile deleted file mode 100644 index 0f880cc..0000000 --- a/_includes/category_page.textile +++ /dev/null @@ -1,5 +0,0 @@ -<ul id="archive"> - {% for post in category_posts %} - <li><a href="{{ post.url }}">{{ post.title }}</a><abbr>{{ post.date | date_to_string }}</abbr></li> - {% endfor %} -</ul> diff --git a/_layouts/default.html b/_layouts/default.html deleted file mode 100644 index 3989891..0000000 --- a/_layouts/default.html +++ /dev/null @@ -1,141 +0,0 @@ -<!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=" /> - <meta name="google-site-verification" content="azRTUqgmDhUXbspUrLJgLUXeLFWczaCQixadxPfXKLY" /> - <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 type="text/javascript"> - // from henrik.github.com - google.load("jquery", "1"); - google.load("jqueryui", "1"); - </script> - - <script type="text/javascript"> - 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 sortByName(a,b) - { - if(a.name == b.name){ - return 0; - } - - return (a.name < b.name) ? -1 : 1; - } - - 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.sort(sortByName)); - }); - } - }); - - </script> - -</head> -<body> - -<div class="site"> - <div class="title"> - <a href="/">Matt Scilipoti</a> - <a class="extra" href="/">home</a> - </div> - - <section id="by_category" class="grid_2"> - <h2>"Tag Cloud"</h2> - <a href="/code.html">code ({{ site.categories.code | size }})</a> - <a href="/ruby.html">ruby ({{ site.categories.ruby | size }})</a> - </section> - - - {{ 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> - -<script type="text/javascript"> -//<![CDATA[ - $(document).ready(function() { - $('p.update').effect("highlight", {}, 3000); - }); -//]]> -</script> - -<script type="text/javascript"> - - var _gaq = _gaq || []; - _gaq.push(['_setAccount', 'UA-18771872-1']); - _gaq.push(['_trackPageview']); - - (function() { - var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); - })(); - -</script> - -</body> -</html> - diff --git a/_layouts/post.html b/_layouts/post.html deleted file mode 100644 index 0938f45..0000000 --- a/_layouts/post.html +++ /dev/null @@ -1,15 +0,0 @@ ---- -layout: default ---- -<div id="post"> -{{ content }} -</div> - -<div id="related"> - <h2>Related Posts</h2> - <ul class="posts"> - {% for post in site.related_posts limit:3 %} - <li><span>{{ post.date | date_to_string }}</span> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> - {% endfor %} - </ul> -</div> \ No newline at end of file diff --git a/_layouts/static.html b/_layouts/static.html deleted file mode 100644 index 0e0cbf6..0000000 --- a/_layouts/static.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -layout: default ---- -<div id="static"> - <h1>{{ page.title }}</h1> - {{ content }} - </ul> -</div> - - diff --git a/_posts/2009-06-11-blog_engines_detect.textile b/_posts/2009-06-11-blog_engines_detect.textile deleted file mode 100644 index 87ed9ae..0000000 --- a/_posts/2009-06-11-blog_engines_detect.textile +++ /dev/null @@ -1,32 +0,0 @@ ---- -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 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. 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. diff --git a/_posts/2009-06-12-its-lonely-in-the-stairwell.textile b/_posts/2009-06-12-its-lonely-in-the-stairwell.textile deleted file mode 100644 index e78b5af..0000000 --- a/_posts/2009-06-12-its-lonely-in-the-stairwell.textile +++ /dev/null @@ -1,13 +0,0 @@ ---- -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. - diff --git a/_posts/2009-07-29-a-facet-of-Facets.textile b/_posts/2009-07-29-a-facet-of-Facets.textile deleted file mode 100644 index 0ce27ca..0000000 --- a/_posts/2009-07-29-a-facet-of-Facets.textile +++ /dev/null @@ -1,56 +0,0 @@ ---- -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. - - %(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/_posts/2009-08-03-rails-script-runner-and-cron.textile b/_posts/2009-08-03-rails-script-runner-and-cron.textile deleted file mode 100644 index bf18147..0000000 --- a/_posts/2009-08-03-rails-script-runner-and-cron.textile +++ /dev/null @@ -1,74 +0,0 @@ ---- -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` ("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 ("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. bleh. - -??{color:green}PASS.?? - -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`. - 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 deleted file mode 100644 index 603dd4a..0000000 --- a/_posts/2009-08-05-AR-allow-nil-but-not-blank.textile +++ /dev/null @@ -1,37 +0,0 @@ ---- -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 } - - diff --git a/_posts/2009-08-21-moonshine-rmagick-jaunty.textile b/_posts/2009-08-21-moonshine-rmagick-jaunty.textile deleted file mode 100644 index e5a911a..0000000 --- a/_posts/2009-08-21-moonshine-rmagick-jaunty.textile +++ /dev/null @@ -1,48 +0,0 @@ ---- -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 diff --git a/_posts/2009-08-26-match_false_nil.textile b/_posts/2009-08-26-match_false_nil.textile deleted file mode 100644 index c917bfc..0000000 --- a/_posts/2009-08-26-match_false_nil.textile +++ /dev/null @@ -1,75 +0,0 @@ ---- -published: false -layout: post -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. - -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 %} diff --git a/_posts/2009-08-27-jekyll_pygment.textile b/_posts/2009-08-27-jekyll_pygment.textile deleted file mode 100644 index 4fb3b06..0000000 --- a/_posts/2009-08-27-jekyll_pygment.textile +++ /dev/null @@ -1,24 +0,0 @@ ---- -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 %} - - 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 deleted file mode 100644 index f7bde7d..0000000 --- a/_posts/2010-04-29-postgresql_on_snow_leopard_with_rails_using_homebrew.textile +++ /dev/null @@ -1,78 +0,0 @@ ---- -layout: post -title: Rails and PostgreSQL on Snow Leopard using homebrew ---- - -h1. {{ page.title }} - -p(meta). 29 Apr 2010 - Laurel, MD - -Update: 12 May 2010. Updated automatic load instructions. - -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. - -UPDATE: -If postgres is not loading on boot OR you see: -<code>launchctl: Dubious ownership on file (skipping): /usr/local/Cellar/postgresql/8.4.3/org.postgresql.postgres.plist -nothing found to load</code> - -Then this should fix it: -<code> - sudo chown root:wheel /usr/local/Cellar/postgresql/8.4.3/org.postgresql.postgres.plist - sudo launchctl load -w /usr/local/Cellar/postgresql/8.4.3/org.postgresql.postgres.plist -</code> - - -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 diff --git a/_posts/2010-05-06-heroku_email_socket_error.textile b/_posts/2010-05-06-heroku_email_socket_error.textile deleted file mode 100644 index a4b4278..0000000 --- a/_posts/2010-05-06-heroku_email_socket_error.textile +++ /dev/null @@ -1,30 +0,0 @@ ---- -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. 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> - -Removing them fixed my email. Sendgrid is working fine. - -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* cause of this error. diff --git a/_posts/2010-05-25-requirement_or_policy.textile b/_posts/2010-05-25-requirement_or_policy.textile deleted file mode 100644 index 6f3275d..0000000 --- a/_posts/2010-05-25-requirement_or_policy.textile +++ /dev/null @@ -1,24 +0,0 @@ ---- -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 deleted file mode 100644 index 5aa007d..0000000 --- a/_posts/2010-07-08-rails_3_plugins_and_initialization.textile +++ /dev/null @@ -1,76 +0,0 @@ ---- -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 deleted file mode 100644 index ccde446..0000000 --- a/_posts/2010-09-14-I18n_Rails3_and_gems.textile +++ /dev/null @@ -1,102 +0,0 @@ ---- -layout: post -title: I18n for Rails 3 and common gems (Part One) -published: true -categories: -- code -- I18n -- rails -- ruby ---- - -h1. {{ page.title }} - -p(meta). 14 Sept 2010 - Baltimore, MD - -Part One: Discussion - -p(update). Update 1 (2010-09-16): "Entries to assist translators":#update_1 - -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)**. - -{% 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. - -h2. My expectations - -*1.* Items that can be internationalized should have smart defaults. I should not have to make an entry like: - -pre. labels: - name: Name - -<a name="update_1"> - -p(update). *Update 2010-09-16:* My co-worker, Chris Cahoon, shares a great point. We probably *want* to make entries like `name: Name`, to assist translators. Allowing them to just go down the line translating each entry in the file. Otherwise, many items will not be translated. This makes tools like "Tolk":http://github.com/tokumine/tolk especially helpful. -<a/> - -*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: - -pre. create_success: "%{model} created" - create_fail: "The %{model} could not be created:" - -The specific: - -pre. tour_versions: - create: - success: Your tour was successfully published. - -*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! diff --git a/_posts/2010-09-16-conventional_rails.md b/_posts/2010-09-16-conventional_rails.md deleted file mode 100644 index 0d9bc70..0000000 --- a/_posts/2010-09-16-conventional_rails.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -layout: post -title: Conventional Rails -published: false ---- - -= {{ page.title }} - -p(meta). 16 Sept 2010 - Baltimore, MD diff --git a/_posts/[email protected] b/_posts/[email protected] deleted file mode 100644 index 3c41299..0000000 --- a/_posts/[email protected] +++ /dev/null @@ -1,72 +0,0 @@ ---- -layout: post -title: Embracing RVM's Global Gemset -categories: -- ruby -- rvm -published: true ---- - -{{ page.title }} -================ - -<p class='meta'> 17 Sept 2010 - Prince William Forest Park, VA</p> - -In the brave new world of bundler and rvm, I have been looking for a way to manage my global gems. -The latest iteration is working pretty good. - -rvm provides `~/.rvm/gemsets/global.gems`, but this only runs when a ruby is first installed. I need to manage my day by day changes. - -Enter ~/Gemfile.global. - - rvm ree@global - bundle install --gemfile=~/Gemfile.global - -Simple enough. But very helpful. - -Today I started playing with ruby 1.9.2. Some of the gems in Gemfile.global aren't quite ready yet. -I started editing a copy, named `Gemfile.global19`, but that seemed like folly. - -Enter `group "1.8"`. - -For 1.8, use `bundle install --without "1.9" --gemfile=~/Gemfile.global`<br/> -For 1.9, use `bundle install --without "1.8" --gemfile=~/Gemfile.global` - -Note: a symbol, which is a number (:1.8), causes problems. Use a string ("1.8"). - -Seeing the Gemfile might help: - - source :rubygems - - gem 'autotest' - gem 'autotest-fsevent' - gem 'autotest-notification' - gem 'autotest-rails' - gem 'cheat' - gem 'diff-lcs' - gem 'github' - gem 'hitch' - gem 'jeweler' - gem 'rake' - gem 'rdoc' - gem 'rdoc-data' - gem 'sqlite3-ruby' - gem 'thin' - gem 'thor' - gem 'watchr' - gem 'yard' - - group :irb do - gem 'hirb' - gem 'method_lister' - gem 'wirble' - end - - group '1.8' do - gem 'hammertime' - gem 'ruby-debug' # highline is not 1.9 compatible. highline1.9 is. - end - - group '1.9' do - gem 'ruby-debug19' - end diff --git a/_posts/2010-09-17-jekyll-categories.md b/_posts/2010-09-17-jekyll-categories.md deleted file mode 100644 index d920d32..0000000 --- a/_posts/2010-09-17-jekyll-categories.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -layout: post -title: Categories for your GitHub Pages (Jekyll) -categories: -- code -- github pages -published: true ---- - -{{ page.title }} -================ - -<p class='meta'> 17 Sept 2010 - Laurel, MD</p> - -You, like me, have a github pages powered blog. -You, like me, are contemplating switching to WordPress for tags/categories. -Fret no more. I added categories to my github pages powered blog today. -You can too. - -Just assign a yaml list to categories in your page meta: - categories: - - ruby - - rvm - - -Listing and linking to them was harder than I expected. -I was forced to create a page for each category that I wanted a list of posts for (code.html, ruby.html). - -<p class="update">Update: I went to great pains to format this liquid code (within liquid). Even using the `--safe` argument on my jekyll server. But, it still formatted differently on github pages. I hope to figure out a workaround shortly. Until then, check out the source <a href="http://github.com/mattscilipoti/mattscilipoti.github.com"> at github</a>. -</p> - - -For each post, I expected to get a nice list of assigned categories using: - {{ " {{ post.categories | array_to_sentence_string " }} }} - instead, I got: - {{ post.categories | array_to_sentence_string }} - -Then I tried this (and variations): - - <div id="categories"> - <h2>In this post:</h2> - <ul class="categories"> - {{" {% for category in post.categories "}} %} - <li><a href="/{{"{{ category[0] "}} }}.html">{{" {{ category[0] "}} }}</a></li> - {{" {% endfor"}} %} - </ul> - </div> - -Which rendered: - -<div id="categories"> - <h2>In this post:</h2> - <ul class="categories"> - {% for category in post.categories %} - <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> - {% endfor %} - </ul> -</div> - -That's right. Nothing. - -`sites.categories` works nicely in that loop, but I wanted the categories for this post. -<div id="categories"> - <h2>In this site:</h2> - <ul class="categories"> - {% for category in site.categories %} - <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> - {% endfor %} - </ul> -</div> - -Armed with this knowledge, I set out to create a Tag Cloud. But, I could not find a way to get the count of posts for each category. -I found an example on [litanyagainstfear.com](http://github.com/qrush/litanyagainstfear/blob/master/_layouts/default.html). Alas, it looks like you have to name each category explicitly to get the count of posts. - {{" {{ site.categories.code | size "}} }} - {{" {{ site.categories.ruby | size "}} }} - -Which led me to the (poor man's) Tag Cloud you see in the upper right corner. - -The good news? I was able to use _includes to reuse the category page for each category. - -See the source for this page [at github](http://github.com/mattscilipoti/mattscilipoti.github.com). diff --git a/_posts/2010-09-23-railsmachine-powns-moonshine.textile b/_posts/2010-09-23-railsmachine-powns-moonshine.textile deleted file mode 100644 index 96c6199..0000000 --- a/_posts/2010-09-23-railsmachine-powns-moonshine.textile +++ /dev/null @@ -1,32 +0,0 @@ ---- -layout: post -title: Moonshine hearts Rails3 (and Bundler) -published: true -categories: -- code -- rails3 -- moonshine ---- - -h1. {{ page.title }} - -p(meta). 23 Sept 2010 - Baltimore, MD - -Moonshine and Rails3 sitting in a tree... - -As of today, moonshine is working nicely with Rails3 and Bundler 1.0. Whew! - -h2. "Mooonsine":http://github.com/railsmachine/moonshine - -bq. Rails deployment and configuration management done right. -ShadowPuppet + Capistrano == crazy delicious - -I don't know about you, but I missed the friendly voice of moonshine, "let me handle this provisioning and deployment for you, sir." - -Kudos go out to Josh (technicalpickles) and Rails Machine! He is wrapping up the last bits as this goes to press. - - - -Thanks! - - diff --git a/_posts/2010-10-07-can-can-and-inherited_resources.textile b/_posts/2010-10-07-can-can-and-inherited_resources.textile deleted file mode 100644 index ca69db4..0000000 --- a/_posts/2010-10-07-can-can-and-inherited_resources.textile +++ /dev/null @@ -1,78 +0,0 @@ ---- -layout: post -title: Cancan, Inherited Resources, and Nested Routes ---- - -h1. {{ page.title }} - -p(meta). 07 Oct 2010 - Balitmore, MD - -h2. Problem: - -My subscription does not have a subscriber. -InheritedResources is not populating the `belongs_to` item. - -{% highlight ruby %} - SubscriptionsController << InheritedResources::Base - belongs_to :subscriber - load_and_authorize_resource - - def create - @subscription = build_resource - # do something with subscription - create! - end - end -{% endhighlight %} - - -In `def create`, `@subscription.subscriber` is nil. This *should* be populated by InheritedResources during #build_resource. - -{% highlight ruby %} - def build_resource - get_resource_ivar || set_resource_ivar(end_of_association_chain.send(method_for_build, params[resource_instance_name] || {})) - end -{% endhighlight %} - -Unfortunately, Cancan's load_resource is populating the @subscription instance var, so build_resource simply returns the value of the instance var (get_resource_var). - -h2. Solution: - -Don't ask cancan to load the resource. - -{% highlight ruby %} - SubscriptionsController << InheritedResources::Base - belongs_to :subscriber - authorize_resource - - def create - @subscription = build_resource - # do something with subscription - create! - end - end -{% endhighlight %} - -Or... - -{% highlight ruby %} - SubscriptionsController << InheritedResources::Base - belongs_to :subscriber - - def create - @subscription = build_resource - authorize! :create, Subscription - # do something with subscription - create! - end - end -{% endhighlight %} - -Note: this appears to only be an issue if using nested routes. - -{% highlight ruby %} -resources :subscriber do - resources :subscription -{% endhighlight %} - -This was identified on Rails 3. May affect Rails 2. diff --git a/atom.xml b/atom.xml deleted file mode 100644 index 9e564d0..0000000 --- a/atom.xml +++ /dev/null @@ -1,27 +0,0 @@ ---- -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.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.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> diff --git a/blog.thor b/blog.thor deleted file mode 100644 index c570d49..0000000 --- a/blog.thor +++ /dev/null @@ -1,15 +0,0 @@ -class Blog < Thor - - desc "starts a server", "Starts a server on port:4000, automatically refreshes as site is changed" - def server - cmd = 'jekyll --pygments --server --auto --safe --rdiscount --lsi' - exec cmd - end - - desc "watches & generates", "Watches the site, automatically refreshes as site is changed" - def watch - cmd = 'jekyll --pygments --auto --rdiscount' - exec cmd - end - -end \ No newline at end of file diff --git a/code.textile b/code.textile deleted file mode 100644 index 4baad3b..0000000 --- a/code.textile +++ /dev/null @@ -1,7 +0,0 @@ ---- -layout: static -title: code ---- - -{% assign category_posts = site.categories.code %} -{% include category_page.textile %} \ No newline at end of file diff --git a/css/screen.css b/css/screen.css deleted file mode 100644 index 9f5d7c3..0000000 --- a/css/screen.css +++ /dev/null @@ -1,234 +0,0 @@ -/*****************************************************************************/ -/* -/* 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; - margin-left: 2em; -/* text-align: center; */ -} - - -h1, h2, h3, h4, h5, h6 { - margin-top: 1em; - margin-bottom: 1em; -} - - -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 { - width: 40em; - text-align: center; - 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; - } - - section#by_category { - float: right; - top: 100px; - } - -#repos_frame { - width: 100%; - height: 600px; - border: none; -} - -/*****************************************************************************/ -/* -/* 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; -} diff --git a/css/syntax.css b/css/syntax.css deleted file mode 100644 index 2774b76..0000000 --- a/css/syntax.css +++ /dev/null @@ -1,60 +0,0 @@ -.highlight { background: #ffffff; } -.highlight .c { color: #999988; font-style: italic } /* Comment */ -.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ -.highlight .k { font-weight: bold } /* Keyword */ -.highlight .o { font-weight: bold } /* Operator */ -.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ -.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ -.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ -.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ -.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ -.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */ -.highlight .ge { font-style: italic } /* Generic.Emph */ -.highlight .gr { color: #aa0000 } /* Generic.Error */ -.highlight .gh { color: #999999 } /* Generic.Heading */ -.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ -.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */ -.highlight .go { color: #888888 } /* Generic.Output */ -.highlight .gp { color: #555555 } /* Generic.Prompt */ -.highlight .gs { font-weight: bold } /* Generic.Strong */ -.highlight .gu { color: #aaaaaa } /* Generic.Subheading */ -.highlight .gt { color: #aa0000 } /* Generic.Traceback */ -.highlight .kc { font-weight: bold } /* Keyword.Constant */ -.highlight .kd { font-weight: bold } /* Keyword.Declaration */ -.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ -.highlight .kr { font-weight: bold } /* Keyword.Reserved */ -.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ -.highlight .m { color: #009999 } /* Literal.Number */ -.highlight .s { color: #d14 } /* Literal.String */ -.highlight .na { color: #008080 } /* Name.Attribute */ -.highlight .nb { color: #0086B3 } /* Name.Builtin */ -.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ -.highlight .no { color: #008080 } /* Name.Constant */ -.highlight .ni { color: #800080 } /* Name.Entity */ -.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ -.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ -.highlight .nn { color: #555555 } /* Name.Namespace */ -.highlight .nt { color: #000080 } /* Name.Tag */ -.highlight .nv { color: #008080 } /* Name.Variable */ -.highlight .ow { font-weight: bold } /* Operator.Word */ -.highlight .w { color: #bbbbbb } /* Text.Whitespace */ -.highlight .mf { color: #009999 } /* Literal.Number.Float */ -.highlight .mh { color: #009999 } /* Literal.Number.Hex */ -.highlight .mi { color: #009999 } /* Literal.Number.Integer */ -.highlight .mo { color: #009999 } /* Literal.Number.Oct */ -.highlight .sb { color: #d14 } /* Literal.String.Backtick */ -.highlight .sc { color: #d14 } /* Literal.String.Char */ -.highlight .sd { color: #d14 } /* Literal.String.Doc */ -.highlight .s2 { color: #d14 } /* Literal.String.Double */ -.highlight .se { color: #d14 } /* Literal.String.Escape */ -.highlight .sh { color: #d14 } /* Literal.String.Heredoc */ -.highlight .si { color: #d14 } /* Literal.String.Interpol */ -.highlight .sx { color: #d14 } /* Literal.String.Other */ -.highlight .sr { color: #009926 } /* Literal.String.Regex */ -.highlight .s1 { color: #d14 } /* Literal.String.Single */ -.highlight .ss { color: #990073 } /* Literal.String.Symbol */ -.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ -.highlight .vc { color: #008080 } /* Name.Variable.Class */ -.highlight .vg { color: #008080 } /* Name.Variable.Global */ -.highlight .vi { color: #008080 } /* Name.Variable.Instance */ -.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ diff --git a/favicon.png b/favicon.png deleted file mode 100644 index 7492db2..0000000 Binary files a/favicon.png and /dev/null differ diff --git a/images/Facets_formatted.png b/images/Facets_formatted.png deleted file mode 100644 index 5e8b0fe..0000000 Binary files a/images/Facets_formatted.png and /dev/null differ diff --git a/images/rss.png b/images/rss.png deleted file mode 100644 index d6ecb16..0000000 Binary files a/images/rss.png and /dev/null differ diff --git a/index.html b/index.html index 58f04cb..76b3025 100644 --- a/index.html +++ b/index.html @@ -1,41 +1,13 @@ ---- -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> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> - {% endfor %} - </ul> - - <h2>Interviews, Talks, Etc</h2> - <ul class="posts"> - <li><span>13 Apr 2010</span> &raquo; <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>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> - <li><a href="http://http://github.com/aslakhellesoy/cucumber/">Cucumber:</a> BDD that talks to domain experts first and code second</li> - <h2> Cucumber Resources</h2> - <ul> - <li> <a href="http://elabs.se/blog/15-you-re-cuking-it-wrong">you-re-cuking-it-wrong</a></li> - <li> <a href="http://griffin.oobleyboo.com/archive/our-3-laws-of-cucumber/">our-3-laws-of-cucumber</a></li> - <li> <a href="http://bjeanes.com/2010/09/19/selector-free-cucumber-scenarios">selector-free-cucumber-scenarios</a></li> - </ul> - <h2> Cucumber Tips</h2> - <ul> - <li> <a href="http://bjeanes.com/2010/09/20/pausing-cucumber-scenarios-to-debug">pausing-cucumber-scenarios-to-debug</a> - </ul> - </ul> - <h3>My Repos (sources, no forks)</h3> - - <iframe id=repos_frame src="http://minimal-github.gilesb.com/mattscilipoti"> - <p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p> - </iframe> -</div> - +<html> + <head> + <title>Redirecting to Who Am I</title> + <META http-equiv="refresh" content="1;URL=http://blog.clearto.me/page/who-am-i"> + <script type="text/javascript"> + window.location.href = "http://blog.clearto.me/page/who-am-i" + </script> + </head> + <body bgcolor="#ffffff"> + <p>The contents you are looking for have moved. You will be redirected to the new location automatically. </p> + <p>Please bookmark the correct page at <a href="http://blog.clearto.me/page/who-am-i">http://blog.clearto.me/page/who-am-i</a></p> + </body> +</html> diff --git a/ruby.textile b/ruby.textile deleted file mode 100644 index 3f827aa..0000000 --- a/ruby.textile +++ /dev/null @@ -1,6 +0,0 @@ ---- -layout: static -title: ruby ---- -{% assign category_posts = site.categories.ruby %} -{% include category_page.textile %} \ No newline at end of file
mattscilipoti/mattscilipoti.github.io
cef968443ee9f6ba68db958f1ba208cae2eea365
Complete cancan/InheritedRes post.
diff --git a/_posts/2010-10-07-can-can-and-inherited_resources.textile b/_posts/2010-10-07-can-can-and-inherited_resources.textile index a737119..ca69db4 100644 --- a/_posts/2010-10-07-can-can-and-inherited_resources.textile +++ b/_posts/2010-10-07-can-can-and-inherited_resources.textile @@ -1,57 +1,78 @@ --- layout: post title: Cancan, Inherited Resources, and Nested Routes --- h1. {{ page.title }} p(meta). 07 Oct 2010 - Balitmore, MD h2. Problem: -My subscription does not have a subscriber. +My subscription does not have a subscriber. +InheritedResources is not populating the `belongs_to` item. {% highlight ruby %} SubscriptionsController << InheritedResources::Base belongs_to :subscriber load_and_authorize_resource def create @subscription = build_resource # do something with subscription create! end end {% endhighlight %} -In `def create`, `@subscription.sbscriber` is nil. This *should* be populated by InheritedResources during #build_resource. +In `def create`, `@subscription.subscriber` is nil. This *should* be populated by InheritedResources during #build_resource. {% highlight ruby %} def build_resource get_resource_ivar || set_resource_ivar(end_of_association_chain.send(method_for_build, params[resource_instance_name] || {})) end {% endhighlight %} - Unfortunately, Cancan's load_resource is populating the @subscription instance var, so build_resource simply returns the value of the instance var. +Unfortunately, Cancan's load_resource is populating the @subscription instance var, so build_resource simply returns the value of the instance var (get_resource_var). h2. Solution: Don't ask cancan to load the resource. {% highlight ruby %} SubscriptionsController << InheritedResources::Base belongs_to :subscriber authorize_resource def create @subscription = build_resource # do something with subscription create! end end {% endhighlight %} +Or... +{% highlight ruby %} + SubscriptionsController << InheritedResources::Base + belongs_to :subscriber + + def create + @subscription = build_resource + authorize! :create, Subscription + # do something with subscription + create! + end + end +{% endhighlight %} + +Note: this appears to only be an issue if using nested routes. + +{% highlight ruby %} +resources :subscriber do + resources :subscription +{% endhighlight %} -I +This was identified on Rails 3. May affect Rails 2.
mattscilipoti/mattscilipoti.github.io
d7a9a1d3dbb2cccbe510da32ee0ae0102c8b9514
Use minimal-github.gilesb.com
diff --git a/css/screen.css b/css/screen.css index ec73fde..9f5d7c3 100644 --- a/css/screen.css +++ b/css/screen.css @@ -1,227 +1,234 @@ /*****************************************************************************/ /* /* 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; margin-left: 2em; /* text-align: center; */ } h1, h2, h3, h4, h5, h6 { margin-top: 1em; margin-bottom: 1em; } 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 { width: 40em; text-align: center; 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; } section#by_category { float: right; top: 100px; } + +#repos_frame { + width: 100%; + height: 600px; + border: none; +} + /*****************************************************************************/ /* /* 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; } diff --git a/index.html b/index.html index 0150198..58f04cb 100644 --- a/index.html +++ b/index.html @@ -1,38 +1,41 @@ --- 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> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> <h2>Interviews, Talks, Etc</h2> <ul class="posts"> <li><span>13 Apr 2010</span> &raquo; <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>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> <li><a href="http://http://github.com/aslakhellesoy/cucumber/">Cucumber:</a> BDD that talks to domain experts first and code second</li> <h2> Cucumber Resources</h2> <ul> <li> <a href="http://elabs.se/blog/15-you-re-cuking-it-wrong">you-re-cuking-it-wrong</a></li> <li> <a href="http://griffin.oobleyboo.com/archive/our-3-laws-of-cucumber/">our-3-laws-of-cucumber</a></li> <li> <a href="http://bjeanes.com/2010/09/19/selector-free-cucumber-scenarios">selector-free-cucumber-scenarios</a></li> </ul> <h2> Cucumber Tips</h2> <ul> <li> <a href="http://bjeanes.com/2010/09/20/pausing-cucumber-scenarios-to-debug">pausing-cucumber-scenarios-to-debug</a> </ul> </ul> <h3>My Repos (sources, no forks)</h3> - <p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p> + + <iframe id=repos_frame src="http://minimal-github.gilesb.com/mattscilipoti"> + <p id="repos">See <a href="http://github.com/mattscilipoti">github.com/mattscilipoti</a>.</p> + </iframe> </div>
mattscilipoti/mattscilipoti.github.io
9badf3a9858f068ee796e40d2979c0965a266d38
Sort repos by name.
diff --git a/_layouts/default.html b/_layouts/default.html index 2bc76f7..3989891 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,132 +1,141 @@ <!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=" /> <meta name="google-site-verification" content="azRTUqgmDhUXbspUrLJgLUXeLFWczaCQixadxPfXKLY" /> <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 type="text/javascript"> // from henrik.github.com google.load("jquery", "1"); google.load("jqueryui", "1"); </script> <script type="text/javascript"> 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 sortByName(a,b) + { + if(a.name == b.name){ + return 0; + } + + return (a.name < b.name) ? -1 : 1; + } + 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); + callback(repos.sort(sortByName)); }); } }); </script> </head> <body> <div class="site"> <div class="title"> <a href="/">Matt Scilipoti</a> <a class="extra" href="/">home</a> </div> <section id="by_category" class="grid_2"> <h2>"Tag Cloud"</h2> <a href="/code.html">code ({{ site.categories.code | size }})</a> <a href="/ruby.html">ruby ({{ site.categories.ruby | size }})</a> </section> {{ 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> <script type="text/javascript"> //<![CDATA[ $(document).ready(function() { $('p.update').effect("highlight", {}, 3000); }); //]]> </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18771872-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
mattscilipoti/mattscilipoti.github.io
34b16b47945a06d8b5ba0af8304c279f5cb59cbd
Yuck. Cucumber resources/tips marginally better.
diff --git a/index.html b/index.html index fec5b40..0150198 100644 --- a/index.html +++ b/index.html @@ -1,36 +1,38 @@ --- 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> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> <h2>Interviews, Talks, Etc</h2> <ul class="posts"> <li><span>13 Apr 2010</span> &raquo; <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>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> <li><a href="http://http://github.com/aslakhellesoy/cucumber/">Cucumber:</a> BDD that talks to domain experts first and code second</li> - <ul>Resources + <h2> Cucumber Resources</h2> + <ul> <li> <a href="http://elabs.se/blog/15-you-re-cuking-it-wrong">you-re-cuking-it-wrong</a></li> <li> <a href="http://griffin.oobleyboo.com/archive/our-3-laws-of-cucumber/">our-3-laws-of-cucumber</a></li> <li> <a href="http://bjeanes.com/2010/09/19/selector-free-cucumber-scenarios">selector-free-cucumber-scenarios</a></li> </ul> - <ul> Tips + <h2> Cucumber Tips</h2> + <ul> <li> <a href="http://bjeanes.com/2010/09/20/pausing-cucumber-scenarios-to-debug">pausing-cucumber-scenarios-to-debug</a> </ul> </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
d772efa795cfb7e7d1c110956e9d0d6f2ae38777
add draft: Cancan and InheritedResources
diff --git a/_posts/2010-10-07-can-can-and-inherited_resources.textile b/_posts/2010-10-07-can-can-and-inherited_resources.textile new file mode 100644 index 0000000..a737119 --- /dev/null +++ b/_posts/2010-10-07-can-can-and-inherited_resources.textile @@ -0,0 +1,57 @@ +--- +layout: post +title: Cancan, Inherited Resources, and Nested Routes +--- + +h1. {{ page.title }} + +p(meta). 07 Oct 2010 - Balitmore, MD + +h2. Problem: + +My subscription does not have a subscriber. + +{% highlight ruby %} + SubscriptionsController << InheritedResources::Base + belongs_to :subscriber + load_and_authorize_resource + + def create + @subscription = build_resource + # do something with subscription + create! + end + end +{% endhighlight %} + + +In `def create`, `@subscription.sbscriber` is nil. This *should* be populated by InheritedResources during #build_resource. + +{% highlight ruby %} + def build_resource + get_resource_ivar || set_resource_ivar(end_of_association_chain.send(method_for_build, params[resource_instance_name] || {})) + end +{% endhighlight %} + + Unfortunately, Cancan's load_resource is populating the @subscription instance var, so build_resource simply returns the value of the instance var. + +h2. Solution: + +Don't ask cancan to load the resource. + +{% highlight ruby %} + SubscriptionsController << InheritedResources::Base + belongs_to :subscriber + authorize_resource + + def create + @subscription = build_resource + # do something with subscription + create! + end + end +{% endhighlight %} + + + +I
mattscilipoti/mattscilipoti.github.io
f2c48432e8828e4a025a6d5693a4f6871bd34cfc
Add cucumber resources
diff --git a/index.html b/index.html index 4db1f74..fec5b40 100644 --- a/index.html +++ b/index.html @@ -1,27 +1,36 @@ --- 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> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> <h2>Interviews, Talks, Etc</h2> <ul class="posts"> <li><span>13 Apr 2010</span> &raquo; <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>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> + <li><a href="http://http://github.com/aslakhellesoy/cucumber/">Cucumber:</a> BDD that talks to domain experts first and code second</li> + <ul>Resources + <li> <a href="http://elabs.se/blog/15-you-re-cuking-it-wrong">you-re-cuking-it-wrong</a></li> + <li> <a href="http://griffin.oobleyboo.com/archive/our-3-laws-of-cucumber/">our-3-laws-of-cucumber</a></li> + <li> <a href="http://bjeanes.com/2010/09/19/selector-free-cucumber-scenarios">selector-free-cucumber-scenarios</a></li> + </ul> + <ul> Tips + <li> <a href="http://bjeanes.com/2010/09/20/pausing-cucumber-scenarios-to-debug">pausing-cucumber-scenarios-to-debug</a> + </ul> </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
07c7064715c4a0f14acf58fa72c261dc593d6591
css: remove fixed width
diff --git a/css/screen.css b/css/screen.css index 647a899..ec73fde 100644 --- a/css/screen.css +++ b/css/screen.css @@ -1,221 +1,227 @@ /*****************************************************************************/ /* /* 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; + margin-left: 2em; +/* text-align: center; */ } + h1, h2, h3, h4, h5, h6 { - font-size: 100%; + margin-top: 1em; + margin-bottom: 1em; } + 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; + /* width: 40em; */ margin: 3em auto 2em auto; line-height: 1.5em; } -.title { +.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 { + width: 40em; + text-align: center; 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; } section#by_category { float: right; top: 100px; } /*****************************************************************************/ /* /* 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
a7c125d76c39b772ae1e5254d386748067ad4950
Add google site verification.
diff --git a/_layouts/default.html b/_layouts/default.html index 85ae021..2bc76f7 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,131 +1,132 @@ <!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=" /> + <meta name="google-site-verification" content="azRTUqgmDhUXbspUrLJgLUXeLFWczaCQixadxPfXKLY" /> <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 type="text/javascript"> // from henrik.github.com google.load("jquery", "1"); google.load("jqueryui", "1"); </script> <script type="text/javascript"> 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> <section id="by_category" class="grid_2"> <h2>"Tag Cloud"</h2> <a href="/code.html">code ({{ site.categories.code | size }})</a> <a href="/ruby.html">ruby ({{ site.categories.ruby | size }})</a> </section> {{ 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> <script type="text/javascript"> //<![CDATA[ $(document).ready(function() { $('p.update').effect("highlight", {}, 3000); }); //]]> </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18771872-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
mattscilipoti/mattscilipoti.github.io
474484c8b0d369758d380a72370f4ecdbcd04281
Add google analytics to page.
diff --git a/_layouts/default.html b/_layouts/default.html index ebe3323..85ae021 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,117 +1,131 @@ <!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 type="text/javascript"> // from henrik.github.com google.load("jquery", "1"); google.load("jqueryui", "1"); </script> <script type="text/javascript"> 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> <section id="by_category" class="grid_2"> <h2>"Tag Cloud"</h2> <a href="/code.html">code ({{ site.categories.code | size }})</a> <a href="/ruby.html">ruby ({{ site.categories.ruby | size }})</a> </section> {{ 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> <script type="text/javascript"> //<![CDATA[ $(document).ready(function() { $('p.update').effect("highlight", {}, 3000); }); //]]> </script> +<script type="text/javascript"> + + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-18771872-1']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); + +</script> + </body> </html>
mattscilipoti/mattscilipoti.github.io
b76dbb714d20f93db8c05f778af84a1ad274ab87
New post: moonshine and rails3
diff --git a/_posts/2010-09-23-railsmachine-powns-moonshine.textile b/_posts/2010-09-23-railsmachine-powns-moonshine.textile new file mode 100644 index 0000000..61b1cf2 --- /dev/null +++ b/_posts/2010-09-23-railsmachine-powns-moonshine.textile @@ -0,0 +1,24 @@ +--- +layout: post +title: Moonshine hearts Rails3 (and Bundler) +published: true +categories: +- code +- rails3 +- moonshine +--- + +h1. {{ page.title }} + +p(meta). 23 Sept 2010 - Baltimore, MD + +Moonshine and Rails3 sitting in a tree... + +As of today, moonshine is working nicely with Rails3 and Bundler. Whew! + +I don't know about you, but I missed the friendly voice of moonshine, "let me handle this provisioning and deployment for you, sir." + +Kudos go out to Josh (technicalpickles) and Rails Machine! He is wrapping up the last bits as this goes to press. + +Thanks! +
mattscilipoti/mattscilipoti.github.io
7abd5dc34327ca37dfa56d5e8eadc9af1a8ef429
Add RVM to title.
diff --git a/_posts/[email protected] b/_posts/[email protected] index f388deb..3c41299 100644 --- a/_posts/[email protected] +++ b/_posts/[email protected] @@ -1,72 +1,72 @@ --- layout: post -title: Embracing the Global Gemset +title: Embracing RVM's Global Gemset categories: - ruby - rvm published: true --- {{ page.title }} ================ <p class='meta'> 17 Sept 2010 - Prince William Forest Park, VA</p> In the brave new world of bundler and rvm, I have been looking for a way to manage my global gems. The latest iteration is working pretty good. rvm provides `~/.rvm/gemsets/global.gems`, but this only runs when a ruby is first installed. I need to manage my day by day changes. Enter ~/Gemfile.global. rvm ree@global bundle install --gemfile=~/Gemfile.global Simple enough. But very helpful. Today I started playing with ruby 1.9.2. Some of the gems in Gemfile.global aren't quite ready yet. I started editing a copy, named `Gemfile.global19`, but that seemed like folly. Enter `group "1.8"`. For 1.8, use `bundle install --without "1.9" --gemfile=~/Gemfile.global`<br/> For 1.9, use `bundle install --without "1.8" --gemfile=~/Gemfile.global` Note: a symbol, which is a number (:1.8), causes problems. Use a string ("1.8"). Seeing the Gemfile might help: source :rubygems gem 'autotest' gem 'autotest-fsevent' gem 'autotest-notification' gem 'autotest-rails' gem 'cheat' gem 'diff-lcs' gem 'github' gem 'hitch' gem 'jeweler' gem 'rake' gem 'rdoc' gem 'rdoc-data' gem 'sqlite3-ruby' gem 'thin' gem 'thor' gem 'watchr' gem 'yard' group :irb do gem 'hirb' gem 'method_lister' gem 'wirble' end group '1.8' do gem 'hammertime' gem 'ruby-debug' # highline is not 1.9 compatible. highline1.9 is. end group '1.9' do gem 'ruby-debug19' end
mattscilipoti/mattscilipoti.github.io
cda7e59e90a697ad63bac14a2f3f4448017fbd38
Publish: bundler@global
diff --git a/_posts/[email protected] b/_posts/[email protected] index f36b230..f388deb 100644 --- a/_posts/[email protected] +++ b/_posts/[email protected] @@ -1,15 +1,72 @@ --- layout: post title: Embracing the Global Gemset categories: - ruby - rvm -published: false +published: true --- {{ page.title }} ================ -{.meta} 17 Sept 2010 - Baltimore, MD +<p class='meta'> 17 Sept 2010 - Prince William Forest Park, VA</p> -Part One: Discussion \ No newline at end of file +In the brave new world of bundler and rvm, I have been looking for a way to manage my global gems. +The latest iteration is working pretty good. + +rvm provides `~/.rvm/gemsets/global.gems`, but this only runs when a ruby is first installed. I need to manage my day by day changes. + +Enter ~/Gemfile.global. + + rvm ree@global + bundle install --gemfile=~/Gemfile.global + +Simple enough. But very helpful. + +Today I started playing with ruby 1.9.2. Some of the gems in Gemfile.global aren't quite ready yet. +I started editing a copy, named `Gemfile.global19`, but that seemed like folly. + +Enter `group "1.8"`. + +For 1.8, use `bundle install --without "1.9" --gemfile=~/Gemfile.global`<br/> +For 1.9, use `bundle install --without "1.8" --gemfile=~/Gemfile.global` + +Note: a symbol, which is a number (:1.8), causes problems. Use a string ("1.8"). + +Seeing the Gemfile might help: + + source :rubygems + + gem 'autotest' + gem 'autotest-fsevent' + gem 'autotest-notification' + gem 'autotest-rails' + gem 'cheat' + gem 'diff-lcs' + gem 'github' + gem 'hitch' + gem 'jeweler' + gem 'rake' + gem 'rdoc' + gem 'rdoc-data' + gem 'sqlite3-ruby' + gem 'thin' + gem 'thor' + gem 'watchr' + gem 'yard' + + group :irb do + gem 'hirb' + gem 'method_lister' + gem 'wirble' + end + + group '1.8' do + gem 'hammertime' + gem 'ruby-debug' # highline is not 1.9 compatible. highline1.9 is. + end + + group '1.9' do + gem 'ruby-debug19' + end diff --git a/_posts/2010-09-17-jekyll-categories.md b/_posts/2010-09-17-jekyll-categories.md index fc545cc..d920d32 100644 --- a/_posts/2010-09-17-jekyll-categories.md +++ b/_posts/2010-09-17-jekyll-categories.md @@ -1,81 +1,81 @@ --- layout: post title: Categories for your GitHub Pages (Jekyll) categories: - code - github pages published: true --- {{ page.title }} ================ <p class='meta'> 17 Sept 2010 - Laurel, MD</p> You, like me, have a github pages powered blog. You, like me, are contemplating switching to WordPress for tags/categories. Fret no more. I added categories to my github pages powered blog today. You can too. Just assign a yaml list to categories in your page meta: categories: - ruby - rvm Listing and linking to them was harder than I expected. I was forced to create a page for each category that I wanted a list of posts for (code.html, ruby.html). -<p class="update">Update: I went to great pains to format this liquid code (within liquid). Even using the `--safe` argument on my jekyll server. But, it still formatted differently on github pages. I hope to figure out a workaround shortly. Until then, check out the source [at github](http://github.com/mattscilipoti/mattscilipoti.github.com). +<p class="update">Update: I went to great pains to format this liquid code (within liquid). Even using the `--safe` argument on my jekyll server. But, it still formatted differently on github pages. I hope to figure out a workaround shortly. Until then, check out the source <a href="http://github.com/mattscilipoti/mattscilipoti.github.com"> at github</a>. </p> For each post, I expected to get a nice list of assigned categories using: {{ " {{ post.categories | array_to_sentence_string " }} }} instead, I got: {{ post.categories | array_to_sentence_string }} Then I tried this (and variations): <div id="categories"> <h2>In this post:</h2> <ul class="categories"> {{" {% for category in post.categories "}} %} <li><a href="/{{"{{ category[0] "}} }}.html">{{" {{ category[0] "}} }}</a></li> {{" {% endfor"}} %} </ul> </div> Which rendered: <div id="categories"> <h2>In this post:</h2> <ul class="categories"> {% for category in post.categories %} <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> {% endfor %} </ul> </div> That's right. Nothing. `sites.categories` works nicely in that loop, but I wanted the categories for this post. <div id="categories"> <h2>In this site:</h2> <ul class="categories"> {% for category in site.categories %} <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> {% endfor %} </ul> </div> Armed with this knowledge, I set out to create a Tag Cloud. But, I could not find a way to get the count of posts for each category. I found an example on [litanyagainstfear.com](http://github.com/qrush/litanyagainstfear/blob/master/_layouts/default.html). Alas, it looks like you have to name each category explicitly to get the count of posts. {{" {{ site.categories.code | size "}} }} {{" {{ site.categories.ruby | size "}} }} Which led me to the (poor man's) Tag Cloud you see in the upper right corner. The good news? I was able to use _includes to reuse the category page for each category. See the source for this page [at github](http://github.com/mattscilipoti/mattscilipoti.github.com).
mattscilipoti/mattscilipoti.github.io
cbb8c3a243bb7a56db27bfc6eb52b857c4af771f
Github pages lost my format.
diff --git a/_posts/2010-09-17-jekyll-categories.md b/_posts/2010-09-17-jekyll-categories.md index 5e1d289..fc545cc 100644 --- a/_posts/2010-09-17-jekyll-categories.md +++ b/_posts/2010-09-17-jekyll-categories.md @@ -1,77 +1,81 @@ --- layout: post title: Categories for your GitHub Pages (Jekyll) categories: - code - github pages published: true --- {{ page.title }} ================ <p class='meta'> 17 Sept 2010 - Laurel, MD</p> You, like me, have a github pages powered blog. You, like me, are contemplating switching to WordPress for tags/categories. Fret no more. I added categories to my github pages powered blog today. You can too. Just assign a yaml list to categories in your page meta: categories: - ruby - rvm Listing and linking to them was harder than I expected. I was forced to create a page for each category that I wanted a list of posts for (code.html, ruby.html). +<p class="update">Update: I went to great pains to format this liquid code (within liquid). Even using the `--safe` argument on my jekyll server. But, it still formatted differently on github pages. I hope to figure out a workaround shortly. Until then, check out the source [at github](http://github.com/mattscilipoti/mattscilipoti.github.com). +</p> + + For each post, I expected to get a nice list of assigned categories using: - {{" {{ post.categories | array_to_sentence_string "}} }} + {{ " {{ post.categories | array_to_sentence_string " }} }} instead, I got: {{ post.categories | array_to_sentence_string }} Then I tried this (and variations): <div id="categories"> <h2>In this post:</h2> <ul class="categories"> - {{ "{% for category in post.categories " }} %} + {{" {% for category in post.categories "}} %} <li><a href="/{{"{{ category[0] "}} }}.html">{{" {{ category[0] "}} }}</a></li> {{" {% endfor"}} %} </ul> </div> Which rendered: <div id="categories"> <h2>In this post:</h2> <ul class="categories"> {% for category in post.categories %} <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> {% endfor %} </ul> </div> That's right. Nothing. `sites.categories` works nicely in that loop, but I wanted the categories for this post. <div id="categories"> <h2>In this site:</h2> <ul class="categories"> {% for category in site.categories %} <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> {% endfor %} </ul> </div> Armed with this knowledge, I set out to create a Tag Cloud. But, I could not find a way to get the count of posts for each category. I found an example on [litanyagainstfear.com](http://github.com/qrush/litanyagainstfear/blob/master/_layouts/default.html). Alas, it looks like you have to name each category explicitly to get the count of posts. {{" {{ site.categories.code | size "}} }} {{" {{ site.categories.ruby | size "}} }} Which led me to the (poor man's) Tag Cloud you see in the upper right corner. The good news? I was able to use _includes to reuse the category page for each category. See the source for this page [at github](http://github.com/mattscilipoti/mattscilipoti.github.com).
mattscilipoti/mattscilipoti.github.io
c3f1e0869f89e71689ab8452211b304cbbdb1a2e
New draft bunlder@global
diff --git a/_posts/[email protected] b/_posts/[email protected] new file mode 100644 index 0000000..f36b230 --- /dev/null +++ b/_posts/[email protected] @@ -0,0 +1,15 @@ +--- +layout: post +title: Embracing the Global Gemset +categories: +- ruby +- rvm +published: false +--- + +{{ page.title }} +================ + +{.meta} 17 Sept 2010 - Baltimore, MD + +Part One: Discussion \ No newline at end of file
mattscilipoti/mattscilipoti.github.io
56a131cdb2ed60557146145054bd0885dbf9266d
We have categories.
diff --git a/_includes/category_page.textile b/_includes/category_page.textile new file mode 100644 index 0000000..0f880cc --- /dev/null +++ b/_includes/category_page.textile @@ -0,0 +1,5 @@ +<ul id="archive"> + {% for post in category_posts %} + <li><a href="{{ post.url }}">{{ post.title }}</a><abbr>{{ post.date | date_to_string }}</abbr></li> + {% endfor %} +</ul> diff --git a/_layouts/default.html b/_layouts/default.html index a0c103a..ebe3323 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,109 +1,117 @@ <!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 type="text/javascript"> // from henrik.github.com google.load("jquery", "1"); google.load("jqueryui", "1"); </script> <script type="text/javascript"> 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> + + <section id="by_category" class="grid_2"> + <h2>"Tag Cloud"</h2> + <a href="/code.html">code ({{ site.categories.code | size }})</a> + <a href="/ruby.html">ruby ({{ site.categories.ruby | size }})</a> + </section> + {{ 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> <script type="text/javascript"> //<![CDATA[ $(document).ready(function() { $('p.update').effect("highlight", {}, 3000); }); //]]> </script> </body> </html> diff --git a/_layouts/static.html b/_layouts/static.html new file mode 100644 index 0000000..0e0cbf6 --- /dev/null +++ b/_layouts/static.html @@ -0,0 +1,10 @@ +--- +layout: default +--- +<div id="static"> + <h1>{{ page.title }}</h1> + {{ content }} + </ul> +</div> + + diff --git a/_posts/2010-09-14-I18n_Rails3_and_gems.textile b/_posts/2010-09-14-I18n_Rails3_and_gems.textile index d1e9ce7..ccde446 100644 --- a/_posts/2010-09-14-I18n_Rails3_and_gems.textile +++ b/_posts/2010-09-14-I18n_Rails3_and_gems.textile @@ -1,97 +1,102 @@ --- layout: post title: I18n for Rails 3 and common gems (Part One) published: true +categories: +- code +- I18n +- rails +- ruby --- h1. {{ page.title }} p(meta). 14 Sept 2010 - Baltimore, MD Part One: Discussion p(update). Update 1 (2010-09-16): "Entries to assist translators":#update_1 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)**. {% 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. h2. My expectations *1.* Items that can be internationalized should have smart defaults. I should not have to make an entry like: pre. labels: name: Name <a name="update_1"> p(update). *Update 2010-09-16:* My co-worker, Chris Cahoon, shares a great point. We probably *want* to make entries like `name: Name`, to assist translators. Allowing them to just go down the line translating each entry in the file. Otherwise, many items will not be translated. This makes tools like "Tolk":http://github.com/tokumine/tolk especially helpful. <a/> *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: pre. create_success: "%{model} created" create_fail: "The %{model} could not be created:" The specific: pre. tour_versions: create: success: Your tour was successfully published. *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! diff --git a/_posts/2010-09-17-jekyll-categories.md b/_posts/2010-09-17-jekyll-categories.md new file mode 100644 index 0000000..5e1d289 --- /dev/null +++ b/_posts/2010-09-17-jekyll-categories.md @@ -0,0 +1,77 @@ +--- +layout: post +title: Categories for your GitHub Pages (Jekyll) +categories: +- code +- github pages +published: true +--- + +{{ page.title }} +================ + +<p class='meta'> 17 Sept 2010 - Laurel, MD</p> + +You, like me, have a github pages powered blog. +You, like me, are contemplating switching to WordPress for tags/categories. +Fret no more. I added categories to my github pages powered blog today. +You can too. + +Just assign a yaml list to categories in your page meta: + categories: + - ruby + - rvm + + +Listing and linking to them was harder than I expected. +I was forced to create a page for each category that I wanted a list of posts for (code.html, ruby.html). + +For each post, I expected to get a nice list of assigned categories using: + {{" {{ post.categories | array_to_sentence_string "}} }} + instead, I got: + {{ post.categories | array_to_sentence_string }} + +Then I tried this (and variations): + + <div id="categories"> + <h2>In this post:</h2> + <ul class="categories"> + {{ "{% for category in post.categories " }} %} + <li><a href="/{{"{{ category[0] "}} }}.html">{{" {{ category[0] "}} }}</a></li> + {{" {% endfor"}} %} + </ul> + </div> + +Which rendered: + +<div id="categories"> + <h2>In this post:</h2> + <ul class="categories"> + {% for category in post.categories %} + <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> + {% endfor %} + </ul> +</div> + +That's right. Nothing. + +`sites.categories` works nicely in that loop, but I wanted the categories for this post. +<div id="categories"> + <h2>In this site:</h2> + <ul class="categories"> + {% for category in site.categories %} + <li><a href="/{{ category[0] }}.html">{{ category[0] }}</a></li> + {% endfor %} + </ul> +</div> + +Armed with this knowledge, I set out to create a Tag Cloud. But, I could not find a way to get the count of posts for each category. +I found an example on [litanyagainstfear.com](http://github.com/qrush/litanyagainstfear/blob/master/_layouts/default.html). Alas, it looks like you have to name each category explicitly to get the count of posts. + {{" {{ site.categories.code | size "}} }} + {{" {{ site.categories.ruby | size "}} }} + +Which led me to the (poor man's) Tag Cloud you see in the upper right corner. + +The good news? I was able to use _includes to reuse the category page for each category. + +See the source for this page [at github](http://github.com/mattscilipoti/mattscilipoti.github.com). diff --git a/code.textile b/code.textile new file mode 100644 index 0000000..4baad3b --- /dev/null +++ b/code.textile @@ -0,0 +1,7 @@ +--- +layout: static +title: code +--- + +{% assign category_posts = site.categories.code %} +{% include category_page.textile %} \ No newline at end of file diff --git a/css/screen.css b/css/screen.css index 6c4fa45..647a899 100644 --- a/css/screen.css +++ b/css/screen.css @@ -1,217 +1,221 @@ /*****************************************************************************/ /* /* 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; } + section#by_category { + float: right; + top: 100px; + } /*****************************************************************************/ /* /* 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; } diff --git a/ruby.textile b/ruby.textile new file mode 100644 index 0000000..3f827aa --- /dev/null +++ b/ruby.textile @@ -0,0 +1,6 @@ +--- +layout: static +title: ruby +--- +{% assign category_posts = site.categories.ruby %} +{% include category_page.textile %} \ No newline at end of file
mattscilipoti/mattscilipoti.github.io
33b93155365715d1130124d45cf77e232eefb52c
Uses rdiscount
diff --git a/blog.thor b/blog.thor index 2758eea..c570d49 100644 --- a/blog.thor +++ b/blog.thor @@ -1,9 +1,15 @@ class Blog < Thor desc "starts a server", "Starts a server on port:4000, automatically refreshes as site is changed" def server - cmd = 'jekyll --pygments --server --auto' + cmd = 'jekyll --pygments --server --auto --safe --rdiscount --lsi' + exec cmd + end + + desc "watches & generates", "Watches the site, automatically refreshes as site is changed" + def watch + cmd = 'jekyll --pygments --auto --rdiscount' exec cmd end end \ No newline at end of file